Skip to content

Commit d6b0fb1

Browse files
committed
adding flask badrequest examples
1 parent 25a7e5e commit d6b0fb1

26 files changed

+222
-81
lines changed
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
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+

content/pages/examples/flask/flask-app-flask.markdown

Lines changed: 21 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
title: flask.app Flask code examples
22
category: page
33
slug: flask-app-flask-examples
4-
sortorder: 500021000
4+
sortorder: 500021001
55
toc: False
66
sidebartitle: flask.app Flask
77
meta: Python example code for the Flask class from the flask.app module of the Flask project.
@@ -23,86 +23,49 @@ forms, and internationalization support.
2323
Flask App Builder is provided under the
2424
[BSD 3-Clause "New" or "Revised" license](https://github.com/dpgaspar/Flask-AppBuilder/blob/master/LICENSE).
2525

26-
[**Flask AppBuilder / flask_appbuilder / tests / _test_ldapsearch.py**](https://github.com/dpgaspar/Flask-AppBuilder/blob/master/flask_appbuilder/tests/_test_ldapsearch.py)
26+
[**Flask AppBuilder / flask_appbuilder / tests / _test_oauth_registration_role.py**](https://github.com/dpgaspar/Flask-AppBuilder/blob/master/flask_appbuilder/tests/_test_oauth_registration_role.py)
2727

2828
```python
29-
# _test_ldapsearch.py
29+
# _test_oauth_registration_role.py
3030
import logging
3131
import unittest
3232

3333
~~from flask import Flask
3434
from flask_appbuilder import AppBuilder, SQLA
35-
import jinja2
36-
import ldap
37-
from mockldap import MockLdap
3835

3936

4037
logging.basicConfig(format="%(asctime)s:%(levelname)s:%(name)s:%(message)s")
4138
logging.getLogger().setLevel(logging.DEBUG)
4239
log = logging.getLogger(__name__)
4340

4441

45-
class LDAPSearchTestCase(unittest.TestCase):
46-
47-
top = ("o=test", {"o": ["test"]})
48-
example = ("ou=example,o=test", {"ou": ["example"]})
49-
manager = (
50-
"cn=manager,ou=example,o=test",
51-
{"cn": ["manager"], "userPassword": ["ldaptest"]},
52-
)
53-
alice = (
54-
"cn=alice,ou=example,o=test",
55-
{
56-
"cn": ["alice"],
57-
"memberOf": ["cn=group,ou=groups,o=test"],
58-
"userPassword": ["alicepw"],
59-
},
60-
)
61-
group = (
62-
"cn=group,ou=groups,o=test",
63-
{"cn": ["group"], "member": ["cn=alice,ou=example,o=test"]},
64-
)
65-
66-
directory = dict([top, example, group, manager, alice])
67-
68-
@classmethod
69-
def setUpClass(cls):
70-
cls.mockldap = MockLdap(cls.directory)
71-
72-
@classmethod
73-
def tearDownClass(cls):
74-
del cls.mockldap
75-
42+
class OAuthRegistrationRoleTestCase(unittest.TestCase):
7643
def setUp(self):
77-
78-
self.mockldap.start()
79-
self.ldapobj = self.mockldap["ldap://localhost/"]
80-
8144
~~ self.app = Flask(__name__)
82-
self.app.jinja_env.undefined = jinja2.StrictUndefined
83-
self.db = SQLA(self.app)
84-
8545
self.app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
86-
self.app.config["AUTH_LDAP_UID_FIELD"] = "cn"
87-
self.app.config["AUTH_LDAP_ALLOW_SELF_SIGNED"] = False
88-
self.app.config["AUTH_LDAP_USE_TLS"] = False
89-
self.app.config["AUTH_LDAP_SERVER"] = "ldap://localhost/"
90-
self.app.config["AUTH_LDAP_SEARCH"] = "ou=example,o=test"
91-
self.app.config["AUTH_LDAP_APPEND_DOMAIN"] = False
92-
self.app.config["AUTH_LDAP_FIRSTNAME_FIELD"] = None
93-
self.app.config["AUTH_LDAP_LASTNAME_FIELD"] = None
94-
self.app.config["AUTH_LDAP_EMAIL_FIELD"] = None
46+
self.db = SQLA(self.app)
9547

9648
def tearDown(self):
97-
self.mockldap.stop()
98-
del self.ldapobj
99-
log.debug("TEAR DOWN")
100-
10149
self.appbuilder = None
10250
self.app = None
10351
self.db = None
10452

105-
def test_ldapsearch(self):
53+
def test_self_registration_not_enabled(self):
54+
self.app.config["AUTH_USER_REGISTRATION"] = False
55+
self.appbuilder = AppBuilder(self.app, self.db.session)
56+
57+
result = self.appbuilder.sm.auth_user_oauth(userinfo={"username": "testuser"})
58+
59+
self.assertIsNone(result)
60+
self.assertEqual(len(self.appbuilder.sm.get_all_users()), 0)
61+
62+
def test_register_and_attach_static_role(self):
63+
self.app.config["AUTH_USER_REGISTRATION"] = True
64+
self.app.config["AUTH_USER_REGISTRATION_ROLE"] = "Public"
65+
self.appbuilder = AppBuilder(self.app, self.db.session)
66+
67+
user = self.appbuilder.sm.auth_user_oauth(userinfo={"username": "testuser"})
68+
10669

10770

10871
## ... source file continues with no further Flask examples...

content/pages/examples/flask/flask-app-headers.markdown

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
title: flask.app Headers code examples
22
category: page
33
slug: flask-app-headers-examples
4-
sortorder: 500021001
4+
sortorder: 500021002
55
toc: False
66
sidebartitle: flask.app Headers
77
meta: Python example code for the Headers class from the flask.app module of the Flask project.

content/pages/examples/flask/flask-blueprints-blueprint.markdown

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
title: flask.blueprints Blueprint code examples
22
category: page
33
slug: flask-blueprints-blueprint-examples
4-
sortorder: 500021002
4+
sortorder: 500021003
55
toc: False
66
sidebartitle: flask.blueprints Blueprint
77
meta: Python example code for the Blueprint class from the flask.blueprints module of the Flask project.

content/pages/examples/flask/flask-cli-flaskgroup.markdown

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
title: flask.cli FlaskGroup code examples
22
category: page
33
slug: flask-cli-flaskgroup-examples
4-
sortorder: 500021003
4+
sortorder: 500021004
55
toc: False
66
sidebartitle: flask.cli FlaskGroup
77
meta: Python example code for the FlaskGroup class from the flask.cli module of the Flask project.

content/pages/examples/flask/flask-cli-scriptinfo.markdown

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
title: flask.cli ScriptInfo code examples
22
category: page
33
slug: flask-cli-scriptinfo-examples
4-
sortorder: 500021004
4+
sortorder: 500021005
55
toc: False
66
sidebartitle: flask.cli ScriptInfo
77
meta: Python example code for the ScriptInfo class from the flask.cli module of the Flask project.

content/pages/examples/flask/flask-cli-with-appcontext.markdown

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
title: flask.cli with_appcontext code examples
22
category: page
33
slug: flask-cli-with-appcontext-examples
4-
sortorder: 500021005
4+
sortorder: 500021006
55
toc: False
66
sidebartitle: flask.cli with_appcontext
77
meta: Python example code for the with_appcontext function from the flask.cli module of the Flask project.

content/pages/examples/flask/flask-ctx-has-app-context.markdown

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
title: flask.ctx has_app_context code examples
22
category: page
33
slug: flask-ctx-has-app-context-examples
4-
sortorder: 500021006
4+
sortorder: 500021007
55
toc: False
66
sidebartitle: flask.ctx has_app_context
77
meta: Python example code for the has_app_context function from the flask.ctx module of the Flask project.

content/pages/examples/flask/flask-ctx-has-request-context.markdown

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
title: flask.ctx has_request_context code examples
22
category: page
33
slug: flask-ctx-has-request-context-examples
4-
sortorder: 500021007
4+
sortorder: 500021008
55
toc: False
66
sidebartitle: flask.ctx has_request_context
77
meta: Python example code for the has_request_context function from the flask.ctx module of the Flask project.

content/pages/examples/flask/flask-globals-current-app.markdown

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
title: flask.globals current_app code examples
22
category: page
33
slug: flask-globals-current-app-examples
4-
sortorder: 500021008
4+
sortorder: 500021009
55
toc: False
66
sidebartitle: flask.globals current_app
77
meta: Python example code for the current_app function from the flask.globals module of the Flask project.

0 commit comments

Comments
 (0)