Skip to content

Commit bcac792

Browse files
committed
add a few more flask example code pages
1 parent b56dab6 commit bcac792

20 files changed

+2222
-17
lines changed

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
title: flask.blueprints Blueprint Python code examples
1+
title: flask.blueprints Blueprint code examples
22
category: page
33
slug: flask-blueprints-blueprint-examples
44
sortorder: 500021000

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
title: flask.cli FlaskGroup Python code examples
1+
title: flask.cli FlaskGroup code examples
22
category: page
33
slug: flask-cli-flaskgroup-examples
44
sortorder: 500021000

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
title: flask.cli ScriptInfo Python code examples
1+
title: flask.cli ScriptInfo code examples
22
category: page
33
slug: flask-cli-scriptinfo-examples
44
sortorder: 500021001

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
title: flask.cli with_appcontext Python code examples
1+
title: flask.cli with_appcontext code examples
22
category: page
33
slug: flask-cli-with-appcontext-examples
44
sortorder: 500021002
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
title: flask.ctx has_app_context code examples
2+
category: page
3+
slug: flask-ctx-has-app-context-examples
4+
sortorder: 500021000
5+
toc: False
6+
sidebartitle: flask.ctx has_app_context
7+
meta: Python example code for the has_app_context function from the flask.ctx module of the Flask project.
8+
9+
10+
has_app_context is a function within the flask.ctx module of the Flask project.
11+
12+
13+
## Example 1 from flask-restx
14+
[Flask RESTX](https://github.com/python-restx/flask-restx) is an
15+
extension that makes it easier to build
16+
[RESTful APIs](/application-programming-interfaces.html) into
17+
your applications. Flask RESTX aims for minimal configuration to
18+
get basic APIs running for existing applications and it exposes
19+
endpoint documentation using [Swagger](https://swagger.io/).
20+
21+
Flask RESTX is provided as open source under the
22+
[BSD 3-Clause license](https://github.com/python-restx/flask-restx/blob/master/LICENSE).
23+
24+
[**flask-restx / flask_restx / marshalling.py**](https://github.com/python-restx/flask-restx/blob/master/flask_restx/./marshalling.py)
25+
26+
```python
27+
# marshalling.py
28+
# -*- coding: utf-8 -*-
29+
from __future__ import unicode_literals
30+
31+
from collections import OrderedDict
32+
from functools import wraps
33+
from six import iteritems
34+
35+
~~from flask import request, current_app, has_app_context
36+
37+
from .mask import Mask, apply as apply_mask
38+
from .utils import unpack
39+
40+
41+
def make(cls):
42+
if isinstance(cls, type):
43+
return cls()
44+
return cls
45+
46+
47+
def marshal(data, fields, envelope=None, skip_none=False, mask=None, ordered=False):
48+
"""Takes raw data (in the form of a dict, list, object) and a dict of
49+
fields to output and filters the data based on those fields.
50+
51+
:param data: the actual object(s) from which the fields are taken from
52+
:param fields: a dict of whose keys will make up the final serialized
53+
response output
54+
:param envelope: optional key that will be used to envelop the serialized
55+
response
56+
:param bool skip_none: optional key will be used to eliminate fields
57+
which value is None or the field's key not
58+
exist in data
59+
:param bool ordered: Wether or not to preserve order
60+
61+
62+
## ... source file abbreviated to get to has_app_context examples ...
63+
64+
65+
def __init__(
66+
self, fields, envelope=None, skip_none=False, mask=None, ordered=False
67+
):
68+
"""
69+
:param fields: a dict of whose keys will make up the final
70+
serialized response output
71+
:param envelope: optional key that will be used to envelop the serialized
72+
response
73+
"""
74+
self.fields = fields
75+
self.envelope = envelope
76+
self.skip_none = skip_none
77+
self.ordered = ordered
78+
self.mask = Mask(mask, skip=True)
79+
80+
def __call__(self, f):
81+
@wraps(f)
82+
def wrapper(*args, **kwargs):
83+
resp = f(*args, **kwargs)
84+
mask = self.mask
85+
~~ if has_app_context():
86+
mask_header = current_app.config["RESTX_MASK_HEADER"]
87+
mask = request.headers.get(mask_header) or mask
88+
if isinstance(resp, tuple):
89+
data, code, headers = unpack(resp)
90+
return (
91+
marshal(
92+
data,
93+
self.fields,
94+
self.envelope,
95+
self.skip_none,
96+
mask,
97+
self.ordered,
98+
),
99+
code,
100+
headers,
101+
)
102+
else:
103+
return marshal(
104+
resp, self.fields, self.envelope, self.skip_none, mask, self.ordered
105+
)
106+
107+
return wrapper
108+
109+
110+
111+
112+
## ... source file continues with no further has_app_context examples...
113+
114+
115+
```
116+
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
title: flask.ctx has_request_context code examples
2+
category: page
3+
slug: flask-ctx-has-request-context-examples
4+
sortorder: 500021001
5+
toc: False
6+
sidebartitle: flask.ctx has_request_context
7+
meta: Python example code for the has_request_context function from the flask.ctx module of the Flask project.
8+
9+
10+
has_request_context is a function within the flask.ctx 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 / babel / manager.py**](https://github.com/dpgaspar/Flask-AppBuilder/blob/master/flask_appbuilder/babel/manager.py)
27+
28+
```python
29+
# manager.py
30+
import os
31+
32+
~~from flask import has_request_context, request, session
33+
from flask_babel import Babel
34+
35+
from .views import LocaleView
36+
from ..basemanager import BaseManager
37+
38+
39+
class BabelManager(BaseManager):
40+
41+
babel = None
42+
locale_view = None
43+
44+
def __init__(self, appbuilder):
45+
super(BabelManager, self).__init__(appbuilder)
46+
app = appbuilder.get_app
47+
app.config.setdefault("BABEL_DEFAULT_LOCALE", "en")
48+
if not app.config.get("LANGUAGES"):
49+
app.config["LANGUAGES"] = {"en": {"flag": "us", "name": "English"}}
50+
appbuilder_parent_dir = os.path.join(
51+
os.path.dirname(os.path.abspath(__file__)), os.pardir
52+
)
53+
appbuilder_translations_path = os.path.join(
54+
appbuilder_parent_dir, "translations"
55+
)
56+
if "BABEL_TRANSLATION_DIRECTORIES" in app.config:
57+
58+
59+
## ... source file abbreviated to get to has_request_context examples ...
60+
61+
62+
)
63+
else:
64+
translations_path = appbuilder_translations_path + ";translations"
65+
app.config["BABEL_TRANSLATION_DIRECTORIES"] = translations_path
66+
self.babel = Babel(app)
67+
self.babel.locale_selector_func = self.get_locale
68+
69+
def register_views(self):
70+
self.locale_view = LocaleView()
71+
self.appbuilder.add_view_no_menu(self.locale_view)
72+
73+
@property
74+
def babel_default_locale(self):
75+
return self.appbuilder.get_app.config["BABEL_DEFAULT_LOCALE"]
76+
77+
@property
78+
def languages(self):
79+
return self.appbuilder.get_app.config["LANGUAGES"]
80+
81+
def get_locale(self):
82+
~~ if has_request_context():
83+
# locale selector for API searches for request args
84+
for arg, value in request.args.items():
85+
if arg == "_l_":
86+
if value in self.languages:
87+
return value
88+
else:
89+
return self.babel_default_locale
90+
locale = session.get("locale")
91+
if locale:
92+
return locale
93+
session["locale"] = self.babel_default_locale
94+
return session["locale"]
95+
96+
97+
## ... source file continues with no further has_request_context examples...
98+
99+
100+
```
101+
102+
103+
## Example 2 from FlaskBB
104+
[FlaskBB](https://github.com/flaskbb/flaskbb)
105+
([project website](https://flaskbb.org/)) is a [Flask](/flask.html)-based
106+
forum web application. The web app allows users to chat in an open
107+
message board or send private messages in plain text or
108+
[Markdown](/markdown.html).
109+
110+
FlaskBB is provided as open source
111+
[under this license](https://github.com/flaskbb/flaskbb/blob/master/LICENSE).
112+
113+
[**FlaskBB / flaskbb / forum / locals.py**](https://github.com/flaskbb/flaskbb/blob/master/flaskbb/forum/locals.py)
114+
115+
```python
116+
# locals.py
117+
# -*- coding: utf-8 -*-
118+
"""
119+
flaskbb.forum.locals
120+
--------------------
121+
Thread local helpers for FlaskBB
122+
123+
:copyright: 2017, the FlaskBB Team
124+
:license: BSD, see license for more details
125+
"""
126+
127+
~~from flask import _request_ctx_stack, has_request_context, request
128+
from werkzeug.local import LocalProxy
129+
130+
from .models import Category, Forum, Post, Topic
131+
132+
133+
@LocalProxy
134+
def current_post():
135+
return _get_item(Post, 'post_id', 'post')
136+
137+
138+
@LocalProxy
139+
def current_topic():
140+
if current_post:
141+
return current_post.topic
142+
return _get_item(Topic, 'topic_id', 'topic')
143+
144+
145+
@LocalProxy
146+
def current_forum():
147+
if current_topic:
148+
return current_topic.forum
149+
return _get_item(Forum, 'forum_id', 'forum')
150+
151+
152+
@LocalProxy
153+
def current_category():
154+
if current_forum:
155+
return current_forum.category
156+
return _get_item(Category, 'category_id', 'category')
157+
158+
159+
def _get_item(model, view_arg, name):
160+
if (
161+
~~ has_request_context() and
162+
not getattr(_request_ctx_stack.top, name, None) and
163+
view_arg in request.view_args
164+
):
165+
setattr(
166+
_request_ctx_stack.top,
167+
name,
168+
model.query.filter_by(id=request.view_args[view_arg]).first()
169+
)
170+
171+
return getattr(_request_ctx_stack.top, name, None)
172+
173+
174+
## ... source file continues with no further has_request_context examples...
175+
176+
177+
```
178+

0 commit comments

Comments
 (0)