Skip to content

Commit e0ce2ac

Browse files
committed
add new flask example code
1 parent ef4ee5a commit e0ce2ac

35 files changed

+1734
-57
lines changed

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

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,3 +236,61 @@ def same_origin(current_uri, compare_uri):
236236

237237
```
238238

239+
240+
## Example 3 from indico
241+
[indico](https://github.com/indico/indico)
242+
([project website](https://getindico.io/),
243+
[documentation](https://docs.getindico.io/en/stable/installation/)
244+
and [sandbox demo](https://sandbox.getindico.io/))
245+
is a [Flask](/flask.html)-based web app for event management.
246+
The code is open sourced under the
247+
[MIT license](https://github.com/indico/indico/blob/master/LICENSE).
248+
249+
[**indico / indico / core / errors.py**](https://github.com/indico/indico/blob/master/indico/core/errors.py)
250+
251+
```python
252+
# errors.py
253+
254+
255+
~~from werkzeug.exceptions import BadRequest, Forbidden, HTTPException, NotFound
256+
257+
from indico.util.i18n import _
258+
from indico.util.string import to_unicode
259+
260+
261+
def get_error_description(exception):
262+
try:
263+
description = exception.description
264+
except AttributeError:
265+
return to_unicode(exception.message)
266+
if isinstance(exception, Forbidden) and description == Forbidden.description:
267+
return _(u"You are not allowed to access this page.")
268+
elif isinstance(exception, NotFound) and description == NotFound.description:
269+
return _(u"The page you are looking for doesn't exist.")
270+
~~ elif isinstance(exception, BadRequest) and description == BadRequest.description:
271+
return _(u"The request was invalid or contained invalid arguments.")
272+
else:
273+
return to_unicode(description)
274+
275+
276+
class IndicoError(Exception):
277+
278+
279+
class NoReportError(IndicoError):
280+
281+
@classmethod
282+
def wrap_exc(cls, exc):
283+
assert isinstance(exc, HTTPException)
284+
exc._disallow_report = True
285+
return exc
286+
287+
288+
class UserValueError(NoReportError):
289+
http_status_code = 400
290+
291+
292+
293+
## ... source file continues with no further BadRequest examples...
294+
295+
```
296+
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
title: flask.app ImmutableDict Example Code
2+
category: page
3+
slug: flask-app-immutabledict-examples
4+
sortorder: 500021003
5+
toc: False
6+
sidebartitle: flask.app ImmutableDict
7+
meta: Example code for understanding how to use the ImmutableDict class from the flask.app module of the Flask project.
8+
9+
10+
ImmutableDict is a class within the flask.app module of the Flask project.
11+
12+
13+
## Example 1 from indico
14+
[indico](https://github.com/indico/indico)
15+
([project website](https://getindico.io/),
16+
[documentation](https://docs.getindico.io/en/stable/installation/)
17+
and [sandbox demo](https://sandbox.getindico.io/))
18+
is a [Flask](/flask.html)-based web app for event management.
19+
The code is open sourced under the
20+
[MIT license](https://github.com/indico/indico/blob/master/LICENSE).
21+
22+
[**indico / indico / core / config.py**](https://github.com/indico/indico/blob/master/indico/core/config.py)
23+
24+
```python
25+
# config.py
26+
27+
from __future__ import absolute_import, unicode_literals
28+
29+
import ast
30+
import codecs
31+
import os
32+
import re
33+
import socket
34+
import warnings
35+
from datetime import timedelta
36+
37+
import pytz
38+
from celery.schedules import crontab
39+
from flask import current_app, g
40+
from flask.helpers import get_root_path
41+
~~from werkzeug.datastructures import ImmutableDict
42+
from werkzeug.urls import url_parse
43+
44+
from indico.util.caching import make_hashable
45+
from indico.util.fs import resolve_link
46+
from indico.util.packaging import package_is_editable
47+
from indico.util.string import crc32, snakify
48+
49+
50+
DEFAULTS = {
51+
'ATTACHMENT_STORAGE': 'default',
52+
'AUTH_PROVIDERS': {},
53+
'BASE_URL': None,
54+
'CACHE_BACKEND': 'files',
55+
'CACHE_DIR': '/opt/indico/cache',
56+
'CATEGORY_CLEANUP': {},
57+
'CELERY_BROKER': None,
58+
'CELERY_CONFIG': {},
59+
'CELERY_RESULT_BACKEND': None,
60+
'COMMUNITY_HUB_URL': 'https://hub.getindico.io',
61+
'CUSTOMIZATION_DEBUG': False,
62+
'CUSTOMIZATION_DIR': None,
63+
'CUSTOM_COUNTRIES': {},
64+
'DB_LOG': False,
65+
'DEBUG': False,
66+
67+
68+
## ... source file abbreviated to get to ImmutableDict examples ...
69+
70+
71+
allowed |= set(INTERNAL_DEFAULTS)
72+
for key in set(data) - allowed:
73+
warnings.warn('Ignoring unknown config key {}'.format(key))
74+
return {k: v for k, v in data.iteritems() if k in allowed}
75+
76+
77+
def load_config(only_defaults=False, override=None):
78+
data = dict(DEFAULTS, **INTERNAL_DEFAULTS)
79+
if not only_defaults:
80+
path = get_config_path()
81+
config = _sanitize_data(_parse_config(path))
82+
data.update(config)
83+
env_override = os.environ.get('INDICO_CONF_OVERRIDE')
84+
if env_override:
85+
data.update(_sanitize_data(ast.literal_eval(env_override)))
86+
resolved_path = resolve_link(path) if os.path.islink(path) else path
87+
resolved_path = None if resolved_path == os.devnull else resolved_path
88+
data['CONFIG_PATH'] = path
89+
data['CONFIG_PATH_RESOLVED'] = resolved_path
90+
if resolved_path is not None:
91+
data['LOGGING_CONFIG_PATH'] = os.path.join(os.path.dirname(resolved_path), data['LOGGING_CONFIG_FILE'])
92+
93+
if override:
94+
data.update(_sanitize_data(override, allow_internal=True))
95+
_postprocess_config(data)
96+
~~ return ImmutableDict(data)
97+
98+
99+
class IndicoConfig(object):
100+
101+
__slots__ = ('_config', '_exc')
102+
103+
def __init__(self, config=None, exc=AttributeError):
104+
object.__setattr__(self, '_config', config)
105+
object.__setattr__(self, '_exc', exc)
106+
107+
@property
108+
def data(self):
109+
try:
110+
return self._config or current_app.config['INDICO']
111+
except KeyError:
112+
raise RuntimeError('config not loaded')
113+
114+
@property
115+
def hash(self):
116+
return crc32(repr(make_hashable(sorted(self.data.items()))))
117+
118+
@property
119+
def CONFERENCE_CSS_TEMPLATES_BASE_URL(self):
120+
return self.BASE_URL + '/css/confTemplates'
121+
122+
123+
## ... source file continues with no further ImmutableDict examples...
124+
125+
```
126+

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 Example Code
22
category: page
33
slug: flask-blueprints-blueprint-examples
4-
sortorder: 500021003
4+
sortorder: 500021004
55
toc: False
66
sidebartitle: flask.blueprints Blueprint
77
meta: Example code for understanding how to use the Blueprint class from the flask.blueprints module of the Flask project.
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
title: flask.cli AppGroup Example Code
2+
category: page
3+
slug: flask-cli-appgroup-examples
4+
sortorder: 500021005
5+
toc: False
6+
sidebartitle: flask.cli AppGroup
7+
meta: Example code for understanding how to use the AppGroup class from the flask.cli module of the Flask project.
8+
9+
10+
AppGroup is a class within the flask.cli module of the Flask project.
11+
12+
13+
## Example 1 from indico
14+
[indico](https://github.com/indico/indico)
15+
([project website](https://getindico.io/),
16+
[documentation](https://docs.getindico.io/en/stable/installation/)
17+
and [sandbox demo](https://sandbox.getindico.io/))
18+
is a [Flask](/flask.html)-based web app for event management.
19+
The code is open sourced under the
20+
[MIT license](https://github.com/indico/indico/blob/master/LICENSE).
21+
22+
[**indico / indico / cli / util.py**](https://github.com/indico/indico/blob/master/indico/cli/util.py)
23+
24+
```python
25+
# util.py
26+
27+
from __future__ import unicode_literals
28+
29+
import traceback
30+
from importlib import import_module
31+
32+
import click
33+
~~from flask.cli import AppGroup, FlaskGroup, ScriptInfo
34+
from flask_pluginengine import wrap_in_plugin_context
35+
from werkzeug.utils import cached_property
36+
37+
38+
39+
40+
def _create_app(info):
41+
from indico.web.flask.app import make_app
42+
return make_app(set_path=True)
43+
44+
45+
class IndicoFlaskGroup(FlaskGroup):
46+
47+
def __init__(self, **extra):
48+
super(IndicoFlaskGroup, self).__init__(create_app=_create_app, add_default_commands=False,
49+
add_version_option=False, set_debug_flag=False, **extra)
50+
self._indico_plugin_commands = None
51+
52+
def _load_plugin_commands(self):
53+
assert False
54+
55+
def _wrap_in_plugin_context(self, plugin, cmd):
56+
cmd.callback = wrap_in_plugin_context(plugin, cmd.callback)
57+
for subcmd in getattr(cmd, 'commands', {}).viewvalues():
58+
self._wrap_in_plugin_context(plugin, subcmd)
59+
60+
def _get_indico_plugin_commands(self, ctx):
61+
if self._indico_plugin_commands is not None:
62+
return self._indico_plugin_commands
63+
try:
64+
from indico.core import signals
65+
from indico.util.signals import named_objects_from_signal
66+
ctx.ensure_object(ScriptInfo).load_app()
67+
cmds = named_objects_from_signal(signals.plugin.cli.send(), plugin_attr='_indico_plugin')
68+
rv = {}
69+
for name, cmd in cmds.viewitems():
70+
if cmd._indico_plugin:
71+
self._wrap_in_plugin_context(cmd._indico_plugin, cmd)
72+
rv[name] = cmd
73+
except Exception as exc:
74+
if 'No indico config found' not in unicode(exc):
75+
click.echo(click.style('Loading plugin commands failed:', fg='red', bold=True))
76+
click.echo(click.style(traceback.format_exc(), fg='red'))
77+
rv = {}
78+
self._indico_plugin_commands = rv
79+
return rv
80+
81+
def get_command(self, ctx, name):
82+
~~ rv = AppGroup.get_command(self, ctx, name)
83+
if rv is not None:
84+
return rv
85+
return self._get_indico_plugin_commands(ctx).get(name)
86+
87+
def list_commands(self, ctx):
88+
rv = set(click.Group.list_commands(self, ctx))
89+
rv.update(self._get_indico_plugin_commands(ctx))
90+
return sorted(rv)
91+
92+
93+
class LazyGroup(click.Group):
94+
95+
def __init__(self, import_name, **kwargs):
96+
self._import_name = import_name
97+
super(LazyGroup, self).__init__(**kwargs)
98+
99+
@cached_property
100+
def _impl(self):
101+
module, name = self._import_name.split(':', 1)
102+
return getattr(import_module(module), name)
103+
104+
def get_command(self, ctx, cmd_name):
105+
return self._impl.get_command(ctx, cmd_name)
106+
107+
108+
109+
## ... source file continues with no further AppGroup examples...
110+
111+
```
112+

0 commit comments

Comments
 (0)