Flask

  1. Import Flask: Import the Flask class from the flask module.
from flask import Flask
  1. Create an instance of the Flask class: Create a Flask application instance.
app = Flask(__name__)
  1. Define a route and its corresponding function: Use the @app.route decorator to specify a route and define a function that will be executed when the route is accessed.
@app.route('/')
def home():
    return 'Hello, World!'
  1. Run the Flask application: Use the app.run() method to start the development server.
if __name__ == '__main__':
    app.run(debug=True)
  1. Save the file and execute: Save the Python script and run it to start the Flask development server.
python filename.py
  1. Access the application: Open a web browser and navigate to the specified address (usually http://127.0.0.1:5000/ or http://localhost:5000/) to see the "Hello, World!" message.

  2. Dynamic Routes: Define dynamic routes by adding variable parts to the URL using <variable_type:variable_name> syntax.

@app.route('/user/<username>')
def show_user_profile(username):
    return f'User {username}'
  1. HTTP Methods: Specify allowed HTTP methods for a route using the methods parameter in the @app.route decorator.
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # Handle login logic for POST request
        pass
    else:
        # Render login form for GET request
        pass
  1. Templates: Render HTML templates using the render_template function.
from flask import render_template

@app.route('/template_example')
def template_example():
    return render_template('index.html', title='Flask Template Example', content='This is content.')
  1. Static Files: Serve static files (e.g., CSS, JavaScript) using the url_for function in templates.
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
  1. Redirects: Use the redirect function to redirect users to a different URL.
from flask import redirect, url_for

@app.route('/redirect_example')
def redirect_example():
    return redirect(url_for('home'))
  1. Request and Form Data: Access request and form data using the request object.
from flask import request

@app.route('/form_example', methods=['POST'])
def form_example():
    username = request.form['username']
    password = request.form['password']
    return f'Username: {username}, Password: {password}'