Master Flask: Request Handling, Contexts, Hooks, Blueprints, and Views
This article provides a comprehensive tutorial on Flask, covering request objects, application and request contexts, lifecycle hooks, blueprint modularization, class‑based and method‑based views, routing techniques, and common HTTP status codes for rapid Python web development.
Preface
Today we introduce Flask, a lightweight Python web framework. It enables fast development, though it has some drawbacks that are not discussed here. This article continues the previous part and covers the remaining topics.
Request Operations
1) request.method
Provides the HTTP method of the request, commonly GET and POST. Example code:
@app.route('/get', methods=['GET','POST'])
def get():
if request.method == 'GET':
return 'This is a GET request'
else:
return 'This is another request'2) request.args
Contains query parameters of a GET request. Example usage:
request.args['keyword']
request.args.get('keyword')3) request.form
Holds form data submitted via POST. Example usage:
request.form['keyword']
request.form.get('keyword')4) request.values
Returns a combined dictionary of query parameters and form data; rarely used.
5) request.cookies
Accesses cookies sent by the client. Example usage:
request.cookies['keyword']
request.cookies.get('keyword')6) request.headers
Provides request header information as a dictionary‑like object. Example usage:
request.headers['keyword']
request.headers.get('keyword')7) request.url, path, script_root, base_url, url_root
request.url # full request URL
request.path # URL path
request.script_root# script root directory
request.base_url # base URL without query string
request.url_root # root URL of the application8) request.data
Returns the raw request payload as bytes.
request.data # returns a bytes object9) request.files
Handles file uploads via POST. Example:
@app.route('/upload', methods=['GET','POST'])
def upload():
if request.method == 'POST':
f = request.files['file']
filename = secure_filename(f.filename)
f.save('app/static/' + str(filename))
return 'ok'
else:
return 'fail'10) request.json
Parses JSON payload of a request.
11) request.environ
Exposes the WSGI environment dictionary.
12) request.remote_addr
Returns the client’s IP address.
13) request.host
Returns the host information of the request.
Context and Request Hooks
1) Context
Flask defines two contexts:
Application context – g for temporary storage per request and current_app for the active app instance.
Request context – the request object and session for client‑side data.
2) Hooks
Flask provides lifecycle hooks to run code at specific points: before_first_request – runs once before the first request. before_request – runs before each request (e.g., for authentication). after_request – runs after each request to modify the response. teardown_request – runs after each request to handle exceptions. after_this_request – registers a function to run after the current request.
Example usage:
@app.before_first_request
def first():
print('I run first')
@app.before_request
def every():
print('I run before each request')
@app.after_request
def recv(res):
res.headers['Content-Type'] = 'application/json'
return res
@app.route('/start/<string:id>')
def start(id):
g.use = request.cookies.get('user')
if id == g.use:
return request.url
else:
return request.cookies
ac = app.app_context()
ac.push()
print(ac)
print(current_app)
ac.pop()
with app.app_context() as f:
b = current_app
print(b)
print(f)Blueprints
When an application grows, splitting it into modules using blueprints keeps the codebase manageable. The following demos illustrate basic blueprint usage.
# demo1.py
from flask import Flask
app = Flask(__name__)
@app.route('/kj')
def df():
return 'hello world'
@app.route('/index')
def lk():
return 'efhsfj'
# demo2.py
from flask import Flask, request
from demo1 import *
@app.route('/')
def login():
return request.url
if __name__ == '__main__':
app.run(debug=True)
# demo3.py
from flask import Flask
from demo4 import root
from demo5 import admin
app = Flask(__name__)
@app.route('/')
def lo():
return '1111'
app.register_blueprint(root, url_prefix='/')
app.register_blueprint(root, url_prefix='/root')
app.register_blueprint(root, url_prefix='/admin')
app.register_blueprint(admin, url_prefix='/')
app.register_blueprint(admin, url_prefix='/admin')
app.register_blueprint(admin, url_prefix='/root')
if __name__ == '__main__':
app.run(debug=True)
# demo4.py
from flask import Blueprint
root = Blueprint('root', __name__)
@root.route('/login')
def b1():
return 'hello'
@root.route('/index')
def b2():
return 'world'
# demo5.py
from flask import Blueprint
admin = Blueprint('admin', __name__)
@admin.route('/ff')
def bw():
return 'ergdsfg'
@admin.route('/gg')
def be():
return 'gtergsdf'Blueprints allow multiple modules to be registered under different URL prefixes, keeping the main application clean.
Views
1) Class‑based Views
from flask.views import View
class St(View):
def dispatch_request(self):
return "任性的90后boy"
app.add_url_rule('/ff', view_func=St.as_view('tt'))2) Method Views
from flask.views import MethodView
class Login(MethodView):
def get(self):
return 'get'
def post(self):
email = request.form.get('user')
password = request.form.get('pass')
if email == 'gffsadff' and password == '4fsaferwf':
return '登录成功'
else:
return '登陆失败'
app.add_url_rule('/gg', view_func=Login.as_view('lg'))Additional Topics
1) Global Objects
with app.test_request_context():
print('I am the first to run')2) Route Alias
@app.route('/<path:url>', endpoint='name1')
def first_flask(url):
print(url_for('name1', url=url))
return redirect(url_for('get'))3) Adding URL Rules
def fl():
return 'ok3'
app.add_url_rule('/kj', endpoint='name2', view_func=fl, methods=['GET'])4) Central URL Mapping without Decorators
# myapp.py
from flask import Flask
import views
app = Flask(__name__)
@app.route('/')
def ll():
return 'index'
@app.route('/use/<usename>')
def use(usename):
return usename
# views.py
def ll():
return 'index'
def use(usename):
return usename
# main.py
from myapp import views
from flask import Flask
app = Flask(__name__)
app.add_url_rule('/', view_func=views.ll)
app.add_url_rule('/use/<usename>', view_func=views.use)
if __name__ == '__main__':
app.run(debug=True)5) Common HTTP Status Codes
200 – OK
404 – Not Found
405 – Method Not Allowed
500 – Internal Server Error
302 – Redirect
301 – Permanent RedirectConclusion
This article covered the fundamental usage of Flask, a powerful lightweight web framework that enables rapid development of web applications. While Flask is simple to start with, extending its capabilities often requires additional extensions and careful structuring.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
