Here’s a basic cheat sheet for Flask, a popular Python web framework.
- Setup
- Routing
- Request and Response
- Templates
- Static Files
- Blueprints
- Error Handling
- Sessions
- Debugging
-
Install Flask:
pip install Flask
-
Basic Application:
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Hello, World!' if __name__ == '__main__': app.run(debug=True)
-
Basic Route:
@app.route('/path') def function_name(): return 'Response'
-
Dynamic Routes:
@app.route('/user/<username>') def show_user_profile(username): return f'User {username}'
-
HTTP Methods:
@app.route('/post', methods=['POST']) def handle_post(): return 'POST request'
-
Access Request Data:
from flask import request @app.route('/form', methods=['POST']) def form(): username = request.form['username'] return f'Hello {username}'
-
JSON Request:
@app.route('/json', methods=['POST']) def json_example(): data = request.json return f"Received data: {data}"
-
Response Object:
from flask import make_response @app.route('/response') def custom_response(): response = make_response('Custom response') response.headers['X-Custom-Header'] = 'Value' return response
-
Render Template:
from flask import render_template @app.route('/hello') def hello(): return render_template('hello.html', name='World')
In
templates/hello.html
:<!doctype html> <html> <head><title>Hello</title></head> <body> <h1>Hello {{ name }}!</h1> </body> </html>
- Serve Static Files:
- Place static files (CSS, JS) in a folder named
static
. - Access static files via
/static/filename
.
- Place static files (CSS, JS) in a folder named
- Create and Register Blueprint:
from flask import Blueprint example_bp = Blueprint('example', __name__) @example_bp.route('/example') def example(): return 'Blueprint example' app.register_blueprint(example_bp)
- Custom Error Pages:
@app.errorhandler(404) def not_found_error(error): return 'Page not found', 404 @app.errorhandler(500) def internal_error(error): return 'Internal server error', 500
- Using Sessions:
from flask import session app.secret_key = 'supersecretkey' @app.route('/set_session') def set_session(): session['username'] = 'admin' return 'Session data set' @app.route('/get_session') def get_session(): username = session.get('username', 'not set') return f'Username is {username}'
- Enable Debug Mode:
if __name__ == '__main__': app.run(debug=True)
This cheat sheet covers the basics of Flask, but Flask has many more capabilities that can be explored through its official documentation.