Lin / docu_code /security_flask.txt
Zelyanoth's picture
fff
25f22bf
raw
history blame
88 kB
========================
CODE SNIPPETS
========================
TITLE: Implementing Content Security Policy (CSP) in Flask
DESCRIPTION: Sets the Content Security Policy header to control resource loading, mitigating XSS and data injection attacks. The example shows a strict policy allowing resources only from the same origin.
SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_5
LANGUAGE: Python
CODE:
```
response.headers['Content-Security-Policy'] = "default-src 'self'"
```
----------------------------------------
TITLE: Setting Secure and HttpOnly Cookies in Flask
DESCRIPTION: Demonstrates how to set a secure, HttpOnly, and SameSite=Lax cookie in Flask, enhancing security by preventing client-side script access and cross-site request forgery.
SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_9
LANGUAGE: python
CODE:
```
response.set_cookie('username', 'flask', secure=True, httponly=True, samesite='Lax')
```
----------------------------------------
TITLE: Configuring Secure Session Cookie Options in Flask
DESCRIPTION: Demonstrates how to configure Flask's session cookie with 'Secure', 'HttpOnly', and 'SameSite' options for enhanced security. 'Secure' limits cookies to HTTPS, 'HttpOnly' prevents JavaScript access, and 'SameSite='Lax'' restricts cookie sending with CSRF-prone requests.
SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_8
LANGUAGE: Python
CODE:
```
app.config.update(
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE='Lax'
)
```
----------------------------------------
TITLE: XSS Attack Example: Javascript URI in Anchor Tag
DESCRIPTION: Shows how a javascript: URI in an <a> tag's href attribute can lead to a Cross-Site Scripting (XSS) vulnerability. Browsers will execute such URIs when clicked if not properly secured, for example, by setting a Content Security Policy (CSP).
SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_3
LANGUAGE: html
CODE:
```
<a href="{{ value }}">click here</a>
<a href="javascript:alert('unsafe');">click here</a>
```
----------------------------------------
TITLE: Filtering Backspace Characters from User Input in Python
DESCRIPTION: Provides a Python example for removing backspace characters (\b) from a string. This is a security measure to prevent malicious code from rendering differently in HTML than when pasted into a terminal, although modern terminals often warn about such characters.
SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_12
LANGUAGE: python
CODE:
```
body = body.replace("\b", "")
```
----------------------------------------
TITLE: itsdangerous.TimedSerializer Class
DESCRIPTION: A class from the `itsdangerous` library used to sign and validate values with a time-based signature. It is suitable for securing cookie values or other data that requires integrity and expiration.
SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_16
LANGUAGE: APIDOC
CODE:
```
itsdangerous.TimedSerializer
```
----------------------------------------
TITLE: Mitigating Clickjacking with X-Frame-Options in Flask
DESCRIPTION: Sets the X-Frame-Options header to prevent external sites from embedding the application in an iframe, protecting against clickjacking attacks. 'SAMEORIGIN' allows embedding only by pages from the same origin.
SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_7
LANGUAGE: Python
CODE:
```
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
```
----------------------------------------
TITLE: Preventing MIME Type Sniffing with X-Content-Type-Options in Flask
DESCRIPTION: Adds the X-Content-Type-Options header with 'nosniff' to prevent browsers from guessing content types, which can lead to XSS vulnerabilities.
SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_6
LANGUAGE: Python
CODE:
```
response.headers['X-Content-Type-Options'] = 'nosniff'
```
----------------------------------------
TITLE: Setting HTTP Strict Transport Security (HSTS) Header in Flask
DESCRIPTION: Configures the HSTS header to force browsers to use HTTPS, preventing man-in-the-middle (MITM) attacks. The 'max-age' directive specifies how long the browser should remember to enforce HTTPS, and 'includeSubDomains' applies the policy to subdomains.
SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_4
LANGUAGE: Python
CODE:
```
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
```
----------------------------------------
TITLE: Flask Response.set_cookie Method
DESCRIPTION: Sets a cookie on the response object. Allows specifying various attributes to control cookie behavior and security.
SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_13
LANGUAGE: APIDOC
CODE:
```
response.set_cookie(
key: str,
value: str = '',
max_age: Optional[int] = None, # Cookie expiration in seconds
expires: Optional[Union[int, datetime]] = None, # Cookie expiration date/time
path: str = '/',
domain: Optional[str] = None,
secure: bool = False, # Transmit cookie only over HTTPS
httponly: bool = False, # Prevent client-side script access
samesite: Optional[str] = None, # 'Lax', 'Strict', or 'None'
**kwargs # Additional cookie attributes
)
```
----------------------------------------
TITLE: Configuring and Using Permanent Sessions in Flask
DESCRIPTION: Illustrates how to configure the `PERMANENT_SESSION_LIFETIME` for Flask sessions and how to mark a session as permanent within a route, ensuring it persists for the configured duration. This also impacts the cryptographic signature validation.
SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_11
LANGUAGE: python
CODE:
```
app.config.update(
PERMANENT_SESSION_LIFETIME=600
)
@app.route('/login', methods=['POST'])
def login():
...
session.clear()
session['user_id'] = user.id
session.permanent = True
...
```
----------------------------------------
TITLE: Preventing XSS with Jinja Attribute Quoting
DESCRIPTION: Demonstrates the importance of quoting attributes when using Jinja expressions in HTML to prevent Cross-Site Scripting (XSS) vulnerabilities. Unquoted attributes can allow attackers to inject malicious JavaScript handlers.
SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_1
LANGUAGE: html+jinja
CODE:
```
<input value="{{ value }}">
```
----------------------------------------
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: Generating Flask Secret Key - Shell
DESCRIPTION: Command line example using Python's `secrets` module to generate a secure hexadecimal string suitable for use as a Flask `SECRET_KEY`.
SOURCE: https://github.com/pallets/flask/blob/main/docs/config.rst#_snippet_4
LANGUAGE: text
CODE:
```
$ python -c 'import secrets; print(secrets.token_hex())'
```
----------------------------------------
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 &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')
>>> Markup.escape('<blink>hacker</blink>')
Markup('&lt;blink&gt;hacker&lt;/blink&gt;')
>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()
'Marked up » HTML'
```
----------------------------------------
TITLE: Flask Session.permanent Attribute
DESCRIPTION: A boolean attribute of the Flask session object. If set to `True`, the session cookie will persist for the duration specified by `PERMANENT_SESSION_LIFETIME`.
SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_14
LANGUAGE: APIDOC
CODE:
```
session.permanent: bool
```
----------------------------------------
TITLE: XSS Attack Example: Malicious Attribute Injection
DESCRIPTION: Illustrates a potential Cross-Site Scripting (XSS) attack where an attacker injects a malicious JavaScript handler into an unquoted HTML attribute. This code snippet shows how onmouseover=alert(document.cookie) could be injected to execute arbitrary JavaScript.
SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_2
LANGUAGE: html
CODE:
```
onmouseover=alert(document.cookie)
```
----------------------------------------
TITLE: Werkzeug secure_filename Function
DESCRIPTION: Documentation for the werkzeug.utils.secure_filename function. This function is critical for sanitizing user-provided filenames before saving them to the filesystem, preventing security vulnerabilities like directory traversal by removing unsafe characters and path components.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/fileuploads.rst#_snippet_6
LANGUAGE: APIDOC
CODE:
```
werkzeug.utils.secure_filename(filename: str) -> str
filename: str - The filename string to secure.
Returns: str - A secured version of the filename, safe for storage on a filesystem.
Description: Secures a filename to prevent directory traversal and other filesystem-related attacks by removing unsafe characters.
```
----------------------------------------
TITLE: Flask Resource Use Configuration for DoS Prevention
DESCRIPTION: Details Flask's configuration options to mitigate Denial of Service (DoS) attacks by controlling resource consumption per request. These settings help limit the amount of data, form memory, and form parts processed, preventing excessive resource usage.
SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_0
LANGUAGE: APIDOC
CODE:
```
Configuration Options:
- MAX_CONTENT_LENGTH (or Request.max_content_length): Controls maximum data read from a request. Not set by default, but blocks truly unlimited streams unless WSGI server supports it.
- MAX_FORM_MEMORY_SIZE (or Request.max_form_memory_size): Controls maximum size of non-file multipart/form-data fields. Default: 500kB.
- MAX_FORM_PARTS (or Request.max_form_parts): Controls maximum number of multipart/form-data fields parsed. Default: 1000. Combined with default max_form_memory_size, a form can occupy at most 500MB.
```
----------------------------------------
TITLE: Generate production secret key for Flask
DESCRIPTION: Provides a Python command to generate a strong, random hexadecimal string suitable for use as the SECRET_KEY in a Flask production environment. This key is vital for security, protecting session cookies and other sensitive data.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/deploy.rst#_snippet_4
LANGUAGE: shell
CODE:
```
$ python -c 'import secrets; print(secrets.token_hex())'
```
----------------------------------------
TITLE: Flask PERMANENT_SESSION_LIFETIME Configuration
DESCRIPTION: A configuration key in Flask's `app.config` that defines the lifetime of a permanent session cookie in seconds. This value is also used by Flask's default cookie implementation to validate the cryptographic signature, mitigating replay attacks.
SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_15
LANGUAGE: APIDOC
CODE:
```
app.config['PERMANENT_SESSION_LIFETIME']: int (seconds)
```
----------------------------------------
TITLE: Setting an Expiring Cookie in Flask
DESCRIPTION: Shows how to set a cookie that expires after a specified duration (e.g., 10 minutes) using the `max_age` parameter. If neither `Expires` nor `Max-Age` is set, the cookie will be removed when the browser is closed.
SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_10
LANGUAGE: python
CODE:
```
# cookie expires after 10 minutes
response.set_cookie('snakes', '3', max_age=600)
```
----------------------------------------
TITLE: Configure Flask SECRET_KEY in production
DESCRIPTION: Example of how to set the generated SECRET_KEY within the 'config.py' file, located in the Flask instance folder. This configuration overrides the development key and is essential for securing the application in production.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/deploy.rst#_snippet_5
LANGUAGE: python
CODE:
```
SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'
```
----------------------------------------
TITLE: APIDOC: `tempfile.mkstemp` Function
DESCRIPTION: Documentation for the `tempfile.mkstemp` function, which creates and opens a temporary file securely. It returns a tuple containing an OS-level handle (file descriptor) to the file and its absolute path.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_3
LANGUAGE: APIDOC
CODE:
```
tempfile.mkstemp() -> (fd: int, path: str)
fd: The file descriptor of the temporary file.
path: The absolute path to the temporary file.
```
----------------------------------------
TITLE: Run mod_wsgi-express on privileged port with user/group drop
DESCRIPTION: This example demonstrates how to run `mod_wsgi-express` as a root user to bind to privileged ports (e.g., 80) while securely dropping permissions to a non-root user and group for the worker processes, enhancing security.
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/mod_wsgi.rst#_snippet_3
LANGUAGE: text
CODE:
```
$ sudo /home/hello/.venv/bin/mod_wsgi-express start-server \
/home/hello/wsgi.py \
--user hello --group hello --port 80 --processes 4
```
----------------------------------------
TITLE: Configure Flask to Trust Proxy Headers with ProxyFix Middleware
DESCRIPTION: This Python snippet demonstrates how to apply the ProxyFix middleware from Werkzeug to a Flask application's WSGI app. It configures Flask to trust X-Forwarded-For, X-Forwarded-Proto, X-Forwarded-Host, and X-Forwarded-Prefix headers, which are set by reverse proxies to pass original client information. It's crucial to only apply this middleware if truly behind a proxy and to correctly specify the number of proxies setting each header to avoid security vulnerabilities.
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/proxy_fix.rst#_snippet_0
LANGUAGE: python
CODE:
```
from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(
app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1
)
```
----------------------------------------
TITLE: Bind uWSGI to all external IPs
DESCRIPTION: This snippet explains how to configure uWSGI to bind to all external IP addresses (`0.0.0.0`) on a non-privileged port. It includes a crucial security warning against using this setup when a reverse proxy is already in place.
SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/uwsgi.rst#_snippet_4
LANGUAGE: text
CODE:
```
$ uwsgi --http 0.0.0.0:8000 --master -p 4 -w wsgi:app
```
----------------------------------------
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: Flask File Validation and Upload Route
DESCRIPTION: This snippet defines the allowed_file function to validate file extensions and the main upload_file Flask route. The route handles both GET requests (displaying the upload form) and POST requests (processing file uploads). It checks for file presence, validates the filename, secures it using secure_filename, saves the file, and redirects the user to a download URL.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/fileuploads.rst#_snippet_1
LANGUAGE: Python
CODE:
```
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# If the user does not select a file, the browser submits an
# empty file without a filename.
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('download_file', name=filename))
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>
</form>
'''
```
----------------------------------------
TITLE: Flask send_from_directory Function
DESCRIPTION: Documentation for the flask.send_from_directory function, used to safely serve files from a specified directory. This function is essential for creating download endpoints while mitigating security risks by ensuring only files within the designated directory are accessible.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/fileuploads.rst#_snippet_7
LANGUAGE: APIDOC
CODE:
```
flask.send_from_directory(directory: str, path: str, **options) -> flask.Response
directory: str - The directory from which to send the file.
path: str - The filename or path relative to the directory to send.
options: dict - Additional options for sending the file (e.g., as_attachment=True, mimetype='image/png').
Returns: flask.Response - A response object that serves the file.
Description: Sends a file from a given directory, ensuring security by preventing access to files outside the specified directory.
```
----------------------------------------
TITLE: Disabling Autoescaping in Jinja2 Templates
DESCRIPTION: This code snippet shows how to temporarily disable autoescaping within a Jinja2 template using the '{% autoescape %}' block. This is useful when you need to explicitly inject unescaped HTML, for example, from a trusted source like a markdown converter. Caution is advised when using this feature due to potential security risks.
SOURCE: https://github.com/pallets/flask/blob/main/docs/templating.rst#_snippet_2
LANGUAGE: HTML+Jinja
CODE:
```
{% autoescape false %}
<p>autoescaping is disabled here
<p>{{ will_not_be_escaped }}
{% endautoescape %}
```
----------------------------------------
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: Execute Raw SQL Statement with SQLAlchemy Engine
DESCRIPTION: This example demonstrates how to execute a raw SQL string directly using the SQLAlchemy engine's `execute` method. It supports parameterized queries for security and flexibility, allowing direct interaction with the database when ORM is not preferred.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/sqlalchemy.rst#_snippet_14
LANGUAGE: Python
CODE:
```
engine.execute('select * from users where id = :1', [1]).first()
```
----------------------------------------
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: Test Blog Post Access Control in Flask with Pytest
DESCRIPTION: This set of tests validates access control for blog post management. `test_login_required` ensures unauthenticated users are redirected to the login page for create, update, and delete actions. `test_author_required` verifies that only the post's author can modify or delete it, returning a 403 Forbidden status otherwise. `test_exists_required` checks that a 404 Not Found status is returned if an attempt is made to access or modify a non-existent post.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_16
LANGUAGE: python
CODE:
```
@pytest.mark.parametrize('path', (
'/create',
'/1/update',
'/1/delete',
))
def test_login_required(client, path):
response = client.post(path)
assert response.headers["Location"] == "/auth/login"
def test_author_required(app, client, auth):
# change the post author to another user
with app.app_context():
db = get_db()
db.execute('UPDATE post SET author_id = 2 WHERE id = 1')
db.commit()
auth.login()
# current user can't modify other user's post
assert client.post('/1/update').status_code == 403
assert client.post('/1/delete').status_code == 403
# current user doesn't see edit link
assert b'href="/1/update"' not in client.get('/').data
@pytest.mark.parametrize('path', (
'/2/update',
'/2/delete',
))
def test_exists_required(client, auth, path):
auth.login()
assert client.post(path).status_code == 404
```
----------------------------------------
TITLE: Flask Decorator for Requiring User Authentication
DESCRIPTION: This Python decorator, 'login_required', is designed to protect Flask views by ensuring that a user is logged in before accessing them. It wraps the original view function, checks if 'g.user' is 'None' (indicating no logged-in user), and if so, redirects to the login page. Otherwise, it proceeds to execute the original view function, passing along any keyword arguments.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/views.rst#_snippet_6
LANGUAGE: python
CODE:
```
def login_required(view):
@functools.wraps(view)
def wrapped_view(**kwargs):
if g.user is None:
return redirect(url_for('auth.login'))
return view(**kwargs)
return wrapped_view
```
----------------------------------------
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: 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: Test User Logout in Flask with Pytest
DESCRIPTION: Tests the Flask logout view. This snippet ensures that after a user logs out, their `user_id` is successfully removed from the session, confirming the logout operation's effectiveness.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_14
LANGUAGE: python
CODE:
```
def test_logout(client, auth):
auth.login()
with client:
auth.logout()
assert 'user_id' not in session
```
----------------------------------------
TITLE: Test User Login and Input Validation in Flask with Pytest
DESCRIPTION: Tests the Flask login view. `test_login` verifies successful user login, redirection to the home page, and correct `session` and `g` context updates. `test_login_validate_input` utilizes `pytest.mark.parametrize` to efficiently test various invalid username/password combinations, asserting that the expected error messages are present in the response data.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_13
LANGUAGE: python
CODE:
```
def test_login(client, auth):
assert client.get('/auth/login').status_code == 200
response = auth.login()
assert response.headers["Location"] == "/"
with client:
client.get('/')
assert session['user_id'] == 1
assert g.user['username'] == 'test'
@pytest.mark.parametrize(('username', 'password', 'message'), (
('a', 'test', b'Incorrect username.'),
('test', 'a', b'Incorrect password.'),
))
def test_login_validate_input(auth, username, password, message):
response = auth.login(username, password)
assert message in response.data
```
----------------------------------------
TITLE: Flask User Login View Implementation
DESCRIPTION: This Python code defines the '/login' route for a Flask application, handling both GET and POST requests. On POST, it retrieves username and password, queries the database for the user, verifies the password hash using 'check_password_hash', and manages the user session upon successful login. It also handles incorrect credentials and redirects to the index page.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/views.rst#_snippet_3
LANGUAGE: python
CODE:
```
@bp.route('/login', methods=('GET', 'POST'))
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
db = get_db()
error = None
user = db.execute(
'SELECT * FROM user WHERE username = ?', (username,)
).fetchone()
if user is None:
error = 'Incorrect username.'
elif not check_password_hash(user['password'], password):
error = 'Incorrect password.'
if error is None:
session.clear()
session['user_id'] = user['id']
return redirect(url_for('index'))
flash(error)
return render_template('auth/login.html')
```
----------------------------------------
TITLE: Define Flask Authentication Helper Class and Pytest Fixture
DESCRIPTION: Defines an `AuthActions` class to encapsulate common authentication operations like login and logout using a Flask test client. A Pytest fixture `auth` is provided to easily access these actions in tests, simplifying authentication setup.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_10
LANGUAGE: python
CODE:
```
class AuthActions(object):
def __init__(self, client):
self._client = client
def login(self, username='test', password='test'):
return self._client.post(
'/auth/login',
data={'username': username, 'password': password}
)
def logout(self):
return self._client.get('/auth/logout')
@pytest.fixture
def auth(client):
return AuthActions(client)
```
----------------------------------------
TITLE: Manually Escape HTML in Flask Responses
DESCRIPTION: When returning raw HTML from Flask, it's crucial to escape any user-provided input to prevent injection attacks. This Python snippet demonstrates using 'markupsafe.escape' to sanitize input from a URL parameter before rendering it in the HTML response. While Jinja templates handle this automatically, manual escaping is necessary when directly embedding untrusted data.
SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_4
LANGUAGE: python
CODE:
```
from markupsafe import escape
@app.route("/<name>")
def hello(name):
return f"Hello, {escape(name)}!"
```
----------------------------------------
TITLE: Python SHA1 Checksum Stream Wrapper
DESCRIPTION: This Python code defines a `ChecksumCalcStream` class that wraps an input stream to calculate its SHA1 checksum as data is read. It includes `read` and `readline` methods to update the hash. The `generate_checksum` function demonstrates how to replace the WSGI input stream with this custom stream and retrieve the hash object.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/requestchecksum.rst#_snippet_0
LANGUAGE: python
CODE:
```
import hashlib
class ChecksumCalcStream(object):
def __init__(self, stream):
self._stream = stream
self._hash = hashlib.sha1()
def read(self, bytes):
rv = self._stream.read(bytes)
self._hash.update(rv)
return rv
def readline(self, size_hint):
rv = self._stream.readline(size_hint)
self._hash.update(rv)
return rv
def generate_checksum(request):
env = request.environ
stream = ChecksumCalcStream(env['wsgi.input'])
env['wsgi.input'] = stream
return stream._hash
```
----------------------------------------
TITLE: Load Logged-in User Before Each Flask Request
DESCRIPTION: This Flask 'before_app_request' function ensures that user information is loaded and available for every request if a user is logged in. It retrieves the 'user_id' from the session, queries the database for the corresponding user, and stores the user object in 'g.user' for the duration of the request. If no user is logged in or the ID is invalid, 'g.user' is set to 'None'.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/views.rst#_snippet_4
LANGUAGE: python
CODE:
```
@bp.before_app_request
def load_logged_in_user():
user_id = session.get('user_id')
if user_id is None:
g.user = None
else:
g.user = get_db().execute(
'SELECT * FROM user WHERE id = ?', (user_id,)
).fetchone()
```
----------------------------------------
TITLE: Handle Exceptions with Flask got_request_exception Signal
DESCRIPTION: Shows how to use the `got_request_exception` signal to log or handle unhandled exceptions during request processing. It demonstrates filtering for specific exception types like `SecurityException`.
SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_23
LANGUAGE: python
CODE:
```
from flask import got_request_exception
def log_security_exception(sender, exception, **extra):
if not isinstance(exception, SecurityException):
return
security_logger.exception(
f"SecurityException at {request.url!r}",
exc_info=exception,
)
got_request_exception.connect(log_security_exception, app)
```
----------------------------------------
TITLE: Flask Route Example for Request Checksum
DESCRIPTION: This Flask example shows how to integrate the `generate_checksum` function into a route. It illustrates that accessing request data like `request.files` will consume the input stream, allowing the checksum to be fully calculated. The final checksum can then be retrieved using `hexdigest()`.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/requestchecksum.rst#_snippet_1
LANGUAGE: python
CODE:
```
@app.route('/special-api', methods=['POST'])
def special_api():
hash = generate_checksum(request)
# Accessing this parses the input stream
files = request.files
# At this point the hash is fully constructed.
checksum = hash.hexdigest()
return f"Hash was: {checksum}"
```
----------------------------------------
TITLE: Implement Login Required Decorator in Flask
DESCRIPTION: This decorator ensures that a user is logged in before accessing a view function. If the user is not logged in, they are redirected to the 'login' page, passing the current URL as 'next'. It uses `functools.wraps` to preserve original function metadata. It assumes `g.user` stores the current user and 'login' is the login page endpoint.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/viewdecorators.rst#_snippet_0
LANGUAGE: python
CODE:
```
from functools import wraps
from flask import g, request, redirect, url_for
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if g.user is None:
return redirect(url_for('login', next=request.url))
return f(*args, **kwargs)
return decorated_function
```
----------------------------------------
TITLE: Test Blog Index View in Flask with Pytest
DESCRIPTION: Tests the blog index page's display logic. It verifies that the page correctly shows 'Log In' and 'Register' links when unauthenticated, and 'Log Out' when authenticated. Additionally, it asserts that post data (title, author, body, and an edit link for the author) is properly rendered.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_15
LANGUAGE: python
CODE:
```
import pytest
from flaskr.db import get_db
def test_index(client, auth):
response = client.get('/')
assert b"Log In" in response.data
assert b"Register" in response.data
auth.login()
response = client.get('/')
assert b'Log Out' in response.data
assert b'test title' in response.data
assert b'by test on 2018-01-01' in response.data
assert b'test\nbody' in response.data
assert b'href="/1/update"' in response.data
```
----------------------------------------
TITLE: Implement Path-based Application Dispatcher (Partial)
DESCRIPTION: Introduces the concept of dispatching applications based on URL path segments, similar to subdomain dispatching. This snippet provides the initial setup for such a dispatcher, indicating it would look at the request path instead of the host header.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/appdispatch.rst#_snippet_4
LANGUAGE: python
CODE:
```
from threading import Lock
```
----------------------------------------
TITLE: Flask User Logout Functionality
DESCRIPTION: This Python function defines the '/logout' route in Flask. It clears the user's session data, effectively logging them out. After clearing the session, it redirects the user to the application's index page, ensuring that subsequent requests will not have a logged-in user.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/views.rst#_snippet_5
LANGUAGE: python
CODE:
```
@bp.route('/logout')
def logout():
session.clear()
return redirect(url_for('index'))
```
----------------------------------------
TITLE: Test Flask Database Connection and Closure
DESCRIPTION: Verifies that `get_db` returns the same database connection within an application context and that the connection is properly closed after the context exits, preventing further database operations.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_8
LANGUAGE: python
CODE:
```
import sqlite3
import pytest
from flaskr.db import get_db
def test_get_close_db(app):
with app.app_context():
db = get_db()
assert db is get_db()
with pytest.raises(sqlite3.ProgrammingError) as e:
db.execute('SELECT 1')
assert 'closed' in str(e.value)
```
----------------------------------------
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: Flaskr Jinja2 Base Template with User Authentication and Messages
DESCRIPTION: This Jinja2 template defines the core structure for Flaskr web pages. It includes conditional rendering for user login status (displaying username, logout, register, or login links) and iterates through `get_flashed_messages()` to show system notifications. It also sets up extensible blocks for `title`, `header`, and `content`.
SOURCE: https://github.com/pallets/flask/blob/main/examples/tutorial/flaskr/templates/base.html#_snippet_0
LANGUAGE: Jinja2
CODE:
```
{% block title %}{% endblock %} - Flaskr
[Flaskr]({{ url_for\('index'\) }})
==================================
{% if g.user %}* {{ g.user\['username'\] }}
* [Log Out]({{ url_for\('auth.logout'\) }}) {% else %}
* [Register]({{ url_for\('auth.register'\) }})
* [Log In]({{ url_for\('auth.login'\) }}) {% endif %}
{% block header %}{% endblock %}
{% for message in get\_flashed\_messages() %}
{{ message }}
{% endfor %} {% block content %}{% endblock %}
```
----------------------------------------
TITLE: Test Flask Post Deletion
DESCRIPTION: This Python test verifies the deletion of a blog post. It logs in, sends a POST request to the delete endpoint for post ID 1, asserts that the response redirects to the index URL, and then confirms the post is no longer present in the database.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_20
LANGUAGE: python
CODE:
```
def test_delete(client, auth, app):
auth.login()
response = client.post('/1/delete')
assert response.headers["Location"] == "/"
with app.app_context():
db = get_db()
post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()
assert post is None
```
----------------------------------------
TITLE: Implement Subdomain-based Application Dispatcher
DESCRIPTION: Defines a WSGI application class, `SubdomainDispatcher`, that dynamically creates and manages Flask application instances based on the request's subdomain. It uses a lock for thread-safe instance management and ensures that applications are created only once per subdomain.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/appdispatch.rst#_snippet_2
LANGUAGE: python
CODE:
```
from threading import Lock
class SubdomainDispatcher:
def __init__(self, domain, create_app):
self.domain = domain
self.create_app = create_app
self.lock = Lock()
self.instances = {}
def get_application(self, host):
host = host.split(':')[0]
assert host.endswith(self.domain), 'Configuration error'
subdomain = host[:-len(self.domain)].rstrip('.')
with self.lock:
app = self.instances.get(subdomain)
if app is None:
app = self.create_app(subdomain)
self.instances[subdomain] = app
return app
def __call__(self, environ, start_response):
app = self.get_application(environ['HTTP_HOST'])
return app(environ, start_response)
```
----------------------------------------
TITLE: Create Context Local Proxy with Werkzeug LocalProxy
DESCRIPTION: This snippet demonstrates using `werkzeug.local.LocalProxy` to create a context-local proxy for a resource, such as a database connection. Accessing the `db` proxy internally calls `get_db()`, providing a convenient way to access context-bound resources similar to `current_app`.
SOURCE: https://github.com/pallets/flask/blob/main/docs/appcontext.rst#_snippet_3
LANGUAGE: python
CODE:
```
from werkzeug.local import LocalProxy
db = LocalProxy(get_db)
```
----------------------------------------
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: Basic Flask Application with Message Flashing
DESCRIPTION: This Python code demonstrates a complete Flask application setup for message flashing. It includes routes for the index and a login page, handling POST requests to validate credentials, flashing success messages, and redirecting users. A secret key is set for session management.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/flashing.rst#_snippet_0
LANGUAGE: Python
CODE:
```
from flask import Flask, flash, redirect, render_template, \
request, url_for
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or \
request.form['password'] != 'secret':
error = 'Invalid credentials'
else:
flash('You were successfully logged in')
return redirect(url_for('index'))
return render_template('login.html', error=error)
```
----------------------------------------
TITLE: Handling Subdomains with Nested Blueprints
DESCRIPTION: Illustrates how subdomains are handled when nesting blueprints, where the child's subdomain prefixes the parent's in the final URL.
SOURCE: https://github.com/pallets/flask/blob/main/docs/blueprints.rst#_snippet_7
LANGUAGE: python
CODE:
```
parent = Blueprint('parent', __name__, subdomain='parent')
child = Blueprint('child', __name__, subdomain='child')
parent.register_blueprint(child)
app.register_blueprint(parent)
url_for('parent.child.create', _external=True)
"child.parent.domain.tld"
```
----------------------------------------
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: Define Flask Authentication Blueprint (Python)
DESCRIPTION: This Python code initializes a Flask Blueprint named 'auth' in `flaskr/auth.py`. It imports essential Flask modules and sets a URL prefix '/auth'. This blueprint serves as an organizational unit for authentication-related views and functions.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/views.rst#_snippet_0
LANGUAGE: python
CODE:
```
import functools
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from werkzeug.security import check_password_hash, generate_password_hash
from flaskr.db import get_db
bp = Blueprint('auth', __name__, url_prefix='/auth')
```
----------------------------------------
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: Test Flask Post Update Functionality
DESCRIPTION: This Python test snippet verifies the update functionality for a blog post. It asserts that a GET request to the update page returns a 200 status, then posts data to update a post, and finally checks the database to confirm the post's title has been successfully updated.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_18
LANGUAGE: python
CODE:
```
assert client.get('/1/update').status_code == 200
client.post('/1/update', data={'title': 'updated', 'body': ''})
with app.app_context():
db = get_db()
post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()
assert post['title'] == 'updated'
```
----------------------------------------
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: Flask Proxy Object Behavior and Access
DESCRIPTION: Explains the nature of Flask's proxy objects, their limitations (e.g., type checking), and how to access the underlying proxied object using `_get_current_object`.
SOURCE: https://github.com/pallets/flask/blob/main/docs/reqcontext.rst#_snippet_5
LANGUAGE: APIDOC
CODE:
```
Flask Proxy Objects:
Description:
- Objects provided by Flask are proxies to other objects.
- Accessed uniformly per worker thread, but point to unique underlying objects.
Considerations:
- Type Checks: Proxy objects cannot fake their type. Perform instance checks on the object being proxied.
- Underlying Reference: Needed for sending signals or passing data to background threads.
Accessing Underlying Object:
- Method: werkzeug.local.LocalProxy._get_current_object()
- Usage: app = current_app._get_current_object()
- Example: my_signal.send(app)
```
----------------------------------------
TITLE: Jinja Template for Index Page (index.html)
DESCRIPTION: This Jinja template (`index.html`) extends `layout.html` and provides a simple overview page. It includes a link to the login page, demonstrating how child templates can inherit from a base layout that handles message flashing.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/flashing.rst#_snippet_2
LANGUAGE: HTML+Jinja
CODE:
```
{% extends "layout.html" %}
{% block body %}
<h1>Overview</h1>
<p>Do you want to <a href="{{ url_for('login') }}">log in?</a>
{% endblock %}
```
----------------------------------------
TITLE: Logging User Actions in a Flask Route
DESCRIPTION: Demonstrates how to use `app.logger` within a Flask route to log user login attempts, both successful and failed, providing context about the user and the outcome of the authentication process.
SOURCE: https://github.com/pallets/flask/blob/main/docs/logging.rst#_snippet_0
LANGUAGE: python
CODE:
```
@app.route('/login', methods=['POST'])
def login():
user = get_user(request.form['username'])
if user.check_password(request.form['password']):
login_user(user)
app.logger.info('%s logged in successfully', user.username)
return redirect(url_for('index'))
else:
app.logger.info('%s failed to log in', user.username)
abort(401)
```
----------------------------------------
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: Manage Database Connection with Flask g Object and Teardown
DESCRIPTION: This example shows how to manage a database connection using Flask's `g` object. The `get_db` function ensures a single connection per application context, while `teardown_db` is registered with `@app.teardown_appcontext` to automatically close the connection when the context ends, ensuring proper resource cleanup.
SOURCE: https://github.com/pallets/flask/blob/main/docs/appcontext.rst#_snippet_2
LANGUAGE: python
CODE:
```
from flask import g
def get_db():
if 'db' not in g:
g.db = connect_to_database()
return g.db
@app.teardown_appcontext
def teardown_db(exception):
db = g.pop('db', None)
if db is not None:
db.close()
```
----------------------------------------
TITLE: Flask Session Interface Classes API Reference
DESCRIPTION: Documents the classes that provide a way to replace Flask's session implementation, including `SessionInterface`, `SecureCookieSessionInterface`, `SecureCookieSession`, `NullSession`, and `SessionMixin`. Notes that `PERMANENT_SESSION_LIFETIME` can be an integer or `timedelta`.
SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_5
LANGUAGE: APIDOC
CODE:
```
SessionInterface:
Type: Class
Description: Provides a simple way to replace the session implementation.
Members: All members are documented.
SecureCookieSessionInterface:
Type: Class
Description: Secure cookie-based session interface.
Members: All members are documented.
SecureCookieSession:
Type: Class
Description: Secure cookie session object.
Members: All members are documented.
NullSession:
Type: Class
Description: A session implementation that does nothing.
Members: All members are documented.
SessionMixin:
Type: Class
Description: Mixin for session objects.
Members: All members are documented.
Notice:
The PERMANENT_SESSION_LIFETIME config can be an integer or timedelta. The Flask.permanent_session_lifetime attribute is always a timedelta.
```
----------------------------------------
TITLE: Jinja Template for Login Page (login.html)
DESCRIPTION: This Jinja template (`login.html`) extends `layout.html` and provides a login form. It displays any `error` message passed from the Flask view and includes input fields for username and password, demonstrating form submission within the flashing context.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/flashing.rst#_snippet_3
LANGUAGE: HTML+Jinja
CODE:
```
{% extends "layout.html" %}
{% block body %}
<h1>Login</h1>
{% if error %}
<p class=error><strong>Error:</strong> {{ error }}
{% endif %}
<form method=post>
<dl>
<dt>Username:
<dd><input type=text name=username value="{{
request.form.username }}">
<dt>Password:
<dd><input type=password name=password>
</dl>
<p><input type=submit value=Login>
</form>
{% endblock %}
```
----------------------------------------
TITLE: Embed Server-Side Data in JavaScript using Jinja tojson Filter
DESCRIPTION: This Jinja template snippet shows how to safely embed server-side data (e.g., `chart_data`) directly into a JavaScript block. The `tojson` filter is crucial for converting the data into a valid JavaScript object and escaping unsafe HTML characters, preventing `SyntaxError` in the browser.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/javascript.rst#_snippet_1
LANGUAGE: jinja
CODE:
```
<script>
const chart_data = {{ chart_data|tojson }}
chartLib.makeChart(chart_data)
</script>
```
----------------------------------------
TITLE: Handle Redirects in JavaScript Fetch Responses
DESCRIPTION: This JavaScript example shows how to programmatically handle redirects after a `fetch` request. It checks the `response.redirected` property and, if true, manually updates `window.location` to the new URL provided by `response.url`, effectively changing the page after a server-side redirect.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/javascript.rst#_snippet_8
LANGUAGE: javascript
CODE:
```
fetch("/login", {"body": ...}).then(
response => {
if (response.redirected) {
window.location = response.url
} else {
showLoginError()
}
}
)
```
----------------------------------------
TITLE: Clean Up with Flask appcontext_tearing_down Signal
DESCRIPTION: Demonstrates how to use the `appcontext_tearing_down` signal for application context cleanup. This signal is always called, even on exceptions, and can be used for tasks like closing database sessions.
SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_27
LANGUAGE: python
CODE:
```
def close_db_connection(sender, **extra):
session.close()
from flask import appcontext_tearing_down
appcontext_tearing_down.connect(close_db_connection, 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: Flask: Helper Function to Get Blog Post by ID
DESCRIPTION: This Python function retrieves a blog post from the database by its ID. It includes error handling to abort with a 404 status if the post doesn't exist and a 403 status if `check_author` is true and the logged-in user is not the post's author. This function is designed to be reusable across update and delete views.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/blog.rst#_snippet_7
LANGUAGE: python
CODE:
```
def get_post(id, check_author=True):
post = get_db().execute(
'SELECT p.id, title, body, created, author_id, username'
' FROM post p JOIN user u ON p.author_id = u.id'
' WHERE p.id = ?',
(id,)
).fetchone()
if post is None:
abort(404, f"Post id {id} doesn't exist.")
if check_author and post['author_id'] != g.user['id']:
abort(403)
return post
```
----------------------------------------
TITLE: Setting Nested Config via Environment Variable (Shell)
DESCRIPTION: Demonstrates how to set a nested configuration value using environment variables with double underscores as separators, specifically for a Flask application.
SOURCE: https://github.com/pallets/flask/blob/main/docs/config.rst#_snippet_18
LANGUAGE: text
CODE:
```
$ export FLASK_MYAPI__credentials__username=user123
```
----------------------------------------
TITLE: Jinja2 Login Page Template Structure
DESCRIPTION: This snippet illustrates the fundamental structure of a Jinja2 template for a login page. It extends a 'base.html' template and defines 'header' and 'content' blocks, including a title and placeholders for username and password fields.
SOURCE: https://github.com/pallets/flask/blob/main/examples/tutorial/flaskr/templates/auth/login.html#_snippet_0
LANGUAGE: Jinja2
CODE:
```
{% extends 'base.html' %} {% block header %}
{% block title %}Log In{% endblock %}
=====================================
{% endblock %} {% block content %}
Username Password
{% endblock %}
```
----------------------------------------
TITLE: Combine Flask Applications with DispatcherMiddleware
DESCRIPTION: Shows how to use Werkzeug's DispatcherMiddleware to combine multiple Flask applications (or any WSGI apps) under different URL prefixes, such as a frontend app on '/' and a backend app on '/backend'. This allows entirely separated applications to work next to each other in the same Python interpreter process.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/appdispatch.rst#_snippet_1
LANGUAGE: python
CODE:
```
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from frontend_app import application as frontend
from backend_app import application as backend
application = DispatcherMiddleware(frontend, {
'/backend': backend
})
```
----------------------------------------
TITLE: Fetching Single Result with query_db
DESCRIPTION: Example of using the `query_db` function to fetch a single row based on a condition, demonstrating safe parameter passing using question marks to prevent SQL injection.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/sqlite3.rst#_snippet_8
LANGUAGE: Python
CODE:
```
user = query_db('select * from users where username = ?',
[the_username], one=True)
if user is None:
print('No such user')
else:
print(the_username, 'has the id', user['user_id'])
```
----------------------------------------
TITLE: Flask: Handling 400 Bad Request and 404 Not Found with abort
DESCRIPTION: This Python snippet demonstrates how to use `flask.abort` within a route to signal HTTP errors. It aborts with a 400 Bad Request if a required username is missing from query arguments, and a 404 Not Found if the provided username does not correspond to an existing user.
SOURCE: https://github.com/pallets/flask/blob/main/docs/errorhandling.rst#_snippet_7
LANGUAGE: python
CODE:
```
from flask import abort, render_template, request
# a username needs to be supplied in the query args
# a successful request would be like /profile?username=jack
@app.route("/profile")
def user_profile():
username = request.arg.get("username")
# if a username isn't supplied in the request, return a 400 bad request
if username is None:
abort(400)
user = get_user(username=username)
# if a user can't be found by their username, return 404 not found
if user is None:
abort(404)
return render_template("profile.html", user=user)
```
----------------------------------------
TITLE: Flask Session Object API Reference and Usage
DESCRIPTION: Documents the `session` object, which allows remembering information across requests using signed cookies. It behaves like a dictionary and tracks modifications. Requires `Flask.secret_key` to be set. Includes an example of explicitly marking a session as modified.
SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_4
LANGUAGE: APIDOC
CODE:
```
session:
Type: Global Proxy Object (dict-like)
Description: Stores information across requests using a signed cookie. Requires Flask.secret_key.
Attributes:
new: bool - True if the session is new.
modified: bool - True if the session object detected a modification. Be advised that modifications on mutable structures are not picked up automatically; set this attribute to True yourself.
permanent: bool - If set to True, the session lives for Flask.permanent_session_lifetime seconds (default 31 days). If set to False (default), the session will be deleted when the user closes the browser.
Notes: This is a proxy. See :ref:`notes-on-proxies` for more information.
```
LANGUAGE: python
CODE:
```
# this change is not picked up because a mutable object (here
# a list) is changed.
session['objects'].append(42)
# so mark it as modified yourself
session.modified = True
```
----------------------------------------
TITLE: Test Flask User Registration View and Input Validation
DESCRIPTION: Tests the user registration view, verifying successful rendering on GET requests, redirection to login on valid POST data, and proper storage of user data in the database. It also includes parameterized tests for invalid input scenarios and expected error messages.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_11
LANGUAGE: python
CODE:
```
import pytest
from flask import g, session
from flaskr.db import get_db
def test_register(client, app):
assert client.get('/auth/register').status_code == 200
response = client.post(
'/auth/register', data={'username': 'a', 'password': 'a'}
)
assert response.headers["Location"] == "/auth/login"
with app.app_context():
assert get_db().execute(
"SELECT * FROM user WHERE username = 'a'",
).fetchone() is not None
@pytest.mark.parametrize(('username', 'password', 'message'), (
('', '', b'Username is required.'),
('a', '', b'Password is required.'),
('test', 'test', b'already registered'),
))
def test_register_validate_input(client, username, password, message):
response = client.post(
'/auth/register',
data={'username': username, 'password': password}
)
assert message in response.data
```
----------------------------------------
TITLE: Clean Up with Flask request_tearing_down Signal
DESCRIPTION: Provides an example of connecting to the `request_tearing_down` signal, which is always called when a request is tearing down, even if an exception occurred. Useful for resource cleanup like closing database connections.
SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_25
LANGUAGE: python
CODE:
```
def close_db_connection(sender, **extra):
session.close()
from flask import request_tearing_down
request_tearing_down.connect(close_db_connection, app)
```
----------------------------------------
TITLE: Implement User Registration View Function in Flask (Python)
DESCRIPTION: This Python code defines the `register` view for the Flask 'auth' blueprint, handling GET and POST requests. It validates user input, hashes passwords, and inserts new users into the database. Upon successful registration, it redirects to the login page; otherwise, it flashes an error message.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/views.rst#_snippet_2
LANGUAGE: python
CODE:
```
@bp.route('/register', methods=('GET', 'POST'))
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
db = get_db()
error = None
if not username:
error = 'Username is required.'
elif not password:
error = 'Password is required.'
if error is None:
try:
db.execute(
"INSERT INTO user (username, password) VALUES (?, ?)",
(username, generate_password_hash(password)),
)
db.commit()
except db.IntegrityError:
error = f"User {username} is already registered."
else:
return redirect(url_for("auth.login"))
flash(error)
return render_template('auth/register.html')
```
----------------------------------------
TITLE: Pass Minimal Data to Celery Tasks (User ID Example)
DESCRIPTION: This snippet illustrates the best practice for passing data to Celery tasks: pass only the minimal, serializable data required to re-fetch or recreate complex objects within the task itself. Instead of passing a non-serializable SQLAlchemy user object, the example passes only the `user_id`, allowing the task to query the database for the user object independently. This prevents serialization issues and ensures task robustness.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/celery.rst#_snippet_12
LANGUAGE: python
CODE:
```
@shared_task
def generate_user_archive(user_id: str) -> None:
user = db.session.get(User, user_id)
...
generate_user_archive.delay(current_user.id)
```
----------------------------------------
TITLE: Git Ignore Configuration for Flask Project (.gitignore)
DESCRIPTION: This `.gitignore` file snippet provides a list of common files and directories that should be ignored by Git in a Flask project. These typically include generated files, virtual environments, and build artifacts to keep the repository clean.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/layout.rst#_snippet_3
LANGUAGE: none
CODE:
```
.venv/
*.pyc
__pycache__/
instance/
.pytest_cache/
.coverage
htmlcov/
dist/
build/
*.egg-info/
```
----------------------------------------
TITLE: APIDOC: Flask `TESTING` Configuration Flag
DESCRIPTION: Documentation for the `TESTING` configuration flag in Flask. When set to `True`, it indicates that the application is running in test mode, which can alter internal Flask behavior and affect how extensions operate to facilitate testing.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_4
LANGUAGE: APIDOC
CODE:
```
app.config['TESTING'] = True
Description: A boolean flag that enables test mode for the Flask application.
Effect: Modifies Flask's internal behavior and can be used by extensions to simplify testing.
```
----------------------------------------
TITLE: Accessing Nested Config from Flask App (Python)
DESCRIPTION: Shows how to access a nested configuration value within a Flask application's config object after it has been loaded from environment variables using the double underscore convention.
SOURCE: https://github.com/pallets/flask/blob/main/docs/config.rst#_snippet_19
LANGUAGE: python
CODE:
```
app.config["MYAPI"]["credentials"]["username"] # Is "user123"
```
----------------------------------------
TITLE: Flask Core Application and Request Utilities API
DESCRIPTION: This section documents various Flask functions related to request and application context, URL generation, response handling, and flow control. These functions are typically available within an active application or request context.
SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_10
LANGUAGE: APIDOC
CODE:
```
has_request_context()
copy_current_request_context()
has_app_context()
url_for()
abort()
redirect()
make_response()
after_this_request()
send_file()
send_from_directory()
```
----------------------------------------
TITLE: Testing Flask Request Context with Manual Preprocessing
DESCRIPTION: This Python snippet demonstrates how to use `app.test_request_context` to simulate a request for testing. It shows that `before_request` functions are not automatically called, and how `app.preprocess_request()` can be manually invoked to run these functions, allowing access to context-dependent variables like `g.user`.
SOURCE: https://github.com/pallets/flask/blob/main/docs/testing.rst#_snippet_11
LANGUAGE: python
CODE:
```
def test_auth_token(app):
with app.test_request_context("/user/2/edit", headers={"X-Auth-Token": "1"}):
app.preprocess_request()
assert g.user.name == "Flask"
```
----------------------------------------
TITLE: Jinja Template for Filtering Flashed Messages by Category
DESCRIPTION: This Jinja template snippet demonstrates how to filter flashed messages by category using `category_filter`. It allows rendering specific message types (e.g., 'error' messages) in dedicated blocks, providing more granular control over their display and styling.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/flashing.rst#_snippet_6
LANGUAGE: HTML+Jinja
CODE:
```
{% with errors = get_flashed_messages(category_filter=["error"]) %}
{% if errors %}
<div class="alert-message block-message error">
<a class="close" href="#">×</a>
<ul>
{%- for msg in errors %}
<li>{{ msg }}</li>
{% endfor -%}
</ul>
</div>
{% endif %}
{% endwith %}
```
----------------------------------------
TITLE: Flask Class-based View Handling URL Variables
DESCRIPTION: Shows a `DetailView` class designed to handle URL variables. The `id` captured from the URL is passed as a keyword argument to the `dispatch_request` method, allowing the view to fetch a specific item based on its ID.
SOURCE: https://github.com/pallets/flask/blob/main/docs/views.rst#_snippet_4
LANGUAGE: python
CODE:
```
class DetailView(View):
def __init__(self, model):
self.model = model
self.template = f"{model.__name__.lower()}/detail.html"
def dispatch_request(self, id):
item = self.model.query.get_or_404(id)
return render_template(self.template, item=item)
app.add_url_rule(
"/users/<int:id>",
view_func=DetailView.as_view("user_detail", User)
)
```
----------------------------------------
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: Flask Signal: appcontext_tearing_down
DESCRIPTION: This signal is sent when the app context is tearing down. It is always called, even if an exception is caused. It also passes an `exc` keyword argument with a reference to the exception if one occurred.
SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_28
LANGUAGE: APIDOC
CODE:
```
appcontext_tearing_down: Signal
Sent when the application context is tearing down.
Parameters:
sender: The application instance.
exc (optional): The exception that caused the teardown, if any.
**extra: Additional keyword arguments.
```
----------------------------------------
TITLE: Registering Database Functions with Flask App Context (Python)
DESCRIPTION: This Python snippet demonstrates how to register database cleanup and command-line initialization functions (`close_db`, `init_db_command`) with a Flask application instance. It utilizes `app.teardown_appcontext` to ensure cleanup after responses and `app.cli.add_command` to make `init_db_command` available via the Flask CLI.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/database.rst#_snippet_3
LANGUAGE: python
CODE:
```
def init_app(app):
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command)
```
----------------------------------------
TITLE: Temporarily Set User with Flask appcontext_pushed Signal
DESCRIPTION: Illustrates using the `appcontext_pushed` signal with a context manager to temporarily set a user on the `g` object for testing purposes. This signal is sent when an application context is pushed.
SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_29
LANGUAGE: python
CODE:
```
from contextlib import contextmanager
from flask import appcontext_pushed
@contextmanager
def user_set(app, user):
def handler(sender, **kwargs):
g.user = user
with appcontext_pushed.connected_to(handler, app):
yield
# And in the testcode:
def test_user_me(self):
with user_set(app, 'john'):
c = app.test_client()
resp = c.get('/users/me')
assert resp.data == 'username=john'
```
----------------------------------------
TITLE: Flask Signal: request_tearing_down
DESCRIPTION: This signal is sent when the request is tearing down. It is always called, even if an exception is caused. As of Flask 0.9, it also passes an `exc` keyword argument with a reference to the exception if one occurred.
SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_26
LANGUAGE: APIDOC
CODE:
```
request_tearing_down: Signal
Sent when the request is tearing down.
Parameters:
sender: The application instance.
exc (optional): The exception that caused the teardown, if any.
**extra: Additional keyword arguments.
```
----------------------------------------
TITLE: Embed Server-Side Data in HTML Data Attribute using Jinja tojson Filter
DESCRIPTION: This Jinja template snippet illustrates an alternative method for passing server-side data to JavaScript by embedding it within an HTML `data-` attribute. It's important to use single quotes around the value when using the `tojson` filter in this context to ensure valid and safe HTML.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/javascript.rst#_snippet_2
LANGUAGE: jinja
CODE:
```
<div data-chart='{{ chart_data|tojson }}'></div>
```
----------------------------------------
TITLE: Flask Application with Combined URL Processors and Simplified Routes
DESCRIPTION: Presents a complete Flask application demonstrating the combined use of `url_defaults` and `url_value_preprocessor` to handle language codes automatically, simplifying the view functions.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/urlprocessors.rst#_snippet_3
LANGUAGE: Python
CODE:
```
from flask import Flask, g
app = Flask(__name__)
@app.url_defaults
def add_language_code(endpoint, values):
if 'lang_code' in values or not g.lang_code:
return
if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
values['lang_code'] = g.lang_code
@app.url_value_preprocessor
def pull_lang_code(endpoint, values):
g.lang_code = values.pop('lang_code', None)
@app.route('/<lang_code>/')
def index():
...
@app.route('/<lang_code>/about')
def about():
...
```
----------------------------------------
TITLE: Flask Request Object and Global Proxy API Reference
DESCRIPTION: Documents the Request object, which provides access to incoming request data, and the global 'request' proxy object. Flask parses incoming request data and ensures thread-safe access. Excludes the 'json_module' member.
SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_2
LANGUAGE: APIDOC
CODE:
```
Request:
Type: Class
Description: Provides access to incoming request data.
Members: All members and inherited members are documented, excluding 'json_module'.
request:
Type: Global Proxy Object (instance of flask.Request)
Description: Used to access incoming request data. Flask parses data and ensures correct data for the active thread in multithreaded environments.
Notes: This is a proxy. See :ref:`notes-on-proxies` for more information.
```
----------------------------------------
TITLE: Example Usage of connected_to for Signal Subscription
DESCRIPTION: This snippet shows how to use the `captured_templates` function (modified to utilize `connected_to`) to record template rendering. The `templates` list is passed directly to the function, and the `with` block ensures the subscription is active only for its duration, making it suitable for focused testing or auditing.
SOURCE: https://github.com/pallets/flask/blob/main/docs/signals.rst#_snippet_3
LANGUAGE: Python
CODE:
```
templates = []
with captured_templates(app, templates, **extra):
...
template, context = templates[0]
```
----------------------------------------
TITLE: Define WTForms Registration Form Class
DESCRIPTION: This Python class defines a registration form using WTForms, specifying fields like username, email, password, and terms of service acceptance, along with validators for length, data presence, and password matching.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/wtforms.rst#_snippet_0
LANGUAGE: python
CODE:
```
from wtforms import Form, BooleanField, StringField, PasswordField, validators
class RegistrationForm(Form):
username = StringField('Username', [validators.Length(min=4, max=25)])
email = StringField('Email Address', [validators.Length(min=6, max=35)])
password = PasswordField('New Password', [
validators.DataRequired(),
validators.EqualTo('confirm', message='Passwords must match')
])
confirm = PasswordField('Repeat Password')
accept_tos = BooleanField('I accept the TOS', [validators.DataRequired()])
```
----------------------------------------
TITLE: Flask Endpoint for Serving Uploaded Files
DESCRIPTION: This code defines a Flask route (/uploads/<name>) to serve uploaded files from the configured UPLOAD_FOLDER. It utilizes the flask.send_from_directory function to safely send files, which is crucial for preventing directory traversal attacks when users request files by name, ensuring only files within the designated upload directory are accessible.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/fileuploads.rst#_snippet_3
LANGUAGE: Python
CODE:
```
from flask import send_from_directory
@app.route('/uploads/<name>')
def download_file(name):
return send_from_directory(app.config["UPLOAD_FOLDER"], name)
```
----------------------------------------
TITLE: Config Class with Dynamic Property (Python)
DESCRIPTION: Illustrates how to use Python properties within configuration classes to define dynamic configuration values that depend on other settings within the class, such as constructing a database URI from a server address.
SOURCE: https://github.com/pallets/flask/blob/main/docs/config.rst#_snippet_25
LANGUAGE: python
CODE:
```
class Config(object):
"""Base config, uses staging database server."""
TESTING = False
DB_SERVER = '192.168.1.56'
@property
def DATABASE_URI(self): # Note: all caps
return f"mysql://user@{self.DB_SERVER}/foo"
class ProductionConfig(Config):
"""Uses production database server."""
DB_SERVER = '192.168.19.32'
class DevelopmentConfig(Config):
```
----------------------------------------
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: Flask Blog Post Deletion Endpoint (flaskr/blog.py)
DESCRIPTION: This Python Flask snippet defines the `delete` view for a blog post. It handles POST requests to the `/<int:id>/delete` URL, ensures the user is logged in, retrieves the post to confirm its existence, deletes the corresponding entry from the 'post' table in the database, commits the transaction, and then redirects the user to the blog index page.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/blog.rst#_snippet_10
LANGUAGE: python
CODE:
```
@bp.route('/<int:id>/delete', methods=('POST',))
@login_required
def delete(id):
get_post(id)
db = get_db()
db.execute('DELETE FROM post WHERE id = ?', (id,))
db.commit()
return redirect(url_for('blog.index'))
```
----------------------------------------
TITLE: Serving a Single-Page Application with a Flask API
DESCRIPTION: This Flask application demonstrates how to serve a Single-Page Application (SPA) by configuring a static folder for frontend files and creating a catch-all route that serves the SPA's index.html. It also includes a simple '/heartbeat' API endpoint for health checks.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/singlepageapplications.rst#_snippet_0
LANGUAGE: Python
CODE:
```
from flask import Flask, jsonify
app = Flask(__name__, static_folder='app', static_url_path="/app")
@app.route("/heartbeat")
def heartbeat():
return jsonify({"status": "healthy"})
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
return app.send_static_file("index.html")
```
----------------------------------------
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: Flask: Application-level 404 Handler for Blueprint URL Errors
DESCRIPTION: This Python snippet highlights that 404/405 error handlers defined on blueprints are only triggered by explicit `raise` or `abort` calls within the blueprint's views. For invalid URLs not owned by a blueprint, the handler must be defined at the application level to catch all such errors.
SOURCE: https://github.com/pallets/flask/blob/main/docs/errorhandling.rst#_snippet_15
LANGUAGE: python
CODE:
```
from flask import jsonify, render_template
# at the application level
# not the blueprint level
@app.errorhandler(404)
```
----------------------------------------
TITLE: Test Blog Post Creation and Update in Flask with Pytest
DESCRIPTION: Tests the functionality of creating and updating blog posts. `test_create` verifies that the create page renders correctly on a GET request and that a POST request with valid data successfully inserts a new post into the database. `test_update` (partially shown) would similarly test the modification of existing post data.
SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_17
LANGUAGE: python
CODE:
```
def test_create(client, auth, app):
auth.login()
assert client.get('/create').status_code == 200
client.post('/create', data={'title': 'created', 'body': ''})
with app.app_context():
db = get_db()
count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0]
assert count == 2
def test_update(client, auth, app):
auth.login()
```
----------------------------------------
TITLE: Flask Signal: appcontext_popped
DESCRIPTION: This signal is sent when an application context is popped. The sender is the application. This usually falls in line with the `appcontext_tearing_down` signal.
SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_31
LANGUAGE: APIDOC
CODE:
```
appcontext_popped: Signal
Sent when an application context is popped.
Parameters:
sender: The application instance.
**kwargs: Additional keyword arguments.
```
----------------------------------------
TITLE: Query MongoEngine Documents by Field Value
DESCRIPTION: This snippet demonstrates basic querying in MongoEngine. It shows how to use the `objects` attribute of a document class to find documents based on exact field values, including the use of `get_or_404()` for retrieving a single document or raising an error if not found.
SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/mongoengine.rst#_snippet_5
LANGUAGE: python
CODE:
```
bttf = Movie.objects(title="Back To The Future").get_or_404()
```
----------------------------------------
TITLE: Flask Application Globals API Reference
DESCRIPTION: Documents the `g` object, a special namespace for storing data valid for a single request within an application context, ensuring thread-safety. Also documents the `_AppCtxGlobals` class it defaults to.
SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_8
LANGUAGE: APIDOC
CODE:
```
g:
Type: Global Proxy Object (instance of Flask.app_ctx_globals_class, defaults to ctx._AppCtxGlobals)
Description: A namespace object that can store data during an application context. Ensures thread-safety for request-specific data.
Usage Example: A `before_request` function could load a user object from a session id, then set `g.user` to be used in the view function.
Version Changed: 0.10 (Bound to the application context instead of the request context).
Notes: This is a proxy. See :ref:`notes-on-proxies` for more information.
flask.ctx._AppCtxGlobals:
Type: Class
Description: Default class for application context globals.
Members: All members are documented.
```