How to use try except in python

Python’s exception handling system lets you write code that can deal with unexpected errors

The structure

try:
    # Code that might have problems
except ExceptionType as e:
    # What to do if an error occurs
else:
    # Runs if there's no error
finally:
    # Cleanup code - always runs

Explanation of the structure:

  • try: “This is where we put the code that might cause problems.”
  • except: “If an error happens in the ‘try’ block, the code in ‘except’ tells Python what to do.”
  • else: “This part runs only if there’s no error in the ‘try’ block.”
  • finally: “This code runs no matter what, error or not. It’s great for cleaning up things like closing files.”

The try…except structure in Python aims to prevent programs from crashing by providing a way to handle exceptions. This allows you to continue execution or provide meaningful error messages instead of the program terminating unexpectedly.




import math

def calculate_square_root(num):
	try:
		result = math.sqrt(num)
	except ValueError as ve:
		print(f"Error: {ve}")
	else:
		print(f"The square root of {num} is {result}.")

# Test the function
calculate_square_root(4)    # This will print "The square root of 4 is 2.0"
calculate_square_root(-4)    # This will print "Error: math domain error"




Python for Beginners: Turning Numbers into Text (String Conversion)

Converting to Text with python built in str() Function

Its simple and easy

We can convert number to string like this . here x=10 , where the value of x is a number when we write x=str(x) it becomes a string. Thats all!

x=10

x=str(x)

So we can convert number to string with str()



number = 2  # For example our number is 2

# You can  Check the data type of 'number' with type()
print(type(number))  # Output:  

# We added number+ number so we can show the simple calculation. To show the difference between result with number and string
print(number + number)  # Output: 4 

# NOW CONVERT 'NUMBER' FROM AN INTEGER TO A STRING
number = str(number)  

# Check the new data type As it successfully converted to string
print(type(number))  # Output: 

# And now if we ad number+number it will not calculate instead it will place the character beside the character 
print(number + number)  # Output: 22





Also we can convert string to number! with int() and float()




number='2'  # This time we added the number inside quotation. so it becomes string
print(number)

print(number+number)
# It will print 22 


#Use int() to integer and float() to convert to float
number= int(number)

print(number+number)
# it will print 4 as it converted to integer number




Building a Simple and Secure API with Python Flask

Server-Side: Flask API Development

We will build a simple API that will tell the current time. And then add more feature.

The explanation and the code

The code



from flask import Flask, request, jsonify
from datetime import datetime

app = Flask(__name__) 

# Define a route to get the current time
@app.route('/get-current-time', methods=['POST'])
def get_current_time():
    # Validate the API key
    api_key = request.headers.get('Authorization')
    if api_key != '12345': 
        return jsonify({"error": "Unauthorized"}), 401 

    # Get and format the current time
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    # Return the time in JSON format
    return jsonify({"currentTime": current_time}), 200 

if __name__ == '__main__':
    app.run(port=5000, debug=True) 





Route Definition: Use the @app.route() decorator to define the URL path (/get-current-time) for your API endpoint. This specific endpoint is configured to handle POST requests.
Endpoint Logic: Inside the get_current_time() function (which handles requests to your endpoint), retrieve the API key from the incoming request's headers
Authorization Check: Implement a security measure by verifying that the provided API key matches the correct value. If the key is invalid, return a JSON error response with a 401 (Unauthorized) HTTP status code.

Response Preparation: Construct a JSON dictionary (response_data) to hold the current time value.

Client-Side: Calling the API




import requests

url = 'http://localhost:5000/get-current-time'
api_key = '12345'

headers = {
  'Authorization': api_key,
  'Content-Type': 'application/json',
}

try:
  response = requests.post(url, headers=headers)

  if response.status_code == 200:
    response_data = response.json()
    current_time = response_data.get('currentTime')
    print("Current time received from the API:", current_time)
  else:
    print("Error:", response.status_code, response.text)  # Include response text
except requests.exceptions.RequestException as e:
  print("Error On request:", e)





In the client side we will use requests module to retrieve the time with the API request.

requests module is not a built-in module in Python. So if you have not installed you need to install it first.

pip install requests

The code and the explanations

url = 'http://localhost:5000/get-current-time'
api_key = 'oCZ2DNROIRSyL058'

headers = {
  'Authorization': api_key,
  'Content-Type': 'application/json',
}

Set API URL and Key: Configure the address of your API endpoint and your valid API key.
Create Headers: Build a dictionary containing your API key for authorization and the content type (application/json).


Testing the code

  • First we need to run the code we have add in the top for server side. It will run a server on local host http://localhost:5000/
  • Then we need to run another python script that is written for the client side. That’s all! It will print the time which comes from the server.

This was just for essential approach. We can make it more practical. For example we need check if a number is prime or not but we do not want to write the core functionality in our client side code. So we can write the API for it .. And call when ever we need and wherever we are!

We will use Miller-Rabin Primality Test for more efficiency to check a number is prime or not.

The code that checks the number is prime or not




import random

def is_prime_miller_rabin(n, iterations=40):
    """Performs the Miller-Rabin Primality Test to determine if a number is likely prime.

    This test is probabilistic, meaning it's highly accurate but not foolproof.
    Increasing the 'iterations' value improves the accuracy of the result.

    Args:
        n: The integer to test for primality.
        iterations: Number of test rounds to perform (default is 40).

    Returns:
        True if the number is likely prime, False if it's not.
    """

    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0:
        return False

    # Decompose n-1 into the form 2^r * d
    d = n - 1
    r = 0
    while d % 2 == 0:
        d //= 2
        r += 1

    # Witness loop
    for _ in range(iterations):
        a = random.randint(2, n - 2)
        x = pow(a, d, n)
        if x == 1 or x == n - 1:
            continue
        for _ in range(r - 1):
            x = pow(x, 2, n)
            if x == n - 1:
                break
        else:
            return False
    return True



# Test the code
number_to_test = int(input("Enter a number to check for primality: "))
if is_prime_miller_rabin(number_to_test):
    print(f"{number_to_test} is likely a prime number.")
else:
    print(f"{number_to_test} is not a prime number.") 





If you are interested in prime numbers you also can read this article

Implemented In The server code( API)




from flask import Flask, request, jsonify
from datetime import datetime
import random

app = Flask(__name__) 

def is_prime_miller_rabin(n, iterations=40):
    """Performs the Miller-Rabin Primality Test to determine if a number is likely prime."""
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0:
        return False

    # Decompose n-1 into the form 2^r * d
    d = n - 1
    r = 0
    while d % 2 == 0:
        d //= 2
        r += 1

    # Witness loop
    for _ in range(iterations):
        a = random.randint(2, n - 2)
        x = pow(a, d, n)
        if x == 1 or x == n - 1:
            continue
        for _ in range(r - 1):
            x = pow(x, 2, n)
            if x == n - 1:
                break
        else:
            return False
    return True

# Define a route to check if a number is prime
@app.route('/check-prime', methods=['POST'])
def check_prime():
    # Validate the API key
    api_key = request.headers.get('Authorization')
    if api_key != '12345': 
        return jsonify({"error": "Unauthorized"}), 401 

    # Get the number from the request
    data = request.get_json()
    number_to_test = data.get('number')

    # Check if the number is prime
    is_prime = is_prime_miller_rabin(number_to_test)

    # Return the result
    return jsonify({"number": number_to_test, "isPrime": is_prime}), 200 

if __name__ == '__main__':
    app.run(port=5000, debug=True) 






Calling from the client side




import requests

url = 'http://127.0.0.1:5000/check-prime'
headers = {'Authorization': '12345'}
data = {'number': 172983479832623897492387592384682937659382477}

response = requests.post(url, json=data, headers=headers)
print(response.json())






Limit the API calling: Setting the Rate-Limiting

We can specifically set the daily limit or hourly limit for specific user to save the computation limits. For this we will use a wonderful library apscheduler . I first used this library on video calling project for user data management scheduler.

Install the library with

pip install apscheduler

Now our code will look like this




from flask import Flask, request, jsonify
from datetime import datetime, timedelta
import random
from apscheduler.schedulers.background import BackgroundScheduler

app = Flask(__name__)

def is_prime_miller_rabin(n, iterations=40):
    """Performs the Miller-Rabin Primality Test to determine if a number is likely prime."""
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0:
        return False

    # Decompose n-1 into the form 2^r * d
    d = n - 1
    r = 0
    while d % 2 == 0:
        d //= 2
        r += 1

    # Witness loop
    for _ in range(iterations):
        a = random.randint(2, n - 2)
        x = pow(a, d, n)
        if x == 1 or x == n - 1:
            continue
        for _ in range(r - 1):
            x = pow(x, 2, n)
            if x == n - 1:
                break
        else:
            return False
    return True

# Initialize the scheduler
scheduler = BackgroundScheduler()

# Define the users and their limits
users = {"12345": {"limit": 5}, "45365": {"limit": 5}}

# Function to reset the limits
def reset_limits():
    print("Resetting limits...")
    for user_info in users.values():
        user_info["limit"] = 5

# Schedule the job to run every 24 hours
scheduler.add_job(reset_limits, 'interval', hours=24)

# Start the scheduler
scheduler.start()

# Define a route to check if a number is prime
@app.route('/check-prime', methods=['POST'])
def check_prime():
    # Validate the API key
    api_key = request.headers.get('Authorization')
    if api_key not in users:
        return jsonify({"error": "Unauthorized"}), 401

    # Get the number from the request
    limit = users[api_key]['limit']
    if not limit == 0:
        data = request.get_json()
        number_to_test = data.get('number')

        # Check if the number is prime
        is_prime = is_prime_miller_rabin(number_to_test)

        # Update the request limit
        users[api_key]['limit'] -= 1

        # Return the result
        return jsonify({"number": number_to_test, "isPrime": is_prime}), 200
    else:
        return jsonify({"error": "Request limit exceeded. Please try again later."}), 429

if __name__ == '__main__':
    app.run(port=5000, debug=True)






Client Side will be unchanged!




import requests

url = 'http://127.0.0.1:5000/check-prime'
headers = {'Authorization': '12345'}
data = {'number': 172983479832623897492387592384682937659382477}

response = requests.post(url, json=data, headers=headers)
print(response.json())





Enhance Security Level

For demonstration purposes, this example stores the API key directly in the code. In production environments, always store API keys securely in a database with hashing to protect sensitive information.

With timestamp make the API key ultimately unique when generate new key for user




import secrets
import string
import time

def generate_unique_api_key(length=32):
    """Generate a unique API key using a combination of random characters and timestamp."""
    timestamp = str(int(time.time()))  # Get current timestamp as a string
    alphabet = string.ascii_letters + string.digits
    random_part = ''.join(secrets.choice(alphabet) for _ in range(length - len(timestamp)))
    key = timestamp + random_part
    return key

# Generate a unique API key of length 32
api_key = generate_unique_api_key()
print("unique API key:", api_key)






For You

For more easy to use, I added the code in the github repository

Using Environment Variables in Python: Easy Quick Guide

What are environment variables?

Think of them like secret notes your programs can read. These notes hold important information like:

  • Website addresses for connecting to databases
  • Special settings to make your app run the way you want
  • Secret passwords for extra security

Why are environment variables important?

  • Make your app adaptable: Change settings without changing the actual code.
  • Simplify updates: All your settings are in one place.
  • Boost security: Keep your passwords and sensitive data hidden.
  • Smooth deployments: Run the same app in different environments (like testing vs. live website)

Why Use Environment Variables for Application Security and Flexibility?

Sensitive information like API keys and encryption keys are the essential for modern applications. Adding them directly within your code introduces several risks:

Security Vulnerabilities: Code must be frequently updated and shared across development teams. This exposes sensitive credentials within the code itself.
Open-Source Challenges: If you plan to make your code open-source, you can’t include these secrets without putting your application’s security at risk.


Environment variables offer a more secure and flexible way to handle this:

Isolated Storage: Environment variables reside outside of your source code, minimizing exposure.
Development Agility: Developers can work with the code without accessing the actual secret values.
Environment-Specific Settings: You can easily tailor values (keys, database URLs, etc.) to different environments like development, testing, and production.

  • Environment variables enhance application security.
  • They promote open-source initiatives.
  • They make your codebase more adaptable.

How to use it in python?

For example we have a location API key for generating users data from the IP address

this is the example without environment variable. The key is directly included in the code




import requests

LOCATION_API_KEY = "1234567890"

def get_location(ip_address):
	url = f"https://example.com/{ip_address}/json?token={LOCATION_API_KEY}"
	response = requests.get(url)
	data = response.json()
	country = data.get("country")
	print(country)


    
    

In the example we directly included the key with the source code. The API have call limits. So if it compromised we may have to pay more.

So we can store the key with this command

export LOCATION_API_KEY="1234567890"

We can later access the variable with this command

echo $LOCATION_API_KEY

Implement in python code.

In the code we get the variable securely with os.environ.get(‘LOCATION_API_KEY’) so if even we share the code we can keep the API key secret. Not only API key , you can store password and other sensitive and essential variables




import os
import requests

# Retrieve the LOCATION_API_KEY from environment variables
LOCATION_API_KEY = os.environ.get('LOCATION_API_KEY')

def get_location(ip_address):
	url = f"https://example.com/{ip_address}/json?token={LOCATION_API_KEY}"
	response = requests.get(url)
	data = response.json()
	country = data.get("country")
	print(country)


    
    


We can Store Environment Variable from python code directly




import os

# Set the LOCATION_API_KEY environment variable
os.environ['LOCATION_API_KEY'] = '1234567890'

# Store other essential code like
os.environ['ADMIN_PASSWORD'] = '123456789101112'


# Retrieve the variable when needed
admin_password = os.environ.get('ADMIN_PASSWORD')
print(admin_password)



Flask File Handling Made Easy: Upload and Download Files

Very basic example

code_features

  • Show the user a file upload page
  • Store the uploaded file in the server

This is our first example… Run this code first. Then read the step by step explanation. That will be more effective. Because this tutorial is all about practice. In this article covers simple upload, upload to database, securing the upload by adding limiting file extension and adding download link… Run the example first then read the article…

First Example: Simple Upload

  • copy the example code and run first.
  • The client side HTML is directly added this in python script instead of template for simplicity.
  • It will run on http://127.0.0.1:5000. open that in browser and upload and submit the file, you can get the upload file in the same directory where your python script is.
  • In the next examples, we will store into a folder . And Later into a database.


from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def upload_file():
    return '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>
<body>
    <h2>Upload a File</h2>
    <form action="/uploader" method="POST" enctype="multipart/form-data">
        <input type="file" name="file" />
        <input type="submit"/>
    </form>
</body>
</html>
    '''

@app.route('/uploader', methods=['POST'])
def upload_file_post():
    if request.method == 'POST':
        f = request.files['file']
        f.save(f.filename)
        return 'successfully uploaded file'

if __name__ == '__main__':
    app.run(debug=True)

    
    
    

Step by step explanation

  • from flask import Flask, render_template, request
    Import the necessary module

Understanding app = Flask(__name__) for Flask Web Development

When you write app = Flask(__name__), you're creating the core Flask application object. This line is essential in building web applications with Flask. Here's a breakdown of its importance:

Resource Location: The __name__ variable instructs Flask where to locate resources crucial for your web app, such as:
Templates: HTML files that define the structure and appearance of your website.
Static Files: Supporting files like CSS (stylesheets), JavaScript, and images.
Flexible Configurations: Using __name__ allows Flask to adapt configurations based on your development environment (local testing vs. live deployment).

The page where user can upload the file



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>
<body>
    <h2>Upload a File</h2>
    <form action="/uploader" method="POST" enctype="multipart/form-data">
        <input type="file" name="file" />
        <input type="submit"/>
    </form>
</body>
</html>


    

    






We can add this in templates folder in flask as upload-file.html other names. for simplicity directly included in the python script.
<form action=”/uploader” method=”POST” enctype=”multipart/form-data”>

This HTML file upload form provide a structured mechanism for users to submit files to a web server.

action=”/uploader” : This attribute acts as the destination address for the uploaded file. It directs the web server to a specific processing location (in this case, the “/uploader” route).


method=”POST” : This attribute specifies a secure transfer method. The “POST” method embeds the file within the body of the HTTP request, enhancing data protection.

enctype=”multipart/form-data” : This attribute is essential for file uploads. It establishes an encoding format that seamlessly transmits both files and standard text-based form data.

This code just upload the file in the server and store the in the same directory. In the next example We will learn how to store the file on specific directory.




@app.route('/uploader', methods=['POST'])
def upload_file_post():
    if request.method == 'POST':
        f = request.files['file']
        f.save(f.filename)
        return 'successfully uploaded file'

    
    


Second Example: Storing the uploaded files in a specific folder



from flask import Flask, render_template, request
import os

app = Flask(__name__)

UPLOAD_FOLDER = 'user-uploads'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/')
def upload_file():
    return '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>
<body>
    <h2>Upload a File</h2>
    <form action="/uploader" method="POST" enctype="multipart/form-data">
        <input type="file" name="file" />
        <input type="submit"/>
    </form>
</body>
</html>
    '''

@app.route('/uploader', methods=['POST'])
def upload_file_post():
    if request.method == 'POST':
        f = request.files['file']
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], f.filename)
        f.save(file_path)
        return 'File uploaded successfully'

if __name__ == '__main__':
    app.run(debug=True)



    
    
    

We have created a folder named ‘upload files’ . If not created the code wil automatically create the folder



import os
UPLOAD_FOLDER = 'user-uploads'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

    
    

We applied python os module to create the folder. 

import os

Integrates the 'os' module, enabling operating system's file management capabilities.



UPLOAD_FOLDER = 'uploads'
keyword-relevant name ('uploads') for the directory where uploaded files will be stored.

if not os.path.exists(UPLOAD_FOLDER):
Verifies the existence of the 'uploads' directory.

os.makedirs(UPLOAD_FOLDER)
If the 'uploads' directory is absent, this command generates it along with any necessary subdirectories.


app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
Define the configuration variable 
Imagine UPLOAD_FOLDER as a designated storage location within your Flask application for uploaded files. The line app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER does the following:

Assigns a Name: It gives this storage location a clear label, 'UPLOAD_FOLDER'.
Defines a Path: It links this label to the actual folder path on your system where uploaded files will be saved.

In the next example we will learn to store the uploaded files in the database.


Third Example: Storing the uploaded files in a database

Storing user data securely and effectively is crucial for many applications. A database is the optimal solution for long-term storage. SQL databases like SQLite, PostgreSQL, and MySQL are excellent options, offering varying features to suit your needs.

For enhanced security and flexibility, consider using an object-relational mapper (ORM). ORMs streamline database interactions within your code. In this example, we’ll demonstrate how to utilize the Peewee ORM with Python’s built-in SQLite database. This approach allows for effortless migration to other SQL databases in the future.

Install peewee orm

pip install peewee

And now copy , run and test the code..



from flask import Flask, render_template, request
from peewee import SqliteDatabase, Model, CharField
from werkzeug.utils import secure_filename
import os

app = Flask(__name__)

# SQLite database initialization
db = SqliteDatabase('uploads.db')

# Define the model for file uploads
class Upload(Model):
    filename = CharField()
    filepath = CharField()

    class Meta:
        database = db

# Create tables if they don't exist
db.connect()
db.create_tables([Upload], safe=True)
db.close()

@app.route('/')
def upload_file():
    return '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>
<body>
    <h2>Upload a File</h2>
    <form action="/uploader" method="POST" enctype="multipart/form-data">
        <input type="file" name="file" />
        <input type="submit"/>
    </form>
</body>
</html>
    '''

# Save file and file information to database
@app.route('/uploader', methods=['POST'])
def upload_file_post():
    if request.method == 'POST':
        f = request.files['file']
        if f:
            filename = secure_filename(f.filename)
            file_path = os.path.join('upload files', filename)
            f.save(file_path)

            # Save file info to database
            Upload.create(filename=filename, filepath=file_path)

            return 'File uploaded successfully'

if __name__ == '__main__':
    app.run(debug=True)


    
    
    

Fourth Example: Securing the The file upload by limiting the upload extensions

Though we can tell the user which type of files to upload. But we can not relay only on that. So for more security and specially server and other users security we must limit the upload files extensions. which files are allowed by the server.



import os
from flask import Flask, flash, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = 'user-uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp'}

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = 'your_secret_key_here'


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # If the user does not select a file, the browser submits an
        # empty file without a filename.
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            flash('File uploaded successfully')
            return redirect(url_for('upload_file'))
        else:
            flash('Invalid file type. Allowed types are: png, jpg, jpeg, gif, bmp')
            return redirect(request.url)
    return render_template('upload.html')


if __name__ == '__main__':
    app.run(debug=True)



    
    
    

Fifth Example: Create link to the file and add downloading option

In this example we will show the download link to the user and make the filename very unique.
In the previous examples we directly added html code in the python script. When application becomes larger and complex its essential to handle everything separately. In this example we will use flask render_temple to render the html

So this example structure

flask_app/
│
├── app.py
│
└── templates/
    └── upload-page.html

Copy, run and test the code.



import os
from flask import Flask, flash, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = 'user-uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp'}

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        
        file = request.files['file']
        
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            flash('File uploaded successfully')
            return redirect(url_for('upload_file'))
        
        flash('Invalid file type. Allowed types are: png, jpg, jpeg, gif, bmp')
        return redirect(request.url)

    return render_template('upload-page.html')


if __name__ == '__main__':
    app.run(debug=True)



    
    
    

The upload-page.html




<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>File Upload</title>
</head>
<body>
	<h2>Upload a File</h2>
	<form action="/" method="POST" enctype="multipart/form-data">
		<input type="file" name="file" />
		<input type="submit"/>
	</form>
	{% with messages = get_flashed_messages() %}
		{% if messages %}
			<ul>
			{% for message in messages %}
				<li>{{ message }}</li>
			{% endfor %}
			</ul>
		{% endif %}
	{% endwith %}
</body>
</html>



    
    
    

In the example we did not use database we stored the uploaded data in a folder. . But in previous example we have the database example( Third example) ..Then why not apply our previous learning experience of database here. Try it by yourself.

How to use python enumerate

Enumerate helps to track  the index and element. Though we can gain the same feature using for loop but enumerate    makes the code more readable

Imagine we have a list of colors

color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown','Cyan']

For tracking both the index and corresponding element we can write this simple code

An Example Without Enumerate



color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']

#Without enumerate Manually track index using a counter variable
index = 0
for color in color_names:
    print(f"Color {index}: {color}")
    index += 1


  
  


We can achieve the same thing with Enumerate. Best thing is it increase the readability and you do not have to track the indexing manually.

The Same Example With Enumerate



color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown','Cyan']
for index, color in enumerate(color_names):
  print(f"Color {index}: {color}")


  
  

This will show the index color name

Color 0: Red
Color 1: Orange
Color 2: Yellow
Color 3: Green
Color 4: Blue
Color 5: Purple
Color 6: Pink
Color 7: Brown
Color 8: Cyan

There are some more details example where you can enumerate. Also I have embedded an online browser based python interpreter( at the end of the article) so you can test the code here instantly


Apply Condition to Access The Index And Value efficiently

In Python programming, accessing both the index and the corresponding value from a list simultaneously, especially with certain conditions, is a common task. Get both the index and value from a Python list more easier with enumerate.



color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']
for index, color in enumerate(color_names):
    if index % 2 == 0:
        print(f"Color {index}: {color}")


  
  
Color 0: Red
Color 2: Yellow
Color 4: Blue
Color 6: Pink
Color 8: Cyan


Update Elements of a List

Updating list items by their index offers a flexible way to make changes to your data. In the example We changed all the color names to uppercase.



color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']
for index, color in enumerate(color_names):
    if index % 2 != 0:
        color_names[index] = color.upper()
print(color_names)


  
  
['Red', 'ORANGE', 'Yellow', 'GREEN', 'Blue', 'PURPLE', 'Pink', 'BROWN', 'Cyan']


Creating python Dictionaries

Transform lists into dictionaries for faster data lookup and better organization. Easily organize and find your data by turning lists into dictionaries using enumerate.



color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']
color_dict = {index: color for index, color in enumerate(color_names)}
print(color_dict)


  
  
{0: 'Red', 1: 'Orange', 2: 'Yellow', 3: 'Green', 4: 'Blue', 5: 'Purple', 6: 'Pink', 7: 'Brown', 8: 'Cyan'}


Accessing Items from Two Lists Together

Process information from several lists at once for more efficient programming.



color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']
rgb_values = [(255, 0, 0), (255, 165, 0), (255, 255, 0), (0, 128, 0), (0, 0, 255), (128, 0, 128), (255, 192, 203), (165, 42, 42), (0, 255, 255)]

for index, (color, rgb) in enumerate(zip(color_names, rgb_values)):
    print(f"Color {index}: {color}, RGB: {rgb}")


for index, color in enumerate(random_color_names):
    print(f"Color {index}: {color}")


  
  
Color 1: Red, RGB: (255, 0, 0)
Color 2: Orange, RGB: (255, 165, 0)
Color 3: Yellow, RGB: (255, 255, 0)
Color 4: Green, RGB: (0, 128, 0)
Color 5: Blue, RGB: (0, 0, 255)
Color 6: Purple, RGB: (128, 0, 128)
Color 7: Pink, RGB: (255, 192, 203)
Color 8: Brown, RGB: (165, 42, 42)
Color 9: Cyan, RGB: (0, 255, 255)


Indexed List and Create Tuples

Python's enumerate function typically starts counting at 0 (like most programming tools). But, by setting start=1, we can make our lists match how people normally count, making them easier to read.

We're creating indexed_colors, a list of tuples where each tuple holds an index (starting from 1) and its corresponding color. Tuples are immutable (meaning their contents can't change), ensuring our color references stay organized.



color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']
indexed_colors = list(enumerate(color_names, start=1))
print(indexed_colors)


  
  
[(1, 'Red'), (2, 'Orange'), (3, 'Yellow'), (4, 'Green'), (5, 'Blue'), (6, 'Purple'), (7, 'Pink'), (8, 'Brown'), (9, 'Cyan')]


Apply Condition to skip the elements.

Skip items when looping if they meet specific conditions. This makes your code more adaptable



color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']
for index, color in enumerate(color_names):
    if 'e' in color:
        continue
    print(f"Color {index}: {color}")


  
  

Color 6: Pink
Color 7: Brown
Color 8: Cyan


Working With Files

Working with files? Python's enumerate function makes it easy to read and process each line, keeping your code clean and efficient.



with open('text.txt', 'r') as file:
    for line_number, line_content in enumerate(file, start=1):
        print(f"Line {line_number}: {line_content.strip()}")


  
  


Working with List Comprehensions

List comprehensions are a short and clear way to create new lists in Python. They let you quickly transform one list into another. You can use the enumerate() function with list comprehensions to easily add indexes to your new lists. This makes your code easier to read and write.



color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']
indexed_colors = [(index, color) for index, color in enumerate(color_names)]
print(indexed_colors)


  
  
[(0, 'Red'), (1, 'Orange'), (2, 'Yellow'), (3, 'Green'), (4, 'Blue'), (5, 'Purple'), (6, 'Pink'), (7, 'Brown'), (8, 'Cyan')]


Reverse a List

To reverse a list and enumerate its elements simultaneously, Python offers an elegant solution: combine enumerate(), reversed(), and list comprehension



color_names = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Pink', 'Brown', 'Cyan']
reversed_colors = [(index, color) for index, color in enumerate(reversed(color_names))]
print(reversed_colors)


  
  
[(0, 'Cyan'), (1, 'Brown'), (2, 'Pink'), (3, 'Purple'), (4, 'Blue'), (5, 'Green'), (6, 'Yellow'), (7, 'Orange'), (8, 'Red')]


Practice or Test the code here. Run python code Directly In the browser

How To Generate URL And Route Dynamically In Flask

We can set route dynamically instead of fixed route.

For example In the pre-determined route links generate like this example.com/users/profile

In the dynamically gendered route will be like this  example.com/users/custom_profile_name


We will use

@app.route('/<username>')

The code will be like this

@app.route('/<username>')
def show_profile(username):
    return username

We can use anything in the <username> here

So if we  load page like example.com/anything_here

It will show the route. This is the complete example. Copy and try and customize the code by yourself.



from flask import Flask, url_for

app = Flask(__name__)

@app.route('/<username>')
def show_profile(username):
    return username

@app.route('/')
def index():
    example_link = url_for('show_profile', username='example')
    return f"You are on index route. Go to <a href='{example_link}'>/example</a> for an example."

if __name__ == '__main__':
    app.run(debug=True)

  
  

Python Flask : Starter Automated Template

When starting new project again, Some common structure needed to be written again and again. So I wrote a program nearly three years (2021) ago to Get Everything ready on one script. Here is the python script that makes everything ready

Here is is the revised version of the code

The Program Automatically generates basic scripts and files and necessary folder.

Copy, run the script And adjust the script on your necessary.


import os

x = os.getcwd()

os.mkdir("templates")
os.mkdir(os.path.join(x, "templates", "layouts"))
os.mkdir("static")
os.mkdir(os.path.join(x, "static", "css"))
os.mkdir(os.path.join(x, "static", "js"))
os.mkdir(os.path.join(x, "static", "img"))

app_w = """from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def home():
	title = "Home"
	return render_template('index.html', title=title)
"""

with open("app.py", "w+") as f:
	f.write(app_w)

css = """
body {
	background-color: #ccebff;
}
a, h1, h2, p {
	color: #3377ba8;
}
"""

with open(os.path.join(x, "static", "css", "main.css"), "w+") as f:
	f.write(css)

main = """<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ title }}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
</head>
<body>
{% block content %}
{% endblock %}
<footer>
<ul>
	<li> <a href="/">Home</a></li>
</ul>
&copy; 2021 Mahid
</footer>
</body>
</html>
"""

with open(os.path.join(x, "templates", "layouts", "main.html"), "w+") as f:
	f.write(main)

index = """{% extends "layouts/main.html" %}
{% block content %}
<h1>{{ title }}</h1>
<p>Hello world</p>
{% endblock %}
"""

with open(os.path.join(x, "templates", "index.html"), "w+") as f:
	f.write(index)