Skip to content

Commit b586659

Browse files
committed
update flask examples with latest updates
1 parent 1b47c23 commit b586659

24 files changed

+274
-92
lines changed

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

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ that accepts POSTs.
2020
and <a href="/flask-app-immutabledict-examples.html">ImmutableDict</a>
2121
are several other callables with code examples from the same `flask.app` package.
2222

23-
These topics are also useful while reading the `BadRequest` examples:
23+
These subjects go along with the `BadRequest` code examples:
2424

2525
* [web development](/web-development.html) and [web design](/web-design.html)
2626
* [Flask](/flask.html) and [web framework](/web-frameworks.html) concepts
@@ -166,6 +166,7 @@ import hashlib
166166
import logging
167167
import os
168168
import warnings
169+
from urllib.parse import urlparse
169170
from functools import wraps
170171

171172
from flask import Blueprint, current_app, g, request, session
@@ -175,7 +176,7 @@ from werkzeug.security import safe_str_cmp
175176
from wtforms import ValidationError
176177
from wtforms.csrf.core import CSRF
177178

178-
from ._compat import FlaskWTFDeprecationWarning, string_types, urlparse
179+
from ._compat import FlaskWTFDeprecationWarning
179180

180181
__all__ = ('generate_csrf', 'validate_csrf', 'CSRFProtect')
181182
logger = logging.getLogger(__name__)
@@ -222,7 +223,7 @@ class CsrfProtect(CSRFProtect):
222223
'"flask_wtf.CsrfProtect" has been renamed to "CSRFProtect" '
223224
'and will be removed in 1.0.'
224225
), stacklevel=2)
225-
super(CsrfProtect, self).__init__(app=app)
226+
super().__init__(app=app)
226227

227228

228229
~~class CSRFError(BadRequest):

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1084,7 +1084,8 @@ from util import base64_to_pil
10841084
~~app = Flask(__name__)
10851085

10861086

1087-
from keras.applications.mobilenet_v2 import MobileNetV2
1087+
1088+
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2
10881089
model = MobileNetV2(weights='imagenet')
10891090

10901091
print('Model loaded. Check http://127.0.0.1:5000/')
@@ -1107,7 +1108,6 @@ def model_predict(img, model):
11071108

11081109

11091110

1110-
11111111
## ... source file continues with no further Flask examples...
11121112

11131113
```

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ Flask web applications.
2222
and <a href="/flask-app-immutabledict-examples.html">ImmutableDict</a>
2323
are several other callables with code examples from the same `flask.app` package.
2424

25-
You should read up on these subjects along with these `Headers` examples:
25+
These topics are also useful while reading the `Headers` examples:
2626

2727
* [web development](/web-development.html) and [web design](/web-design.html)
2828
* [Flask](/flask.html) and [web framework](/web-frameworks.html) concepts
@@ -60,21 +60,27 @@ from CTFd.cache import cache, clear_standings
6060
from CTFd.config import TestingConfig
6161
from CTFd.models import (
6262
Awards,
63+
ChallengeComments,
6364
ChallengeFiles,
6465
Challenges,
66+
Comments,
6567
Fails,
68+
Fields,
6669
Files,
6770
Flags,
6871
Hints,
6972
Notifications,
73+
PageComments,
7074
PageFiles,
7175
Pages,
7276
Solves,
7377
Tags,
78+
TeamComments,
7479
Teams,
7580
Tokens,
7681
Tracking,
7782
Unlocks,
83+
UserComments,
7884
Users,
7985
)
8086

@@ -149,6 +155,7 @@ import operator
149155
import re
150156
import six
151157
import sys
158+
import warnings
152159

153160
from collections import OrderedDict
154161
from functools import wraps, partial

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,8 @@ DEFAULTS = {
7777
'CUSTOMIZATION_DEBUG': False,
7878
'CUSTOMIZATION_DIR': None,
7979
'CUSTOM_COUNTRIES': {},
80+
'CUSTOM_LANGUAGES': {},
8081
'DB_LOG': False,
81-
'DEBUG': False,
8282

8383

8484
## ... source file abbreviated to get to ImmutableDict examples ...

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

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ from flask import redirect, render_template, request, session, url_for
3838
from itsdangerous.exc import BadSignature, BadTimeSignature, SignatureExpired
3939

4040
from CTFd.cache import clear_team_session, clear_user_session
41-
from CTFd.models import Teams, Users, db
41+
from CTFd.models import Teams, UserFieldEntries, UserFields, Users, db
4242
from CTFd.utils import config, email, get_app_config, get_config
4343
from CTFd.utils import user as current_user
4444
from CTFd.utils import validators
@@ -551,7 +551,7 @@ from werkzeug.urls import url_quote_plus
551551

552552
from flask_debugtoolbar.compat import iteritems
553553
from flask_debugtoolbar.toolbar import DebugToolbar
554-
from flask_debugtoolbar.utils import decode_text
554+
from flask_debugtoolbar.utils import decode_text, gzip_compress, gzip_decompress
555555

556556
try:
557557
from importlib.metadata import version
@@ -666,6 +666,7 @@ import hashlib
666666
import logging
667667
import os
668668
import warnings
669+
from urllib.parse import urlparse
669670
from functools import wraps
670671

671672
~~from flask import Blueprint, current_app, g, request, session
@@ -675,7 +676,7 @@ from werkzeug.security import safe_str_cmp
675676
from wtforms import ValidationError
676677
from wtforms.csrf.core import CSRF
677678

678-
from ._compat import FlaskWTFDeprecationWarning, string_types, urlparse
679+
from ._compat import FlaskWTFDeprecationWarning
679680

680681
__all__ = ('generate_csrf', 'validate_csrf', 'CSRFProtect')
681682
logger = logging.getLogger(__name__)
@@ -714,7 +715,7 @@ def generate_csrf(secret_key=None, token_key=None):
714715
if not request.referrer:
715716
self._error_response('The referrer header is missing.')
716717

717-
good_referrer = 'https://{0}/'.format(request.host)
718+
good_referrer = f'https://{request.host}/'
718719

719720
if not same_origin(request.referrer, good_referrer):
720721
self._error_response('The referrer does not match the host.')
@@ -727,7 +728,7 @@ def generate_csrf(secret_key=None, token_key=None):
727728
self._exempt_blueprints.add(view.name)
728729
return view
729730

730-
if isinstance(view, string_types):
731+
if isinstance(view, str):
731732
view_location = view
732733
else:
733734
view_location = '.'.join((view.__module__, view.__name__))

content/pages/examples/flask/flask-ctx-after-this-request.markdown

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@ def us_signin_send_code():
218218

219219

220220
@auth_required(
221+
lambda: config_value("API_ENABLED_METHODS"),
221222
within=lambda: config_value("FRESHNESS"),
222223
grace=lambda: config_value("FRESHNESS_GRACE_PERIOD"),
223224
)
@@ -233,7 +234,6 @@ def us_setup():
233234
form = form_class(meta=suppress_form_csrf())
234235

235236

236-
237237
## ... source file abbreviated to get to after_this_request examples ...
238238

239239

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ from flask_pluginengine import current_plugin
158158
from speaklater import is_lazy_string, make_lazy_string
159159
from werkzeug.utils import cached_property
160160

161+
from indico.core.config import config
161162
from indico.util.caching import memoize_request
162163

163164

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

Lines changed: 128 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,128 @@ def _get_item(model, view_arg, name):
179179
```
180180

181181

182-
## Example 3 from indico
182+
## Example 3 from Flask-SocketIO
183+
[Flask-SocketIO](https://github.com/miguelgrinberg/Flask-SocketIO)
184+
([PyPI package information](https://pypi.org/project/Flask-SocketIO/),
185+
[official tutorial](https://blog.miguelgrinberg.com/post/easy-websockets-with-flask-and-gevent)
186+
and
187+
[project documentation](https://flask-socketio.readthedocs.io/en/latest/))
188+
is a code library by [Miguel Grinberg](https://blog.miguelgrinberg.com/index)
189+
that provides Socket.IO integration for [Flask](/flask.html) applications.
190+
This extension makes it easier to add bi-directional communications on the
191+
web via the [WebSockets](/websockets.html) protocol.
192+
193+
The Flask-SocketIO project is open source under the
194+
[MIT license](https://github.com/miguelgrinberg/Flask-SocketIO/blob/master/LICENSE).
195+
196+
[**Flask-SocketIO / flask_socketio / __init__.py**](https://github.com/miguelgrinberg/Flask-SocketIO/blob/master/./flask_socketio/__init__.py)
197+
198+
```python
199+
# __init__.py
200+
from functools import wraps
201+
import os
202+
import sys
203+
204+
gevent_socketio_found = True
205+
try:
206+
from socketio import socketio_manage
207+
except ImportError:
208+
gevent_socketio_found = False
209+
if gevent_socketio_found:
210+
print('The gevent-socketio package is incompatible with this version of '
211+
'the Flask-SocketIO extension. Please uninstall it, and then '
212+
'install the latest version of python-socketio in its place.')
213+
sys.exit(1)
214+
215+
import flask
216+
~~from flask import _request_ctx_stack, has_request_context, json as flask_json
217+
from flask.sessions import SessionMixin
218+
import socketio
219+
from socketio.exceptions import ConnectionRefusedError
220+
from werkzeug.debug import DebuggedApplication
221+
from werkzeug.serving import run_with_reloader
222+
223+
from .namespace import Namespace
224+
from .test_client import SocketIOTestClient
225+
226+
__version__ = '4.3.2dev'
227+
228+
229+
class _SocketIOMiddleware(socketio.WSGIApp):
230+
def __init__(self, socketio_app, flask_app, socketio_path='socket.io'):
231+
self.flask_app = flask_app
232+
super(_SocketIOMiddleware, self).__init__(socketio_app,
233+
flask_app.wsgi_app,
234+
socketio_path=socketio_path)
235+
236+
def __call__(self, environ, start_response):
237+
environ = environ.copy()
238+
environ['flask.app'] = self.flask_app
239+
return super(_SocketIOMiddleware, self).__call__(environ,
240+
start_response)
241+
242+
243+
## ... source file abbreviated to get to has_request_context examples ...
244+
245+
246+
self.default_exception_handler = exception_handler
247+
return exception_handler
248+
249+
def on_event(self, message, handler, namespace=None):
250+
self.on(message, namespace=namespace)(handler)
251+
252+
def on_namespace(self, namespace_handler):
253+
if not isinstance(namespace_handler, Namespace):
254+
raise ValueError('Not a namespace instance.')
255+
namespace_handler._set_socketio(self)
256+
if self.server:
257+
self.server.register_namespace(namespace_handler)
258+
else:
259+
self.namespace_handlers.append(namespace_handler)
260+
261+
def emit(self, event, *args, **kwargs):
262+
namespace = kwargs.pop('namespace', '/')
263+
room = kwargs.pop('room', None)
264+
include_self = kwargs.pop('include_self', True)
265+
skip_sid = kwargs.pop('skip_sid', None)
266+
if not include_self and not skip_sid:
267+
skip_sid = flask.request.sid
268+
callback = kwargs.pop('callback', None)
269+
if callback:
270+
sid = None
271+
~~ if has_request_context():
272+
sid = getattr(flask.request, 'sid', None)
273+
original_callback = callback
274+
275+
def _callback_wrapper(*args):
276+
return self._handle_event(original_callback, None, namespace,
277+
sid, *args)
278+
279+
if sid:
280+
callback = _callback_wrapper
281+
self.server.emit(event, *args, namespace=namespace, room=room,
282+
skip_sid=skip_sid, callback=callback, **kwargs)
283+
284+
def send(self, data, json=False, namespace=None, room=None,
285+
callback=None, include_self=True, skip_sid=None, **kwargs):
286+
skip_sid = flask.request.sid if not include_self else skip_sid
287+
if json:
288+
self.emit('json', data, namespace=namespace, room=room,
289+
skip_sid=skip_sid, callback=callback, **kwargs)
290+
else:
291+
self.emit('message', data, namespace=namespace, room=room,
292+
skip_sid=skip_sid, callback=callback, **kwargs)
293+
294+
def close_room(self, room, namespace=None):
295+
self.server.close_room(room, namespace)
296+
297+
298+
## ... source file continues with no further has_request_context examples...
299+
300+
```
301+
302+
303+
## Example 4 from indico
183304
[indico](https://github.com/indico/indico)
184305
([project website](https://getindico.io/),
185306
[documentation](https://docs.getindico.io/en/stable/installation/)
@@ -231,6 +352,12 @@ class AddRequestIDFilter(object):
231352
return True
232353

233354

355+
class AddUserIDFilter(object):
356+
def filter(self, record):
357+
~~ record.user_id = unicode(session.user.id) if has_request_context() and session and session.user else '-'
358+
return True
359+
360+
234361
class RequestInfoFormatter(logging.Formatter):
235362
def format(self, record):
236363
rv = super(RequestInfoFormatter, self).format(record)

0 commit comments

Comments
 (0)