|
| 1 | +title: flask.app BadRequest code examples |
| 2 | +category: page |
| 3 | +slug: flask-app-badrequest-examples |
| 4 | +sortorder: 500021000 |
| 5 | +toc: False |
| 6 | +sidebartitle: flask.app BadRequest |
| 7 | +meta: Python example code for the BadRequest class from the flask.app module of the Flask project. |
| 8 | + |
| 9 | + |
| 10 | +BadRequest is a class within the flask.app module of the Flask project. |
| 11 | + |
| 12 | + |
| 13 | +## Example 1 from Flask AppBuilder |
| 14 | +[Flask-AppBuilder](https://github.com/dpgaspar/Flask-AppBuilder) |
| 15 | +([documentation](https://flask-appbuilder.readthedocs.io/en/latest/) |
| 16 | +and |
| 17 | +[example apps](https://github.com/dpgaspar/Flask-AppBuilder/tree/master/examples)) |
| 18 | +is a web application generator that uses Flask to automatically create |
| 19 | +the code for database-driven applications based on parameters set |
| 20 | +by the user. The generated applications include default security settings, |
| 21 | +forms, and internationalization support. |
| 22 | + |
| 23 | +Flask App Builder is provided under the |
| 24 | +[BSD 3-Clause "New" or "Revised" license](https://github.com/dpgaspar/Flask-AppBuilder/blob/master/LICENSE). |
| 25 | + |
| 26 | +[**Flask AppBuilder / flask_appbuilder / api / __init__.py**](https://github.com/dpgaspar/Flask-AppBuilder/blob/master/flask_appbuilder/api/__init__.py) |
| 27 | + |
| 28 | +```python |
| 29 | +# __init__.py |
| 30 | +import functools |
| 31 | +import json |
| 32 | +import logging |
| 33 | +import re |
| 34 | +import traceback |
| 35 | +from typing import Dict, Optional |
| 36 | +import urllib.parse |
| 37 | + |
| 38 | +from apispec import APISpec, yaml_utils |
| 39 | +from apispec.exceptions import DuplicateComponentNameError |
| 40 | +from flask import Blueprint, current_app, jsonify, make_response, request, Response |
| 41 | +from flask_babel import lazy_gettext as _ |
| 42 | +import jsonschema |
| 43 | +from marshmallow import ValidationError |
| 44 | +from marshmallow_sqlalchemy.fields import Related, RelatedList |
| 45 | +import prison |
| 46 | +from sqlalchemy.exc import IntegrityError |
| 47 | +~~from werkzeug.exceptions import BadRequest |
| 48 | +import yaml |
| 49 | + |
| 50 | +from .convert import Model2SchemaConverter |
| 51 | +from .schemas import get_info_schema, get_item_schema, get_list_schema |
| 52 | +from .._compat import as_unicode |
| 53 | +from ..const import ( |
| 54 | + API_ADD_COLUMNS_RES_KEY, |
| 55 | + API_ADD_COLUMNS_RIS_KEY, |
| 56 | + API_ADD_TITLE_RES_KEY, |
| 57 | + API_ADD_TITLE_RIS_KEY, |
| 58 | + API_DESCRIPTION_COLUMNS_RES_KEY, |
| 59 | + API_DESCRIPTION_COLUMNS_RIS_KEY, |
| 60 | + API_EDIT_COLUMNS_RES_KEY, |
| 61 | + API_EDIT_COLUMNS_RIS_KEY, |
| 62 | + API_EDIT_TITLE_RES_KEY, |
| 63 | + API_EDIT_TITLE_RIS_KEY, |
| 64 | + API_FILTERS_RES_KEY, |
| 65 | + API_FILTERS_RIS_KEY, |
| 66 | + API_LABEL_COLUMNS_RES_KEY, |
| 67 | + API_LABEL_COLUMNS_RIS_KEY, |
| 68 | + API_LIST_COLUMNS_RES_KEY, |
| 69 | + API_LIST_COLUMNS_RIS_KEY, |
| 70 | + API_LIST_TITLE_RES_KEY, |
| 71 | + API_LIST_TITLE_RIS_KEY, |
| 72 | + |
| 73 | + |
| 74 | +## ... source file continues with no further BadRequest examples... |
| 75 | + |
| 76 | +``` |
| 77 | + |
| 78 | + |
| 79 | +## Example 2 from Flask-WTF |
| 80 | +[Flask-WTF](https://github.com/lepture/flask-wtf) |
| 81 | +([project documentation](https://flask-wtf.readthedocs.io/en/stable/) |
| 82 | +and |
| 83 | +[PyPI page](https://pypi.org/project/Flask-WTF/)) |
| 84 | +provides a bridge between [Flask](/flask.html) and the the |
| 85 | +[WTForms](https://wtforms.readthedocs.io/en/2.3.x/) form-handling library. |
| 86 | +It makes it easier to use WTForms by reducing boilerplate code and |
| 87 | +shorter examples for common form operations as well as common security |
| 88 | +practices such as [CSRF](/cross-site-request-forgery-csrf.html). |
| 89 | + |
| 90 | +[**Flask-WTF / flask_wtf / csrf.py**](https://github.com/lepture/flask-wtf/blob/master/flask_wtf/./csrf.py) |
| 91 | + |
| 92 | +```python |
| 93 | +# csrf.py |
| 94 | +import hashlib |
| 95 | +import logging |
| 96 | +import os |
| 97 | +import warnings |
| 98 | +from functools import wraps |
| 99 | + |
| 100 | +from flask import Blueprint, current_app, g, request, session |
| 101 | +from itsdangerous import BadData, SignatureExpired, URLSafeTimedSerializer |
| 102 | +~~from werkzeug.exceptions import BadRequest |
| 103 | +from werkzeug.security import safe_str_cmp |
| 104 | +from wtforms import ValidationError |
| 105 | +from wtforms.csrf.core import CSRF |
| 106 | + |
| 107 | +from ._compat import FlaskWTFDeprecationWarning, string_types, urlparse |
| 108 | + |
| 109 | +__all__ = ('generate_csrf', 'validate_csrf', 'CSRFProtect') |
| 110 | +logger = logging.getLogger(__name__) |
| 111 | + |
| 112 | + |
| 113 | +def generate_csrf(secret_key=None, token_key=None): |
| 114 | + |
| 115 | + secret_key = _get_config( |
| 116 | + secret_key, 'WTF_CSRF_SECRET_KEY', current_app.secret_key, |
| 117 | + message='A secret key is required to use CSRF.' |
| 118 | + ) |
| 119 | + field_name = _get_config( |
| 120 | + token_key, 'WTF_CSRF_FIELD_NAME', 'csrf_token', |
| 121 | + message='A field name is required to use CSRF.' |
| 122 | + ) |
| 123 | + |
| 124 | + if field_name not in g: |
| 125 | + s = URLSafeTimedSerializer(secret_key, salt='wtf-csrf-token') |
| 126 | + |
| 127 | + |
| 128 | + |
| 129 | +## ... source file abbreviated to get to BadRequest examples ... |
| 130 | + |
| 131 | + |
| 132 | + warnings.warn(FlaskWTFDeprecationWarning( |
| 133 | + '"@csrf.error_handler" is deprecated. Use the standard Flask ' |
| 134 | + 'error system with "@app.errorhandler(CSRFError)" instead. This ' |
| 135 | + 'will be removed in 1.0.' |
| 136 | + ), stacklevel=2) |
| 137 | + |
| 138 | + @wraps(view) |
| 139 | + def handler(reason): |
| 140 | + response = current_app.make_response(view(reason)) |
| 141 | + raise CSRFError(response=response) |
| 142 | + |
| 143 | + self._error_response = handler |
| 144 | + return view |
| 145 | + |
| 146 | + |
| 147 | +class CsrfProtect(CSRFProtect): |
| 148 | + |
| 149 | + def __init__(self, app=None): |
| 150 | + warnings.warn(FlaskWTFDeprecationWarning( |
| 151 | + '"flask_wtf.CsrfProtect" has been renamed to "CSRFProtect" ' |
| 152 | + 'and will be removed in 1.0.' |
| 153 | + ), stacklevel=2) |
| 154 | + super(CsrfProtect, self).__init__(app=app) |
| 155 | + |
| 156 | + |
| 157 | +~~class CSRFError(BadRequest): |
| 158 | + |
| 159 | + description = 'CSRF validation failed.' |
| 160 | + |
| 161 | + |
| 162 | +def same_origin(current_uri, compare_uri): |
| 163 | + current = urlparse(current_uri) |
| 164 | + compare = urlparse(compare_uri) |
| 165 | + |
| 166 | + return ( |
| 167 | + current.scheme == compare.scheme |
| 168 | + and current.hostname == compare.hostname |
| 169 | + and current.port == compare.port |
| 170 | + ) |
| 171 | + |
| 172 | + |
| 173 | + |
| 174 | +## ... source file continues with no further BadRequest examples... |
| 175 | + |
| 176 | +``` |
| 177 | + |
0 commit comments