Here’s a cheat sheet for Flask, a popular web framework for Python:
Installation
pip install Flask
Hello World App
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
Routing
@app.route('/route')
def my_route():
return 'This is my route!'
Variable Rules
@app.route('/user/<username>')
def show_user(username):
return f'User: {username}'
HTTP Methods
from flask import request
@app.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'POST':
# Process login data
return 'Login POST request'
else:
return 'Login GET request'
Templates
Create a templates
folder in your project directory.
Use the render_template
function to render HTML templates.
Forms
Use the Flask-WTF extension for form handling.
- Example:
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
class MyForm(FlaskForm):
name = StringField('Name')
submit = SubmitField('Submit')
Redirects and Errors
from flask import redirect, url_for, abort
@app.route('/redirect')
def my_redirect():
return redirect(url_for('my_route'))
@app.route('/error')
def my_error():
abort(404)
Flask Extensions
- Flask offers various extensions for additional functionality.
- Example: Flask-SQLAlchemy, Flask-Login, Flask-Mail.
Static Files
- Create a
static
folder in your project directory. - Use the
url_for
function to link to static files. - Example:
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
Flask CLI
Run the Flask development server with:
flask run
Create database tables with:
flask db init
flask db migrate
flask db upgrade
Deployment
Common deployment options include Gunicorn, uWSGI, or using a platform like Heroku.
This cheat sheet covers some fundamental concepts in Flask. Remember to refer to the Flask documentation for more in-depth information and advanced features.