Master Flask: Quick Guide to Installation, Routing, and Session Management
This article provides a concise tutorial on Flask, covering installation, basic routing, custom converters, redirects, error handling, JSON responses, cookie and session management, and configuration techniques, all illustrated with clear code examples and screenshots for rapid web development.
Introduction
Flask is a lightweight Python web framework that enables rapid development. It is easy to get started with, though it has some limitations that are not discussed here.
1. Install Flask
pip install flask # note: flake is a linting tool, not to be confused with FlaskThe command installs four dependent packages for template rendering and networking.
2. Basic Flask Usage
2.1 Start the Application
from flask import Flask<br/>app = Flask(__name__)<br/><br/>@app.route('/') # route decorator creates a URL rule<br/>def hello():<br/> return 'hello' # view function response<br/><br/>if __name__ == '__main__':<br/> app.run(debug=True) # run in debug mode<br/><br># optional: specify host and port<br/>app.run(host='192.168.1.2', port=3243)After modifying the view function, refreshing the browser shows the new output without restarting the server.
2.2 Project Structure
Create a project folder containing at least two subfolders: static for media files and templates for HTML templates. Flask does not generate these automatically.
The url_map stores the mapping between URLs and endpoints. An endpoint is the internal name (usually the view function name) that Flask uses to locate the correct handler.
2.3 Flask Configuration Options
Key attributes include:
static_url_path : URL prefix for static files
static_folder : Filesystem path for static files (default static)
template_folder : Filesystem path for templates (default templates)
2.4 Adding Configuration
2.4.1 Directly in app.run()
Enable debug mode:
app.run(debug=True)2.4.2 Using app.config
app.config = True2.4.3 External Config File
Create a file (e.g., hw.cfg) with DEBUG=True and load it:
app.config.from_pyfile('hw.cfg')3. View Function Patterns
3.1 Sub‑page
@app.route('/index')<br/>def index():<br/> return 'index'3.2 Converters
@app.route('/index/<int:num>') # <int> converter named num<br/>def num(num):<br/> if num > 10:<br/> return 'dog'<br/> else:<br/> return 'pig'Flask’s default converters:
DEFAULT_CONVERTERS = {<br/> 'default': UnicodeConverter,<br/> 'string': UnicodeConverter,<br/> 'any': AnyConverter,<br/> 'path': PathConverter,<br/> 'int': IntegerConverter,<br/> 'float': FloatConverter,<br/> 'uuid': UUIDConverter}<br/>You can also define a custom converter:
class rc(BaseConverter):<br/> # custom validation, e.g., QQ email regex<br/> def __init__(self, url_map):<br/> super(rc, self).__init__(url_map)<br/> self.regex = '[0-9a-zA-Z_]{0,19}@qq.com'<br/> def to_python(self, value):<br/> return value<br/> def to_url(self, value):<br/> return value<br/><br/>app.url_map.converters['em'] = rc # register custom converter<br/>@app.route('/emm/<em:email>')<br/>def email(email):<br/> return 'email is:%s' % email3.3 Multiple Routes to Same View
@app.route('/1')<br/>@app.route('/2')<br/>def fg():<br/> return '1122'Both /1 and /2 return the same response.
4. Redirection
4.1 Direct Redirect
from flask import redirect<br/>@app.route('/refer')<br/>def refer():<br/> return redirect('/1')4.2 Indirect Redirect with url_for
from flask import redirect, url_for<br/>@app.route('/ref')<br/>def ref():<br/> return redirect(url_for('fg'))5. Error Handling
5.1 Using abort
@app.route('/use/<id>')<br/>def get_use(id):<br/> if int(id) < 10:<br/> abort(404)<br/> elif int(id) > 20:<br/> return '---Error---'<br/> return 'hello:%s' % str(id)5.2 Custom Error Handler
@app.errorhandler(404)<br/>def error(err):<br/> return 'hello,%s' % err5.3 Using make_response
@app.route('/error3')<br/>def err3():<br/> resp = make_response('search error')<br/> resp.status = '400'<br/> resp.headers['hrr'] = 'zjj'<br/> resp.headers['hw'] = 'zj'<br/> return resp6. JSON Responses
@app.route('/json1')<br/>def json1():<br/> data = {'name': 'HW', 'first': 'ZJ'}<br/> return jsonify(data)<br/><br/>@app.route('/json2')<br/>def json2():<br/> return jsonify(hour=12, second=21)7. Cookie Operations
7.1 Set Cookie
@app.route('/set_cookie')<br/>def set_cookie():<br/> response = make_response('cookie设置成功')<br/> time = datetime.datetime.today() + datetime.timedelta(days=30)<br/> response.set_cookie('user', 'admin', expires=time)<br/> response.set_cookie('pass', '123456', expires=time)<br/> response.headers['X-Something'] = 'mything'<br/> response.headers['Server'] = 'Linux'<br/> return response7.2 Get Cookie
@app.route('/get_cookie')<br/>def get_cookie():<br/> name = "用户名:" + request.cookies.get('user') + "密码:" + request.cookies.get('pass')<br/> return name7.3 Delete Cookie
@app.route('/del_cookie1')<br/>def del_cookie1():<br/> response = make_response('delete cookie 1')<br/> response.set_cookie('user', '', expires=0)<br/> response.set_cookie('pass', '', expires=0)<br/> return response<br/><br/>@app.route('/del_cookie2')<br/>def del_cookie2():<br/> response = make_response('delete cookie 2')<br/> response.delete_cookie('user')<br/> response.delete_cookie('pass')<br/> return response8. Session Operations
8.1 Set Session
# configure secret key<br/>app.config['SECRET_KEY'] = os.urandom(30)<br/><br># set session values<br/>session['user'] = 'hw'<br/>session['pass'] = 'zj'<br/><br># make session permanent (default 31 days)<br/>session.permanent = True<br/><br># optional: set custom lifetime (e.g., 2 hours)<br/>app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=2)8.2 Get Session
@app.route('/session2')<br/>def session2():<br/> us = session.get('user')<br/> pa = session.get('pass')<br/> return 'hello %s %s' % (us, pa)8.3 Delete Session
# delete specific keys<br/>@app.route('/session3')<br/>def session3():<br/> session.pop('user', None)<br/> session.pop('pass', None)<br/> return 'delete successful!!!!'<br/><br># clear all session data<br/>@app.route('/session4')<br/>def session4():<br/> session.clear()<br/> return 'delete successful!!!!'Conclusion
This article covered the fundamentals of Flask, a powerful yet lightweight web framework that enables fast development of web applications. While only a portion of Flask’s capabilities are demonstrated here, the concepts presented provide a solid foundation for further exploration.
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.
