flask
star
bookmark_border
Create the app in a function so tests and production can each build their own.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
beginner
#structure #config #blueprints
flask
star
bookmark_border
Check the extension, size and filename before saving an upload.
import os
import uuid
from flask import request, abort
from werkzeug.utils import secure_filename
intermediate
#uploads #security #files
flask
bookmark_border
Return JSON instead of HTML for API errors.
from flask import Flask, jsonify
from werkzeug.exceptions import HTTPException
app = Flask(__name__)
beginner
#api #errors #json
flask
bookmark_border
Answer 401 JSON instead of redirecting to the login page.
from functools import wraps
from flask import jsonify
from flask_login import current_user
intermediate
#auth #decorators #api
flask
bookmark_border
Paginate with Flask-SQLAlchemy and keep page numbers safe.
from flask import request, render_template
@bp.get("/posts")
def posts():
beginner
#sqlalchemy #pagination #database
flask
bookmark_border
Stop brute-force attempts with Flask-Limiter.
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
limiter = Limiter(key_func=get_remote_address, storage_uri="memory://") # use redis:// in production
limiter.init_app(app)
beginner
#security #rate-limit #login
flask
bookmark_border
Put the token in a meta tag and send it as X-CSRFToken from JavaScript.
# base.html
# <meta name="csrf-token" content="{{ csrf_token() }}">
# app.py
from flask_wtf import CSRFProtect
beginner
#csrf #security #javascript
flask
bookmark_border
Make email-verification or reset links that expire, without a database table.
from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired
serializer = URLSafeTimedSerializer(app.config["SECRET_KEY"], salt="email-verify")
intermediate
#auth #email #tokens