Here’s a basic cheat sheet for Flask, a popular Python web framework.
pip install Flask
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
@app.route('/path')
def function_name():
return 'Response'
@app.route('/user/<username>')
def show_user_profile(username):
return f'User {username}'
@app.route('/post', methods=['POST'])
def handle_post():
return 'POST request'
from flask import request
@app.route('/form', methods=['POST'])
def form():
username = request.form['username']
return f'Hello {username}'
@app.route('/json', methods=['POST'])
def json_example():
data = request.json
return f"Received data: {data}"
from flask import make_response
@app.route('/response')
def custom_response():
response = make_response('Custom response')
response.headers['X-Custom-Header'] = 'Value'
return response
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 !</h1>
</body>
</html>
static
./static/filename
.from flask import Blueprint
example_bp = Blueprint('example', __name__)
@example_bp.route('/example')
def example():
return 'Blueprint example'
app.register_blueprint(example_bp)
@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
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}'
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.