|
======================== |
|
CODE SNIPPETS |
|
======================== |
|
TITLE: Flask Session Management Example |
|
DESCRIPTION: Demonstrates how to use Flask sessions to store user-specific information across requests, including setting a secret key, handling login, and logout functionality. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_29 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from flask import session |
|
|
|
# Set the secret key to some random bytes. Keep this really secret! |
|
app.secret_key = b'_5#y2L\"F4Q8z\n\xec]/' |
|
|
|
@app.route('/') |
|
def index(): |
|
if 'username' in session: |
|
return f'Logged in as {session["username"]}' |
|
return 'You are not logged in' |
|
|
|
@app.route('/login', methods=['GET', 'POST']) |
|
def login(): |
|
if request.method == 'POST': |
|
session['username'] = request.form['username'] |
|
return redirect(url_for('index')) |
|
return ''' |
|
<form method="post"> |
|
<p><input type=text name=username> |
|
<p><input type=submit value=Login> |
|
</form> |
|
''' |
|
|
|
@app.route('/logout') |
|
def logout(): |
|
# remove the username from the session if it's there |
|
session.pop('username', None) |
|
return redirect(url_for('index')) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Handling Login with Request Method and Form Data |
|
DESCRIPTION: Provides a comprehensive example of a login route that uses `request.method` to differentiate between GET and POST requests and `request.form` to access submitted username and password data. It includes basic validation and error handling. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_18 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
@app.route('/login', methods=['POST', 'GET']) |
|
def login(): |
|
error = None |
|
if request.method == 'POST': |
|
if valid_login(request.form['username'], |
|
request.form['password']): |
|
return log_the_user_in(request.form['username']) |
|
else: |
|
error = 'Invalid username/password' |
|
# the code below is executed if the request method |
|
# was GET or the credentials were invalid |
|
return render_template('login.html', error=error) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Example Jinja2 HTML Template Structure |
|
DESCRIPTION: Provides a basic Jinja2 template demonstrating conditional rendering (`{% if %}` / `{% else %}`) and variable display (`{{ variable }}`). This template is designed to be rendered by a Flask application, showcasing how dynamic content can be integrated into standard HTML markup. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_13 |
|
|
|
LANGUAGE: html |
|
CODE: |
|
``` |
|
<!doctype html> |
|
<title>Hello from Flask</title> |
|
{% if person %} |
|
<h1>Hello {{ person }}!</h1> |
|
{% else %} |
|
<h1>Hello, World!</h1> |
|
{% endif %} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Python Environment and Flask Project |
|
DESCRIPTION: This snippet provides commands to set up a Python virtual environment, activate it, and install the current Flask project in editable mode. This is a standard procedure for preparing a Python development environment. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/examples/javascript/README.rst#_snippet_0 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ python3 -m venv .venv |
|
$ . .venv/bin/activate |
|
$ pip install -e . |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Example Flask Debug Server Console Output |
|
DESCRIPTION: This snippet displays the typical console output when the Flask development server starts in debug mode. It confirms the application being served, the active debug mode, the local URL for access, and the activation of the debugger with its PIN, indicating a successful server startup. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/factory.rst#_snippet_4 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
* Serving Flask app "flaskr" |
|
* Debug mode: on |
|
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) |
|
* Restarting with stat |
|
* Debugger is active! |
|
* Debugger PIN: nnn-nnn-nnn |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Test Dependencies and Run Tests with Coverage |
|
DESCRIPTION: This snippet outlines the steps to install testing dependencies, run tests using pytest, and generate a code coverage report. It ensures the project's functionality and code quality are verified. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/examples/javascript/README.rst#_snippet_2 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ pip install -e '.[test]' |
|
$ coverage run -m pytest |
|
$ coverage report |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Handle Multiple HTTP Methods for Flask Routes |
|
DESCRIPTION: Shows how to configure a Flask route to respond to specific HTTP methods (e.g., GET, POST) using the `methods` argument in the `@app.route` decorator. This allows for different logic based on the request type, such as handling form submissions. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_9 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from flask import request |
|
|
|
@app.route('/login', methods=['GET', 'POST']) |
|
def login(): |
|
if request.method == 'POST': |
|
return do_the_login() |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Gunicorn and application in a virtual environment |
|
DESCRIPTION: This snippet outlines the standard procedure to set up a Python virtual environment, install your Flask application, and then install Gunicorn using pip. This is a common and recommended setup for deploying Python web applications. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/gunicorn.rst#_snippet_0 |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
$ cd hello-app |
|
$ python -m venv .venv |
|
$ . .venv/bin/activate |
|
$ pip install . # install your application |
|
$ pip install gunicorn |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Flask Redirects and Errors: `redirect` and `abort` |
|
DESCRIPTION: Illustrates the basic usage of `flask.redirect` to send a user to another URL and `flask.abort` to immediately terminate a request with an HTTP error code. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_24 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from flask import abort, redirect, url_for |
|
|
|
@app.route('/') |
|
def index(): |
|
return redirect(url_for('login')) |
|
|
|
@app.route('/login') |
|
def login(): |
|
abort(401) |
|
this_is_never_executed() |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Separate Flask Views for GET and POST Methods |
|
DESCRIPTION: Demonstrates how to define distinct view functions for different HTTP methods (GET and POST) on the same route in Flask. This approach, using `@app.get` and `@app.post` decorators, helps organize logic when specific actions are tied to particular request methods, such as displaying a form versus processing its submission. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_10 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
@app.get('/login') |
|
def login_get(): |
|
return show_the_login_form() |
|
|
|
@app.post('/login') |
|
def login_post(): |
|
return do_the_login() |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Run a Flask Application from the Command Line |
|
DESCRIPTION: This command shows how to run the Flask application using the 'flask' command-line interface. The '--app hello' option specifies the application file (e.g., 'hello.py'). The output indicates the server is running locally, typically on port 5000. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_1 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ flask --app hello run |
|
* Serving Flask app 'hello' |
|
* Running on http://127.0.0.1:5000 (Press CTRL+C to quit) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Define Basic Flask Routes |
|
DESCRIPTION: Demonstrates how to bind Python functions to specific URL paths using the `@app.route` decorator in Flask. This allows the application to respond to requests at the defined endpoints. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_5 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
@app.route('/') |
|
def index(): |
|
return 'Index Page' |
|
|
|
@app.route('/hello') |
|
def hello(): |
|
return 'Hello, World' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Run Flask Application |
|
DESCRIPTION: This command starts the Flask development server for the 'js_example' application. It makes the application accessible via a web browser at the specified local address. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/examples/javascript/README.rst#_snippet_1 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ flask --app js_example run |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Flask Error Handling: Custom 404 Page |
|
DESCRIPTION: Shows how to customize error pages in Flask using the `errorhandler` decorator. This example specifically handles a 404 Not Found error by rendering a custom template and setting the correct status code. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_25 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from flask import render_template |
|
|
|
@app.errorhandler(404) |
|
def page_not_found(error): |
|
return render_template('page_not_found.html'), 404 |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Create a Minimal Flask Web Application |
|
DESCRIPTION: This snippet demonstrates how to create a basic Flask application. It imports the Flask class, creates an application instance, defines a route for the root URL ('/'), and returns a simple 'Hello, World!' HTML paragraph. The '__name__' argument helps Flask locate resources like templates. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_0 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from flask import Flask |
|
|
|
app = Flask(__name__) |
|
|
|
@app.route("/") |
|
def hello_world(): |
|
return "<p>Hello, World!</p>" |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install pyuwsgi for Flask applications |
|
DESCRIPTION: This snippet provides shell commands to set up a Python virtual environment, install a Flask application, and then install the `pyuwsgi` package, which offers precompiled wheels for quick setup but lacks SSL support. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/uwsgi.rst#_snippet_0 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ cd hello-app |
|
$ python -m venv .venv |
|
$ . .venv/bin/activate |
|
$ pip install . |
|
$ pip install pyuwsgi |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Define Project Metadata with pyproject.toml |
|
DESCRIPTION: The `pyproject.toml` file is used to describe a Python project and define how it should be built. This example specifies the project's name, version, description, and runtime dependencies, along with the build system requirements for `flit_core`. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/install.rst#_snippet_0 |
|
|
|
LANGUAGE: toml |
|
CODE: |
|
``` |
|
[project] |
|
name = "flaskr" |
|
version = "1.0.0" |
|
description = "The basic blog app built in the Flask tutorial." |
|
dependencies = [ |
|
"flask", |
|
] |
|
|
|
[build-system] |
|
requires = ["flit_core<4"] |
|
build-backend = "flit_core.buildapi" |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Importing the Flask Request Object |
|
DESCRIPTION: Shows the standard way to import the `request` object from the `flask` module, which is necessary before using it to access client data. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_17 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from flask import request |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Using request_context with WSGI Environment |
|
DESCRIPTION: Illustrates an alternative method for binding a request context by passing a full WSGI environment to `app.request_context`. This allows for more granular control over the request context during testing or specific scenarios. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_16 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
with app.request_context(environ): |
|
assert request.method == 'POST' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Running Flask App with Debug Mode - Shell |
|
DESCRIPTION: Command line example showing how to start a Flask development server with debug mode enabled using the `flask run` command. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/config.rst#_snippet_3 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ flask --app hello run --debug |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Basic Flask Application Setup and Configuration |
|
DESCRIPTION: This snippet demonstrates the initial setup of a Flask application by creating an instance of the Flask class. It shows how to configure the application using `app.config.from_mapping` for default settings and `app.config.from_prefixed_env()` for environment-based configuration. A basic route is also included to illustrate a simple 'Hello, World!' endpoint. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/lifecycle.rst#_snippet_0 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from flask import Flask |
|
|
|
app = Flask(__name__) |
|
app.config.from_mapping( |
|
SECRET_KEY="dev", |
|
) |
|
app.config.from_prefixed_env() |
|
|
|
@app.route("/") |
|
def index(): |
|
return "Hello, World!" |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Render Jinja2 Templates in Flask |
|
DESCRIPTION: Shows how to use Flask's `render_template` function to serve dynamic HTML pages. It demonstrates passing Python variables as keyword arguments to a Jinja2 template, enabling personalized content based on URL parameters or other application data. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_12 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from flask import render_template |
|
|
|
@app.route('/hello/') |
|
@app.route('/hello/<name>') |
|
def hello(name=None): |
|
return render_template('hello.html', person=name) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Flaskr Test Dependencies |
|
DESCRIPTION: Command to install the testing dependencies required for running tests on the Flaskr application, specified in the project's setup. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/examples/tutorial/README.rst#_snippet_5 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ pip install '.[test]' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Flask File Upload: Basic Save |
|
DESCRIPTION: Demonstrates how to handle file uploads in Flask using `request.files` and save the uploaded file directly to the server's filesystem. It shows a basic POST request handler for file saving. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_20 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from flask import request |
|
|
|
@app.route('/upload', methods=['GET', 'POST']) |
|
def upload_file(): |
|
if request.method == 'POST': |
|
f = request.files['the_file'] |
|
f.save('/var/www/uploads/uploaded_file.txt') |
|
... |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Flask API Endpoints Returning JSON (dict/list) |
|
DESCRIPTION: Illustrates how Flask automatically converts dictionaries or lists returned from view functions into JSON responses, simplifying the creation of API endpoints. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_28 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
@app.route("/me") |
|
def me_api(): |
|
user = get_current_user() |
|
return { |
|
"username": user.username, |
|
"theme": user.theme, |
|
"image": url_for("user_image", filename=user.image), |
|
} |
|
|
|
@app.route("/users") |
|
def users_api(): |
|
users = get_all_users() |
|
return [user.to_json() for user in users] |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Flask from Source and Flaskr (Main Branch) |
|
DESCRIPTION: Instructions for installing Flask from its source directory and then Flaskr, specifically when working with the main development branch, ensuring all dependencies are met. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/examples/tutorial/README.rst#_snippet_3 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ pip install -e ../.. |
|
$ pip install -e . |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Basic Flask Application Setup |
|
DESCRIPTION: Demonstrates a minimal Flask application that returns 'Hello World!' on the root path. This serves as a basic WSGI application that can be run with any WSGI server. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/appdispatch.rst#_snippet_0 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from flask import Flask |
|
|
|
app = Flask(__name__) |
|
|
|
@app.route('/') |
|
def hello_world(): |
|
return 'Hello World!' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Applying WSGI Middleware to Flask Applications |
|
DESCRIPTION: To integrate WSGI middleware, such as Werkzeug's `ProxyFix`, wrap the `app.wsgi_app` attribute. This approach ensures that the original `app` object remains accessible for direct configuration, while the middleware processes requests. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_32 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from werkzeug.middleware.proxy_fix import ProxyFix |
|
app.wsgi_app = ProxyFix(app.wsgi_app) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Flask Cookies: Reading from Request |
|
DESCRIPTION: Shows how to read cookies sent by the client using `request.cookies.get()`. It emphasizes using `.get()` to avoid `KeyError` if the cookie is missing. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_22 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from flask import request |
|
|
|
@app.route('/') |
|
def index(): |
|
username = request.cookies.get('username') |
|
# use cookies.get(key) instead of cookies[key] to not get a |
|
# KeyError if the cookie is missing. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Build URLs in Flask using url_for Function |
|
DESCRIPTION: Demonstrates how to programmatically generate URLs for Flask functions using `url_for`. This method is preferred over hard-coding URLs as it handles changes, escaping, and application root paths automatically, ensuring robust URL generation. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_8 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from flask import url_for |
|
|
|
@app.route('/') |
|
def index(): |
|
return 'index' |
|
|
|
@app.route('/login') |
|
def login(): |
|
return 'login' |
|
|
|
@app.route('/user/<username>') |
|
def profile(username): |
|
return f'{username}\'s profile' |
|
|
|
with app.test_request_context(): |
|
print(url_for('index')) |
|
print(url_for('login')) |
|
print(url_for('login', next='/')) |
|
print(url_for('profile', username='John Doe')) |
|
``` |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
/ |
|
/login |
|
/login?next=/ |
|
/user/John%20Doe |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Waitress for Flask Application |
|
DESCRIPTION: This snippet demonstrates the steps to set up a Python virtual environment, install your Flask application, and then install the Waitress WSGI server using pip, preparing your project for deployment. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/waitress.rst#_snippet_0 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ cd hello-app |
|
$ python -m venv .venv |
|
$ . .venv/bin/activate |
|
$ pip install . # install your application |
|
$ pip install waitress |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Run Gunicorn with eventlet asynchronous worker |
|
DESCRIPTION: Shows how to start Gunicorn using the 'eventlet' worker type for asynchronous processing. This requires eventlet to be installed and your application code to utilize eventlet for any performance benefits. Ensure greenlet>=1.0 is installed. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/gunicorn.rst#_snippet_4 |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
$ gunicorn -k eventlet 'hello:create_app()' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Using MarkupSafe for HTML Escaping and Unescaping |
|
DESCRIPTION: Demonstrates the `markupsafe.Markup` class for handling HTML strings securely in Python. It illustrates how to combine safe and unsafe strings, explicitly escape potentially malicious HTML, and strip HTML tags from text, crucial for preventing Cross-Site Scripting (XSS) vulnerabilities. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_14 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from markupsafe import Markup |
|
>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>' |
|
Markup('<strong>Hello <blink>hacker</blink>!</strong>') |
|
>>> Markup.escape('<blink>hacker</blink>') |
|
Markup('<blink>hacker</blink>') |
|
>>> Markup('<em>Marked up</em> » HTML').striptags() |
|
'Marked up » HTML' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Run Gunicorn with gevent asynchronous worker |
|
DESCRIPTION: Shows how to start Gunicorn using the 'gevent' worker type for asynchronous processing. This requires gevent to be installed and your application code to utilize gevent for any performance benefits. Ensure greenlet>=1.0 is installed. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/gunicorn.rst#_snippet_3 |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
$ gunicorn -k gevent 'hello:create_app()' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Create Flask Project Directory |
|
DESCRIPTION: This command creates the root directory for the Flask application, which will contain the application package and instance folder. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/factory.rst#_snippet_0 |
|
|
|
LANGUAGE: none |
|
CODE: |
|
``` |
|
$ mkdir flaskr |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Logging Messages in Flask Applications |
|
DESCRIPTION: Flask provides a preconfigured logger accessible via `app.logger` for recording various levels of messages. This allows developers to log debugging information, warnings, and errors within their application. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_31 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
app.logger.debug('A value for debugging') |
|
app.logger.warning('A warning occurred (%d apples)', 42) |
|
app.logger.error('An error occurred') |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Setup Celery Worker for Flask Background Tasks |
|
DESCRIPTION: This command sequence sets up a Python virtual environment, installs project dependencies, and starts the Celery worker process. The Celery worker is essential for processing background tasks submitted by the Flask application. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/examples/celery/README.md#_snippet_0 |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
$ python3 -m venv .venv |
|
$ . ./.venv/bin/activate |
|
$ pip install -r requirements.txt && pip install -e . |
|
$ celery -A make_celery worker --loglevel INFO |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Using test_request_context for Unit Testing |
|
DESCRIPTION: Demonstrates how to use the `test_request_context` context manager to bind a test request to the current context, enabling unit testing of code that depends on the global `request` object. This allows for assertions on request attributes like path and method. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_15 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from flask import request |
|
|
|
with app.test_request_context('/hello', method='POST'): |
|
# now you can do something with the request until the |
|
# end of the with block, such as basic assertions: |
|
assert request.path == '/hello' |
|
assert request.method == 'POST' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Running the Flask Development Server |
|
DESCRIPTION: This shell command shows how to run the simple Flask application created in the previous snippet using the 'flask run' command. It starts the development server, typically on http://127.0.0.1:5000. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/README.md#_snippet_1 |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
$ flask run |
|
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Flask Application Configuration API Reference |
|
DESCRIPTION: Detailed API documentation for key components and methods used in configuring a Flask application, including the Flask class constructor, configuration methods, and routing decorators. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/factory.rst#_snippet_2 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Flask Class Constructor: |
|
Flask(__name__, instance_relative_config=True) |
|
__name__: The name of the current Python module, used by Flask to locate paths. |
|
instance_relative_config: bool - If True, configuration files are relative to the instance folder, which is outside the package and holds local data (e.g., secrets, database). |
|
|
|
Config Object Methods and Attributes: |
|
app.config.from_mapping(mapping: dict) |
|
Purpose: Sets default configuration values for the application. |
|
Parameters: |
|
mapping: A dictionary of configuration key-value pairs. |
|
Attributes: |
|
SECRET_KEY: Used by Flask and extensions for data safety. Default 'dev' for development; should be overridden in production. |
|
DATABASE: Path where the SQLite database file will be saved, typically under app.instance_path. |
|
|
|
app.config.from_pyfile(filename: str, silent: bool = False) |
|
Purpose: Overrides default configuration with values from a Python file in the instance folder. |
|
Parameters: |
|
filename: The name of the Python file (e.g., 'config.py'). |
|
silent: bool - If True, errors are ignored if the file doesn't exist. |
|
|
|
Flask Instance Attributes: |
|
app.instance_path: The path Flask has chosen for the instance folder. This folder is not created automatically and must be ensured to exist (e.g., using os.makedirs). |
|
|
|
Routing Decorators: |
|
@app.route(rule: str, **options) |
|
Purpose: Creates a connection between a URL rule and a function that returns a response. |
|
Parameters: |
|
rule: The URL rule string (e.g., '/hello'). |
|
Usage: Applied as a decorator to a Python function, making that function handle requests to the specified URL. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Verify Installed Python Packages with pip list |
|
DESCRIPTION: The `pip list` command displays all installed Python packages and their versions, including the location for editable installations. This helps confirm that the project has been successfully installed in the virtual environment and shows its current path. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/install.rst#_snippet_2 |
|
|
|
LANGUAGE: none |
|
CODE: |
|
``` |
|
$ pip list |
|
|
|
Package Version Location |
|
-------------- --------- ---------------------------------- |
|
click 6.7 |
|
Flask 1.0 |
|
flaskr 1.0.0 /home/user/Projects/flask-tutorial |
|
itsdangerous 0.24 |
|
Jinja2 2.10 |
|
MarkupSafe 1.0 |
|
pip 9.0.3 |
|
Werkzeug 0.14.1 |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Modifying Flask Response Object with make_response |
|
DESCRIPTION: Shows how to use `make_response` to explicitly create a response object from a view's return value, allowing modification of headers or other properties before returning it. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_27 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from flask import make_response |
|
|
|
@app.errorhandler(404) |
|
def not_found(error): |
|
resp = make_response(render_template('error.html'), 404) |
|
resp.headers['X-Something'] = 'A value' |
|
return resp |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Make Flask Server Externally Visible |
|
DESCRIPTION: By default, the Flask development server is only accessible from the local machine. This command demonstrates how to make the server publicly available on the network by adding '--host=0.0.0.0'. This tells the operating system to listen on all public IP addresses, but should only be used if the debugger is disabled or users on the network are trusted due to security risks. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_2 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ flask run --host=0.0.0.0 |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Installing and Running a Custom Script |
|
DESCRIPTION: These shell commands show how to install a project with a custom script entry point in editable mode and then execute the custom script (`wiki`) directly. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/cli.rst#_snippet_32 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ pip install -e . |
|
$ wiki run |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Flask Cookies: Storing on Response |
|
DESCRIPTION: Demonstrates how to set a cookie on the client's browser by using `make_response` and `resp.set_cookie()`. Cookies are set on the response object before it's returned. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_23 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from flask import make_response |
|
|
|
@app.route('/') |
|
def index(): |
|
resp = make_response(render_template(...)) |
|
resp.set_cookie('username', 'the username') |
|
return resp |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Send GET Request and Assert Response with Flask Test Client |
|
DESCRIPTION: This Python example illustrates how to use Flask's test client to simulate a GET request to a specified route (`/posts`). It then asserts that a particular byte string (`<h2>Hello, World!</h2>`) is present within the response data, verifying the expected output from the application's view. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/testing.rst#_snippet_2 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
def test_request_example(client): |
|
response = client.get("/posts") |
|
assert b"<h2>Hello, World!</h2>" in response.data |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Adding WSGI Middleware to Flask App (Python) |
|
DESCRIPTION: Shows how to wrap the `app.wsgi_app` attribute with WSGI middleware, using `werkzeug.middleware.proxy_fix.ProxyFix` as an example. This method allows middleware integration while keeping the original `app` object accessible for configuration. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_33 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from werkzeug.middleware.proxy_fix import ProxyFix |
|
app.wsgi_app = ProxyFix(app.wsgi_app) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Installing gevent for Flask application |
|
DESCRIPTION: Instructions to set up a Python virtual environment and install gevent, ensuring compatibility with `greenlet>=1.0` and `PyPy>=7.3.7` for proper context local functionality like `request`. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/gevent.rst#_snippet_0 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ cd hello-app |
|
$ python -m venv .venv |
|
$ . .venv/bin/activate |
|
$ pip install . |
|
$ pip install gevent |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Flask Error Handler with Tuple Return |
|
DESCRIPTION: Demonstrates how to define a custom error handler in Flask that returns a tuple containing the response and status code, overriding the default status. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_26 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from flask import render_template |
|
|
|
@app.errorhandler(404) |
|
def not_found(error): |
|
return render_template('error.html'), 404 |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Flask File Upload: Secure Filename |
|
DESCRIPTION: Illustrates how to securely save an uploaded file using `werkzeug.utils.secure_filename` to prevent path traversal vulnerabilities. It's crucial to sanitize client-provided filenames before using them on the server. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_21 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from werkzeug.utils import secure_filename |
|
|
|
@app.route('/upload', methods=['GET', 'POST']) |
|
def upload_file(): |
|
if request.method == 'POST': |
|
file = request.files['the_file'] |
|
file.save(f"/var/www/uploads/{secure_filename(file.filename)}") |
|
... |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Flask application wheel on production server |
|
DESCRIPTION: Demonstrates how to install the previously built Flask application wheel file (.whl) on a target machine using pip. This command installs the application along with its declared dependencies. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/deploy.rst#_snippet_2 |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
$ pip install flaskr-1.0.0-py3-none-any.whl |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Generate Flask Secret Key (Shell Command) |
|
DESCRIPTION: Provides a shell command using Python's `secrets` module to quickly generate a strong, random hexadecimal string suitable for use as a Flask secret key. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_30 |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
python -c 'import secrets; print(secrets.token_hex())' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Clone and Checkout Flask Repository |
|
DESCRIPTION: Instructions to clone the Flask repository, navigate to the `flask` directory, and checkout a specific tagged version of the code for the Flaskr example, ensuring compatibility with documentation. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/examples/tutorial/README.rst#_snippet_0 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ git clone https://github.com/pallets/flask |
|
$ cd flask |
|
$ git tag # shows the tagged versions |
|
$ git checkout latest-tag-found-above |
|
$ cd examples/tutorial |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Enable Debug Mode for Flask Application |
|
DESCRIPTION: This command shows how to run the Flask application in debug mode using the '--debug' option. Debug mode automatically reloads the server on code changes and provides an interactive debugger in the browser for errors. It also displays a debugger PIN. Debug mode should never be used in a production environment due to security vulnerabilities. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_3 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ flask --app hello run --debug |
|
* Serving Flask app 'hello' |
|
* Debug mode: on |
|
* Running on http://127.0.0.1:5000 (Press CTRL+C to quit) |
|
* Restarting with stat |
|
* Debugger is active! |
|
* Debugger PIN: nnn-nnn-nnn |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install uwsgi with compiler or from sdist |
|
DESCRIPTION: This snippet shows alternative `pip install` commands for `uwsgi` or `pyuwsgi` from source distribution. These methods require a compiler but provide SSL support, offering more robust deployment options. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/uwsgi.rst#_snippet_1 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ pip install uwsgi |
|
|
|
# or |
|
$ pip install --no-binary pyuwsgi pyuwsgi |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Accessing URL Parameters with request.args |
|
DESCRIPTION: Demonstrates how to retrieve parameters submitted in the URL query string (e.g., `?key=value`) using the `request.args` attribute. It recommends using the `.get()` method to safely access parameters and provide a default value, preventing `KeyError`. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_19 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
searchword = request.args.get('key', '') |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Generate URLs for Static Files in Flask |
|
DESCRIPTION: Illustrates the use of Flask's `url_for` function with the special `'static'` endpoint to generate URLs for static assets. This function automatically constructs the correct path to files located within the application's `static/` directory, such as `style.css`. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_11 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
url_for('static', filename='style.css') |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Start Flask Development Server |
|
DESCRIPTION: Demonstrates how to start the Flask development server using the `flask run` command. This command replaces the `Flask.run` method for most cases. It's important to note that this server is for development only and not suitable for production. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/cli.rst#_snippet_1 |
|
|
|
LANGUAGE: console |
|
CODE: |
|
``` |
|
$ flask --app hello run |
|
* Serving Flask app "hello" |
|
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Define Flask Routes with Dynamic Variable Rules |
|
DESCRIPTION: Illustrates how to create dynamic URL segments in Flask routes using `<variable_name>` and type converters like `<int:post_id>` or `<path:subpath>`. The corresponding function receives these segments as keyword arguments, allowing for flexible URL patterns. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_6 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from markupsafe import escape |
|
|
|
@app.route('/user/<username>') |
|
def show_user_profile(username): |
|
# show the user profile for that user |
|
return f'User {escape(username)}' |
|
|
|
@app.route('/post/<int:post_id>') |
|
def show_post(post_id): |
|
# show the post with the given id, the id is an integer |
|
return f'Post {post_id}' |
|
|
|
@app.route('/path/<path:subpath>') |
|
def show_subpath(subpath): |
|
# show the subpath after /path/ |
|
return f'Subpath {escape(subpath)}' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Example Pytest Test Session Output |
|
DESCRIPTION: This snippet shows a typical output from running `pytest`, detailing the test session start, platform information, collected items, progress for each test file, and a final summary of passed tests and execution time. It illustrates the console feedback during test execution. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_23 |
|
|
|
LANGUAGE: none |
|
CODE: |
|
``` |
|
========================= test session starts ========================== |
|
platform linux -- Python 3.6.4, pytest-3.5.0, py-1.5.3, pluggy-0.6.0 |
|
rootdir: /home/user/Projects/flask-tutorial |
|
collected 23 items |
|
|
|
tests/test_auth.py ........ [ 34%] |
|
tests/test_blog.py ............ [ 86%] |
|
tests/test_db.py .. [ 95%] |
|
tests/test_factory.py .. [100%] |
|
|
|
====================== 24 passed in 0.64 seconds ======================= |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Start Flask Application with Debug Mode |
|
DESCRIPTION: This command initiates the Flask development server for the 'flaskr' application, activating debug mode. Debug mode is crucial for development as it provides an interactive debugger on errors and automatically reloads the server upon code modifications, streamlining the development workflow. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/factory.rst#_snippet_3 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ flask --app flaskr run --debug |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Initialize and configure a Flask extension in Python |
|
DESCRIPTION: This example demonstrates the general pattern for using a Flask extension. It shows how to import the extension, create an instance, configure application-specific settings via `app.config`, and then initialize the extension with the Flask application instance using the `init_app` method. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/extensions.rst#_snippet_0 |
|
|
|
LANGUAGE: Python |
|
CODE: |
|
``` |
|
from flask_foo import Foo |
|
|
|
foo = Foo() |
|
|
|
app = Flask(__name__) |
|
app.config.update( |
|
FOO_BAR='baz', |
|
FOO_SPAM='eggs', |
|
) |
|
|
|
foo.init_app(app) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Installing eventlet for Flask applications |
|
DESCRIPTION: This snippet provides shell commands to set up a Python virtual environment, install your Flask application, and then install the `eventlet` library. It ensures the necessary dependencies are met for asynchronous serving. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/eventlet.rst#_snippet_0 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ cd hello-app |
|
$ python -m venv .venv |
|
$ . .venv/bin/activate |
|
$ pip install . # install your application |
|
$ pip install eventlet |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Pytest for Flask Application Testing |
|
DESCRIPTION: This snippet demonstrates how to install the `pytest` framework, a prerequisite for setting up and running tests for Flask applications, using the pip package manager. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/testing.rst#_snippet_0 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ pip install pytest |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Running Waitress with Flask App Factory (Shell) |
|
DESCRIPTION: Command to start the Waitress server binding to localhost (127.0.0.1). It uses the '--call' option to specify an app factory function ('module:factory') that Waitress should call to get the application instance. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/waitress.rst#_snippet_2 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
# equivalent to 'from hello import create_app; create_app()' |
|
$ waitress-serve --host 127.0.0.1 --call hello:create_app |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Testing Dependencies for Flask |
|
DESCRIPTION: Instructions to install the `pytest` and `coverage` libraries using pip, which are essential for writing and measuring unit tests in Flask applications. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_0 |
|
|
|
LANGUAGE: none |
|
CODE: |
|
``` |
|
$ pip install pytest coverage |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Implement RESTful API with Flask MethodView |
|
DESCRIPTION: Provides a comprehensive example of building a RESTful API using Flask's `MethodView`. It defines `ItemAPI` for single resource operations (GET, PATCH, DELETE) and `GroupAPI` for collection operations (GET, POST), demonstrating how to dispatch requests to class methods based on HTTP verbs. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/views.rst#_snippet_12 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from flask.views import MethodView |
|
|
|
class ItemAPI(MethodView): |
|
init_every_request = False |
|
|
|
def __init__(self, model): |
|
self.model = model |
|
self.validator = generate_validator(model) |
|
|
|
def _get_item(self, id): |
|
return self.model.query.get_or_404(id) |
|
|
|
def get(self, id): |
|
item = self._get_item(id) |
|
return jsonify(item.to_json()) |
|
|
|
def patch(self, id): |
|
item = self._get_item(id) |
|
errors = self.validator.validate(item, request.json) |
|
|
|
if errors: |
|
return jsonify(errors), 400 |
|
|
|
item.update_from_json(request.json) |
|
db.session.commit() |
|
return jsonify(item.to_json()) |
|
|
|
def delete(self, id): |
|
item = self._get_item(id) |
|
db.session.delete(item) |
|
db.session.commit() |
|
return "", 204 |
|
|
|
class GroupAPI(MethodView): |
|
init_every_request = False |
|
|
|
def __init__(self, model): |
|
self.model = model |
|
self.validator = generate_validator(model, create=True) |
|
|
|
def get(self): |
|
items = self.model.query.all() |
|
return jsonify([item.to_json() for item in items]) |
|
|
|
def post(self): |
|
errors = self.validator.validate(request.json) |
|
|
|
if errors: |
|
return jsonify(errors), 400 |
|
|
|
db.session.add(self.model.from_json(request.json)) |
|
db.session.commit() |
|
return jsonify(item.to_json()) |
|
|
|
def register_api(app, model, name): |
|
item = ItemAPI.as_view(f"{name}-item", model) |
|
group = GroupAPI.as_view(f"{name}-group", model) |
|
app.add_url_rule(f"/{name}/<int:id>", view_func=item) |
|
app.add_url_rule(f"/{name}/", view_func=group) |
|
|
|
register_api(app, User, "users") |
|
register_api(app, Story, "stories") |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Integrating Models and Views in Flask Extensions (Python) |
|
DESCRIPTION: This example illustrates a pattern for a Flask extension that needs to define views interacting with models provided by another extension (like Flask-SQLAlchemy). It shows how the model can be defined during the extension's initialization (`__init__`) and then passed to the view factory (`as_view`) when setting up the application. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/extensiondev.rst#_snippet_3 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
class PostAPI(MethodView): |
|
def __init__(self, model): |
|
self.model = model |
|
|
|
def get(self, id): |
|
post = self.model.query.get(id) |
|
return jsonify(post.to_json()) |
|
|
|
class BlogExtension: |
|
def __init__(self, db): |
|
class Post(db.Model): |
|
id = db.Column(primary_key=True) |
|
title = db.Column(db.String, nullable=False) |
|
|
|
self.post_model = Post |
|
|
|
def init_app(self, app): |
|
api_view = PostAPI.as_view(model=self.post_model) |
|
|
|
db = SQLAlchemy() |
|
blog = BlogExtension(db) |
|
db.init_app(app) |
|
blog.init_app(app) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Run Flask Application with Waitress WSGI Server |
|
DESCRIPTION: These commands illustrate how to launch a Flask application using `waitress-serve`. The first example shows serving a direct application object, while the second demonstrates using an app factory pattern with the `--call` option. Both examples bind the server to the local loopback address `127.0.0.1`. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/waitress.rst#_snippet_1 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
# equivalent to 'from hello import app' |
|
$ waitress-serve --host 127.0.0.1 hello:app |
|
|
|
# equivalent to 'from hello import create_app; create_app()' |
|
$ waitress-serve --host 127.0.0.1 --call hello:create_app |
|
|
|
Serving on http://127.0.0.1:8080 |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Create Flask Project Directory |
|
DESCRIPTION: This snippet shows the basic shell commands to create a new project directory named `flask-tutorial` and navigate into it. This is the initial step for setting up a new Flask application. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/layout.rst#_snippet_0 |
|
|
|
LANGUAGE: none |
|
CODE: |
|
``` |
|
$ mkdir flask-tutorial |
|
$ cd flask-tutorial |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Waitress WSGI server for Flask |
|
DESCRIPTION: Instructions to install Waitress, a production-ready WSGI server, into the virtual environment using pip. Waitress is recommended for serving Flask applications in production instead of the built-in development server. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/deploy.rst#_snippet_6 |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
$ pip install waitress |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Example Flask Python Config File Content |
|
DESCRIPTION: Provides an example of the content for a Python configuration file that can be loaded by Flask's config object using `from_object` or `from_envvar`. Only uppercase variables are loaded. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/config.rst#_snippet_10 |
|
|
|
LANGUAGE: Python |
|
CODE: |
|
``` |
|
# Example configuration |
|
SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Flask File Upload Application Initialization |
|
DESCRIPTION: This code initializes a Flask application for file uploads. It imports necessary modules like os, Flask, request, and secure_filename. It defines the UPLOAD_FOLDER path and ALLOWED_EXTENSIONS set, then configures the Flask app with the upload folder. This setup is crucial for handling file uploads securely and efficiently. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/fileuploads.rst#_snippet_0 |
|
|
|
LANGUAGE: Python |
|
CODE: |
|
``` |
|
import os |
|
from flask import Flask, flash, request, redirect, url_for |
|
from werkzeug.utils import secure_filename |
|
|
|
UPLOAD_FOLDER = '/path/to/the/uploads' |
|
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} |
|
|
|
app = Flask(__name__) |
|
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Werkzeug secure_filename Function Usage Example |
|
DESCRIPTION: This example demonstrates the usage and output of the werkzeug.utils.secure_filename function in a Python REPL. It illustrates how a potentially malicious filename containing directory traversal attempts (../../..) is sanitized into a safe filename, effectively preventing path manipulation vulnerabilities when storing user-provided file names. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/fileuploads.rst#_snippet_2 |
|
|
|
LANGUAGE: Python |
|
CODE: |
|
``` |
|
>>> secure_filename('../../../../home/username/.bashrc') |
|
'home_username_.bashrc' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Python build tool |
|
DESCRIPTION: Installs the 'build' tool using pip, which is necessary for creating distribution wheel files for Python applications. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/deploy.rst#_snippet_0 |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
$ pip install build |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Define Flask Application Factory (Python) |
|
DESCRIPTION: This Python function `create_app` serves as the application factory for a Flask application. It initializes the Flask instance, configures default settings, handles instance-relative configuration, ensures the instance folder exists, and sets up a basic '/hello' route. This pattern is recommended for robust application structures, especially for testing and deployment. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/factory.rst#_snippet_1 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
import os |
|
|
|
from flask import Flask |
|
|
|
|
|
def create_app(test_config=None): |
|
# create and configure the app |
|
app = Flask(__name__, instance_relative_config=True) |
|
app.config.from_mapping( |
|
SECRET_KEY='dev', |
|
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), |
|
) |
|
|
|
if test_config is None: |
|
# load the instance config, if it exists, when not testing |
|
app.config.from_pyfile('config.py', silent=True) |
|
else: |
|
# load the test config if passed in |
|
app.config.from_mapping(test_config) |
|
|
|
# ensure the instance folder exists |
|
try: |
|
os.makedirs(app.instance_path) |
|
except OSError: |
|
pass |
|
|
|
# a simple page that says hello |
|
@app.route('/hello') |
|
def hello(): |
|
return 'Hello, World!' |
|
|
|
return app |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Understand Flask Trailing Slash Redirection Behavior |
|
DESCRIPTION: Explains how Flask handles trailing slashes in URLs, demonstrating that a route ending with a slash (`/projects/`) will redirect if accessed without it, while a route without a trailing slash (`/about`) will result in a 404 if accessed with one. This helps maintain unique URLs for SEO. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_7 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
@app.route('/projects/') |
|
def projects(): |
|
return 'The project page' |
|
|
|
@app.route('/about') |
|
def about(): |
|
return 'The about page' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Flask-MongoEngine |
|
DESCRIPTION: This snippet provides the command to install the Flask-MongoEngine library, which is a required dependency for integrating MongoDB with Flask applications using MongoEngine. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/mongoengine.rst#_snippet_0 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
pip install flask-mongoengine |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install mod_wsgi and application in a virtual environment |
|
DESCRIPTION: This snippet provides the shell commands to set up a Python virtual environment, install your Flask application, and then install the `mod_wsgi` package within that environment, preparing it for deployment. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/mod_wsgi.rst#_snippet_0 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ cd hello-app |
|
$ python -m venv .venv |
|
$ . .venv/bin/activate |
|
$ pip install . |
|
$ pip install mod_wsgi |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Running Gunicorn with Eventlet Worker (Shell) |
|
DESCRIPTION: This command starts Gunicorn using the 'eventlet' worker class for asynchronous request handling. It loads the Flask application via the 'create_app' factory function. Requires the 'eventlet' library installed. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/gunicorn.rst#_snippet_5 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ gunicorn -k eventlet 'hello:create_app()' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Running Flask application with gevent WSGI server |
|
DESCRIPTION: Demonstrates how to create a `wsgi.py` script to initialize the gevent `WSGIServer` and serve a Flask application on a specified host and port. Includes the shell command to execute the script and start the server. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/gevent.rst#_snippet_1 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from gevent.pywsgi import WSGIServer |
|
from hello import create_app |
|
|
|
app = create_app() |
|
http_server = WSGIServer(("127.0.0.1", 8000), app) |
|
http_server.serve_forever() |
|
``` |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ python wsgi.py |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Run Flask Development Server in Debug Mode (CLI) |
|
DESCRIPTION: This command-line snippet demonstrates how to start the Flask development server with debug mode enabled, which activates the built-in Werkzeug debugger. This setup is intended for development environments only due to security implications. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/debugging.rst#_snippet_0 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ flask --app hello run --debug |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Define SQLAlchemy User Model and Table |
|
DESCRIPTION: This example defines a SQLAlchemy ORM User class mapped to a 'users' table. It includes class properties for querying, an initializer, a representation method, and the table schema definition with columns and constraints, demonstrating a typical ORM setup. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/sqlalchemy.rst#_snippet_8 |
|
|
|
LANGUAGE: Python |
|
CODE: |
|
``` |
|
from sqlalchemy import Table, Column, Integer, String |
|
from sqlalchemy.orm import mapper |
|
from yourapplication.database import metadata, db_session |
|
|
|
class User(object): |
|
query = db_session.query_property() |
|
|
|
def __init__(self, name=None, email=None): |
|
self.name = name |
|
self.email = email |
|
|
|
def __repr__(self): |
|
return f'<User {self.name!r}>' |
|
|
|
users = Table('users', metadata, |
|
Column('id', Integer, primary_key=True), |
|
Column('name', String(50), unique=True), |
|
Column('email', String(120), unique=True) |
|
) |
|
mapper(User, users) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Flask - Shell |
|
DESCRIPTION: Command to install the Flask package using pip within the activated virtual environment. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/installation.rst#_snippet_4 |
|
|
|
LANGUAGE: Shell |
|
CODE: |
|
``` |
|
$ pip install Flask |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Python Project in Editable Development Mode |
|
DESCRIPTION: This command uses `pip` to install the current project in 'editable' or 'development' mode. This allows local code changes to be reflected immediately without needing to re-install, unless project metadata like dependencies are altered. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/install.rst#_snippet_1 |
|
|
|
LANGUAGE: none |
|
CODE: |
|
``` |
|
$ pip install -e . |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Sentry SDK for Flask |
|
DESCRIPTION: Install the `sentry-sdk` client with its Flask-specific dependencies using pip to enable error reporting. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/errorhandling.rst#_snippet_0 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ pip install sentry-sdk[flask] |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Example Usage of PathDispatcher with Dynamic App Creation |
|
DESCRIPTION: Demonstrates how to instantiate `PathDispatcher` by providing a `default_app` and a `make_app` function. The `make_app` function dynamically creates an application based on a user retrieved from the path prefix, showcasing the dispatcher's ability to handle dynamic application instances. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/appdispatch.rst#_snippet_6 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from myapplication import create_app, default_app, get_user_for_prefix |
|
|
|
def make_app(prefix): |
|
user = get_user_for_prefix(prefix) |
|
if user is not None: |
|
return create_app(user) |
|
|
|
application = PathDispatcher(default_app, make_app) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Run Pytest with Coverage Report (Coverage Shell) |
|
DESCRIPTION: Runs the test suite with coverage measurement enabled, generates a summary report in the console, and creates a detailed HTML report. The HTML report can be viewed in a browser to see which lines of code were executed by the tests. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/examples/tutorial/README.rst#_snippet_8 |
|
|
|
LANGUAGE: Shell |
|
CODE: |
|
``` |
|
$ coverage run -m pytest |
|
$ coverage report |
|
$ coverage html # open htmlcov/index.html in a browser |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Celery using pip |
|
DESCRIPTION: Instructions to install the Celery library from PyPI using the pip package manager. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/celery.rst#_snippet_0 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ pip install celery |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Example Usage of SubdomainDispatcher |
|
DESCRIPTION: Illustrates how to instantiate and use the `SubdomainDispatcher` with a `make_app` function. The `make_app` function dynamically creates a Flask application based on the subdomain's associated user or returns a 404 Not Found exception if no user is found. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/appdispatch.rst#_snippet_3 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
from myapplication import create_app, get_user_for_subdomain |
|
from werkzeug.exceptions import NotFound |
|
|
|
def make_app(subdomain): |
|
user = get_user_for_subdomain(subdomain) |
|
if user is None: |
|
# if there is no user for that subdomain we still have |
|
# to return a WSGI application that handles that request. |
|
# We can then just return the NotFound() exception as |
|
# application which will render a default 404 page. |
|
# You might also redirect the user to the main page then |
|
return NotFound() |
|
|
|
# otherwise create the application for the specific user |
|
return create_app(user) |
|
|
|
application = SubdomainDispatcher('example.com', make_app) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Create Virtual Environment (Windows) - Shell |
|
DESCRIPTION: Commands to create a project directory and a virtual environment named .venv within it on Windows using the py -3 -m venv command. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/installation.rst#_snippet_1 |
|
|
|
LANGUAGE: Shell |
|
CODE: |
|
``` |
|
> mkdir myproject |
|
> cd myproject |
|
> py -3 -m venv .venv |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Create and Run a Simple Flask Hello World Application |
|
DESCRIPTION: This snippet demonstrates how to create a basic 'Hello, World!' web application using Flask. It initializes a Flask app, defines a route for the root URL, and returns a simple string. The second part shows how to run the Flask development server from the command line, making the application accessible via a web browser. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/README.md#_snippet_0 |
|
|
|
LANGUAGE: python |
|
CODE: |
|
``` |
|
# save this as app.py |
|
from flask import Flask |
|
|
|
app = Flask(__name__) |
|
|
|
@app.route("/") |
|
def hello(): |
|
return "Hello, World!" |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ flask run |
|
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Run Gunicorn with Flask application module or app factory |
|
DESCRIPTION: Demonstrates how to start Gunicorn, specifying the Flask application entry point. You can use either a module and app variable (e.g., 'hello:app') or an app factory function (e.g., 'hello:create_app()'). The '-w' option sets the number of worker processes, typically 'CPU * 2'. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/gunicorn.rst#_snippet_1 |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
# equivalent to 'from hello import app' |
|
$ gunicorn -w 4 'hello:app' |
|
``` |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
# equivalent to 'from hello import create_app; create_app()' |
|
$ gunicorn -w 4 'hello:create_app()' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Run Flask with Waitress production server |
|
DESCRIPTION: Command to start the Flask application using the Waitress WSGI server. It specifies how to call the application factory ('create_app') to obtain the Flask application object, making it accessible via HTTP. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/deploy.rst#_snippet_7 |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
$ waitress-serve --call 'flaskr:create_app' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Start mod_wsgi-express server with processes |
|
DESCRIPTION: This command shows how to start the `mod_wsgi-express` server, specifying the `wsgi.py` script containing your Flask application and configuring the number of worker processes to run, which can be adjusted based on CPU cores. |
|
|
|
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/mod_wsgi.rst#_snippet_2 |
|
|
|
LANGUAGE: text |
|
CODE: |
|
``` |
|
$ mod_wsgi-express start-server wsgi.py --processes 4 |
|
``` |