Django & Flask Topic
1. Flask Introduction
What is Flask?
Flask is a lightweight micro-framework for building web applications in Python. "Micro" doesn't mean it's lacking in functionality, but rather that its core is simple and extensible. It provides you with the essential tools to get a web server up and running with minimal boilerplate code.
Key Philosophy:
-
Simplicity: You start with a single file and add only what you need.
-
Flexibility: You have the freedom to choose how you want to implement things like databases (SQLAlchemy, Peewee, etc.) and authentication.
-
Explicit is Better than Implicit: You generally write out the connections between components, making it clear how your app works.
A "Hello, World!" Application in Flask:
python
# app.py
from flask import Flask
# 1. Create an instance of the Flask class.
# __name__ helps Flask find static files and templates.
app = Flask(__name__)
# 2. Use a route decorator to bind a URL to a function.
@app.route('/')
def hello_world():
# 3. The function returns the response to be displayed in the browser.
return '<h1>Hello, World!</h1>'
# Run the application if this script is executed directly.
if __name__ == '__main__':
app.run(debug=True)
To run it: python app.py. Then visit http://127.0.0.1:5000 in your browser.
2. Routing and HTTP Methods
A. Mapping URLs with @app.route
Routing is the mechanism of matching a URL pattern to the Python function that will handle the logic for that page.
Basic Routing:
The @app.route('/some/url') decorator is placed directly above a Python function. This tells Flask: "When a user requests this URL, execute this function."
python
@app.route('/')
def home():
return 'This is the Home Page.'
@app.route('/about')
def about():
return 'This is the About Page.'
Visiting / executes home().
Visiting /about executes about().
Dynamic Routing (Variable Rules):
You can make parts of the URL dynamic, which are then passed as arguments to your function.
python
@app.route('/user/<username>')
def show_user_profile(username):
# The `username` part of the URL is passed to the function.
return f'Hello, {username}!'
@app.route('/post/<int:post_id>')
def show_post(post_id):
# You can use converters like <int:post_id> to restrict the type.
# This will only match an integer. Other converters: string, float, path, uuid.
return f'This is post #{post_id}.'
B. Handling HTTP Methods (GET, POST)
By default, a route only answers to GET requests. To handle other methods like POST (used when submitting forms), you must specify them explicitly.
Common HTTP Methods:
-
GET: Retrieve data from the server. (Default)
-
POST: Send data to the server to create a new resource (e.g., submit a form, upload a file).
-
PUT: Send data to replace an existing resource.
-
DELETE: Request to delete a resource.
Example: Handling a Login Form (GET & POST)
python
from flask import request, render_template
# Allow both GET and POST methods for this route.
@app.route('/login', methods=['GET', 'POST'])
def login():
# Check which method was used for the request.
if request.method == 'POST':
# This block runs if the form was submitted (POST).
username = request.form['username']
password = request.form['password']
# ... (Logic to check username/password) ...
return f'Logging in user: {username}'
else:
# This block runs if the page is simply loaded (GET).
# Show the empty login form.
return render_template('login.html')
Explanation:
-
When you first go to
/loginin your browser, it's a GET request. Theelsebranch runs, showing the form. -
When you fill out the form and click "Submit", the browser sends a POST request to the same
/loginURL. -
This time, the
if request.method == 'POST'branch is true, and the code processes the submitted data (accessible viarequest.form).
Django Connection: The Direct Translation
The concepts of routing and views are fundamental to all web frameworks. Here's how Flask's concepts map directly to Django.
1. Routing (urls.py vs @app.route)
-
Flask: Uses decorators directly on the view function to define routes.
python
# Flask (in app.py) @app.route('/about') def about(): return 'About Page' -
Django: Uses a dedicated
urls.pyfile to create a mapping between URL patterns and view functions. This is a more centralized and explicit approach.my_project/urls.pypython
from django.urls import path from . import views # Import your view functions urlpatterns = [ path('about/', views.about, name='about'), ]my_project/views.pypython
from django.http import HttpResponse # The view function (no decorator needed here) def about(request): return HttpResponse('About Page')
Connection: Both frameworks have a mechanism to say "URL X should be handled by Python function Y." Flask does it with a decorator, Django does it with a configuration list in urls.py.
2. Handling HTTP Methods
-
Flask: You check the
request.methodinside a single view function that handles multiple methods.python
# Flask @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': # Handle POST else: # Handle GET -
Django: A common convention is to write separate view functions or use class-based views. A simple function-based approach looks very similar.
views.pypython
from django.http import HttpResponse from django.shortcuts import render def login(request): if request.method == 'POST': # Handle POST (data is in request.POST) username = request.POST['username'] return HttpResponse(f'Logging in {username}') else: # Handle GET return render(request, 'login.html')urls.py(stays the same, no need to specify methods)python
urlpatterns = [ path('login/', views.login, name='login'), ]
Connection: Both use the request object to determine the HTTP method and access submitted data (request.form in Flask, request.POST in Django). The logic of "if POST, do this; else, do that" is identical.
Summary: What to Learn
-
Flask's
@app.route: Understand how it binds a URL to a Python function. Practice with static and dynamic URLs. -
HTTP Methods: Understand the difference between GET and POST. Practice writing a single Flask view that can handle both, using
request.methodto branch the logic.
This foundational knowledge translates directly to Django. Once you understand that a "view" is just a function that takes a request and returns a response, and that "routing" is just a mapping table, you've grasped the core concept shared by both frameworks. The main difference is in the configuration style (decorators vs. urls.py).
Comments (0)
No comments yet. Be the first to comment!