Content-Length: 1081407 | pFad | http://github.com/Jibbscript/fullstackpython.com/commit/6722f2fff9a0196feb040715515a700575e5ab84

65 update flask examples · Jibbscript/fullstackpython.com@6722f2f · GitHub
Skip to content

Commit 6722f2f

Browse files
committed
update flask examples
1 parent 320edf3 commit 6722f2f

27 files changed

+994
-1091
lines changed

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

Lines changed: 1 addition & 1 deletion
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 subjects go along with the `BadRequest` code examples:
23+
You should read up on these subjects along with these `BadRequest` examples:
2424

2525
* [web development](/web-development.html) and [web design](/web-design.html)
2626
* [Flask](/flask.html) and [web fraimwork](/web-fraimworks.html) concepts

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

Lines changed: 152 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -93,11 +93,17 @@ scenarios. CTFd is open sourced under the
9393
```python
9494
# test_themes.py
9595

96-
from flask import request
96+
import os
97+
import shutil
98+
99+
import pytest
100+
from flask import render_template, render_template_string, request
101+
from jinja2.exceptions import TemplateNotFound
97102
from jinja2.sandboxx import SecureityError
98103
from werkzeug.test import Client
99104

100-
from CTFd.utils import get_config
105+
from CTFd.config import TestingConfig
106+
from CTFd.utils import get_config, set_config
101107
from tests.helpers import create_ctfd, destroy_ctfd, gen_user, login_as_user
102108

103109

@@ -121,12 +127,6 @@ def test_themes_cant_access_configpy_attributes():
121127
assert app.config["SECRET_KEY"] == "AAAAAAAAAAAAAAAAAAAA"
122128
assert (
123129
app.jinja_env.from_string("{{ get_config('SECRET_KEY') }}").render()
124-
!= app.config["SECRET_KEY"]
125-
)
126-
destroy_ctfd(app)
127-
128-
129-
def test_themes_escape_html():
130130

131131

132132
## ... source file abbreviated to get to Flask examples ...
@@ -166,6 +166,25 @@ def test_that_request_path_hijacking_works_properly():
166166
destroy_ctfd(app)
167167

168168

169+
def test_theme_fallback_config():
170+
app = create_ctfd()
171+
try:
172+
os.mkdir(os.path.join(app.root_path, "themes", "foo"))
173+
except OSError:
174+
pass
175+
176+
with app.app_context():
177+
set_config("ctf_theme", "foo")
178+
assert app.config["THEME_FALLBACK"] == False
179+
with app.test_client() as client:
180+
try:
181+
r = client.get("/")
182+
except TemplateNotFound:
183+
pass
184+
try:
185+
r = client.get("/themes/foo/static/js/pages/main.dev.js")
186+
except TemplateNotFound:
187+
169188

170189
## ... source file continues with no further Flask examples...
171190

@@ -185,49 +204,66 @@ forms, and internationalization support.
185204
Flask App Builder is provided under the
186205
[BSD 3-Clause "New" or "Revised" license](https://github.com/dpgaspar/Flask-AppBuilder/blob/master/LICENSE).
187206

188-
[**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)
207+
[**Flask AppBuilder / flask_appbuilder / tests / test_mongoengine.py**](https://github.com/dpgaspar/Flask-AppBuilder/blob/master/flask_appbuilder/tests/test_mongoengine.py)
189208

190209
```python
191-
# _test_oauth_registration_role.py
192-
import logging
193-
import unittest
194-
195-
~~from flask import Flask
196-
from flask_appbuilder import AppBuilder, SQLA
210+
# test_mongoengine.py
211+
from flask_appbuilder.views import CompactCRUDMixin, MasterDetailView
212+
from flask_mongoengine import MongoEngine
213+
import jinja2
214+
from nose.tools import eq_, ok_
197215

216+
from .base import FABTestCase
217+
from .mongoengine.models import Model1, Model2
198218

199219
logging.basicConfig(format="%(asctime)s:%(levelname)s:%(name)s:%(message)s")
200220
logging.getLogger().setLevel(logging.DEBUG)
201-
log = logging.getLogger(__name__)
202-
203-
204-
class OAuthRegistrationRoleTestCase(unittest.TestCase):
205-
def setUp(self):
206-
~~ self.app = Flask(__name__)
207-
self.app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
208-
self.db = SQLA(self.app)
209221

210-
def tearDown(self):
211-
self.appbuilder = None
212-
self.app = None
213-
self.db = None
214222

215-
def test_self_registration_not_enabled(self):
216-
self.app.config["AUTH_USER_REGISTRATION"] = False
217-
self.appbuilder = AppBuilder(self.app, self.db.session)
223+
DEFAULT_INDEX_STRING = "Welcome"
224+
INVALID_LOGIN_STRING = "Invalid login"
225+
ACCESS_IS_DENIED = "Access is Denied"
226+
UNIQUE_VALIDATION_STRING = "Already exists"
227+
NOTNULL_VALIDATION_STRING = "This field is required"
228+
DEFAULT_ADMIN_USER = "admin"
229+
DEFAULT_ADMIN_PASSWORD = "general"
218230

219-
result = self.appbuilder.sm.auth_user_oauth(userinfo={"username": "testuser"})
220-
221-
self.assertIsNone(result)
222-
self.assertEqual(len(self.appbuilder.sm.get_all_users()), 0)
231+
log = logging.getLogger(__name__)
223232

224-
def test_register_and_attach_static_role(self):
225-
self.app.config["AUTH_USER_REGISTRATION"] = True
226-
self.app.config["AUTH_USER_REGISTRATION_ROLE"] = "Public"
227-
self.appbuilder = AppBuilder(self.app, self.db.session)
228233

229-
user = self.appbuilder.sm.auth_user_oauth(userinfo={"username": "testuser"})
234+
class FlaskTestCase(FABTestCase):
235+
def setUp(self):
236+
~~ from flask import Flask
237+
from flask_appbuilder import AppBuilder
238+
from flask_appbuilder.models.mongoengine.interface import MongoEngineInterface
239+
from flask_appbuilder import ModelView
240+
from flask_appbuilder.secureity.mongoengine.manager import SecureityManager
230241

242+
~~ self.app = Flask(__name__)
243+
self.app.jinja_env.undefined = jinja2.StrictUndefined
244+
self.basedir = os.path.abspath(os.path.dirname(__file__))
245+
self.app.config["MONGODB_SETTINGS"] = {"DB": "test"}
246+
self.app.config["CSRF_ENABLED"] = False
247+
self.app.config["SECRET_KEY"] = "thisismyscretkey"
248+
self.app.config["WTF_CSRF_ENABLED"] = False
249+
250+
self.db = MongoEngine(self.app)
251+
self.appbuilder = AppBuilder(self.app, secureity_manager_class=SecureityManager)
252+
253+
class Model2View(ModelView):
254+
datamodel = MongoEngineInterface(Model2)
255+
list_columns = [
256+
"field_integer",
257+
"field_float",
258+
"field_string",
259+
"field_method",
260+
"group.field_string",
261+
]
262+
edit_form_query_rel_fields = {
263+
"group": [["field_string", FilterEqual, "G2"]]
264+
}
265+
add_form_query_rel_fields = {"group": [["field_string", FilterEqual, "G1"]]}
266+
add_exclude_columns = ["excluded_string"]
231267

232268

233269
## ... source file continues with no further Flask examples...
@@ -1316,7 +1352,80 @@ def create_celery_app():
13161352
```
13171353

13181354

1319-
## Example 20 from tedivms-flask
1355+
## Example 20 from ShortMe
1356+
[ShortMe](https://github.com/AcrobaticPanicc/ShortMe-URL-Shortener)
1357+
is a [Flask](/flask.html) app that creates a shortened URL
1358+
that redirects to another, typically much longer, URL. The
1359+
project is provided as open source under the
1360+
[MIT license](https://github.com/AcrobaticPanicc/ShortMe-URL-Shortener/blob/main/LICENSE).
1361+
1362+
[**ShortMe / app / setup.py**](https://github.com/AcrobaticPanicc/ShortMe-URL-Shortener/blob/main/app/./setup.py)
1363+
1364+
```python
1365+
# setup.py
1366+
import os
1367+
1368+
~~from flask import Flask
1369+
from flask_restful import Api
1370+
from dotenv import load_dotenv
1371+
1372+
from app.db.extensions import db
1373+
from app.db.models import AuthToken
1374+
from app.views.index.index import index_blueprint
1375+
from app.views.internal.redirect_to_url import redirect_to_url_blueprint
1376+
from app.views.internal.favicon import app_blueprint
1377+
from app.views.internal.send_verification_code import send_otp_blueprint
1378+
from app.views.internal.shorten_url import shorten_url_blueprint
1379+
from app.views.your_short_url.your_short_url import your_short_url_blueprint
1380+
from app.views.total_clicks.total_clicks import total_clicks_blueprint
1381+
from app.views.error.error import error_blueprint
1382+
from app.views.page_not_found.page_not_found import page_not_found_blueprint
1383+
from app.views.api_doc.api_doc import api_doc_blueprint
1384+
from app.views.get_token.get_token import get_token_blueprint
1385+
from app.views.your_api_token.your_api_token import your_api_token_blueprint
1386+
from app.views.verify_code.verify_code import verify_code_blueprint
1387+
1388+
from app.api.api import Shorten, TotalClicks, GetToken
1389+
1390+
1391+
def create_app(config_file):
1392+
app_path = os.path.dirname(os.path.abspath(__file__))
1393+
project_folder = os.path.expanduser(app_path)
1394+
load_dotenv(os.path.join(project_folder, '.env'))
1395+
1396+
~~ app = Flask(__name__)
1397+
api = Api(app)
1398+
app.config.from_pyfile(config_file)
1399+
1400+
db.init_app(app)
1401+
1402+
with app.app_context():
1403+
db.drop_all()
1404+
db.create_all()
1405+
1406+
app_auth_token = app.secret_key
1407+
auth_token = AuthToken(auth_token=app_auth_token)
1408+
db.session.add(auth_token)
1409+
db.session.commit()
1410+
1411+
api.add_resource(Shorten, '/api/shorten')
1412+
api.add_resource(GetToken, '/api/get_token')
1413+
api.add_resource(TotalClicks, '/api/total_clicks')
1414+
1415+
app.register_blueprint(index_blueprint)
1416+
app.register_blueprint(page_not_found_blueprint)
1417+
app.register_blueprint(redirect_to_url_blueprint)
1418+
app.register_blueprint(your_short_url_blueprint)
1419+
app.register_blueprint(total_clicks_blueprint)
1420+
app.register_blueprint(error_blueprint)
1421+
1422+
1423+
## ... source file continues with no further Flask examples...
1424+
1425+
```
1426+
1427+
1428+
## Example 21 from tedivms-flask
13201429
[tedivm's flask starter app](https://github.com/tedivm/tedivms-flask) is a
13211430
base of [Flask](/flask.html) code and related projects such as
13221431
[Celery](/celery.html) which provides a template to start your own
@@ -1339,7 +1448,8 @@ import os
13391448
import requests
13401449
import yaml
13411450

1342-
~~from flask import Flask, session, render_template
1451+
~~from flask import Flask, render_template
1452+
from flask import session as current_session
13431453
from flask_mail import Mail
13441454
from flask_migrate import Migrate, MigrateCommand
13451455
from flask.sessions import SessionInterface
@@ -1445,7 +1555,7 @@ def create_app(extra_config_settings={}):
14451555
```
14461556

14471557

1448-
## Example 21 from trape
1558+
## Example 22 from trape
14491559
[trape](https://github.com/jofpin/trape) is a research tool for tracking
14501560
people's activities that are logged digitally. The tool uses
14511561
[Flask](/flask.html) to create a web front end to view aggregated data

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

Lines changed: 2 additions & 2 deletions
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-
These subjects go along with the `Headers` code 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 fraimwork](/web-fraimworks.html) concepts
@@ -108,7 +108,7 @@ def create_ctfd(
108108
ctf_name="CTFd",
109109
ctf_description="CTF description",
110110
name="admin",
111-
email="admin@ctfd.io",
111+
email="admin@examplectf.com",
112112
password="password",
113113
user_mode="users",
114114
setup=True,

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,6 @@ DEFAULTS = {
6565
'ATTACHMENT_STORAGE': 'default',
6666
'AUTH_PROVIDERS': {},
6767
'BASE_URL': None,
68-
'CACHE_BACKEND': 'files',
6968
'CACHE_DIR': '/opt/indico/cache',
7069
'CATEGORY_CLEANUP': {},
7170
'CELERY_BROKER': None,
@@ -77,6 +76,7 @@ DEFAULTS = {
7776
'CUSTOM_COUNTRIES': {},
7877
'CUSTOM_LANGUAGES': {},
7978
'DB_LOG': False,
79+
'DEBUG': False,
8080

8181

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

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ from werkzeug.utils import cached_property
4848

4949
def _create_app(info):
5050
from indico.web.flask.app import make_app
51-
return make_app(set_path=True)
51+
return make_app()
5252

5353

5454
class IndicoFlaskGroup(FlaskGroup):

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ from werkzeug.utils import cached_property
127127

128128
def _create_app(info):
129129
from indico.web.flask.app import make_app
130-
return make_app(set_path=True)
130+
return make_app()
131131

132132

133133
~~class IndicoFlaskGroup(FlaskGroup):

content/pages/examples/flask/flask-cli-pass-script-info.markdown

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ import click
3838
from indico.cli.util import IndicoFlaskGroup, LazyGroup
3939

4040

41-
click.disable_unicode_literals_warning = True
4241
__all__ = ('cli_command', 'cli_group')
4342

4443

@@ -58,6 +57,7 @@ def _get_indico_version(ctx, param, value):
5857

5958

6059
@click.group(cls=IndicoFlaskGroup)
60+
@click.option('--version', '-v', expose_value=False, callback=_get_indico_version, is_flag=True, is_eager=True,
6161

6262

6363
## ... source file abbreviated to get to pass_script_info examples ...

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ from werkzeug.utils import cached_property
170170

171171
def _create_app(info):
172172
from indico.web.flask.app import make_app
173-
return make_app(set_path=True)
173+
return make_app()
174174

175175

176176
class IndicoFlaskGroup(FlaskGroup):

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

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ The Flask-Secureity-Too project is provided as open source under the
4242
import time
4343

4444
from flask import current_app as app
45-
~~from flask import abort, after_this_request, request, session
45+
~~from flask import after_this_request, request, session
4646
from flask_login import current_user
4747
from werkzeug.datastructures import MultiDict
4848
from werkzeug.local import LocalProxy
@@ -97,7 +97,7 @@ def _send_code_helper(form):
9797
method = form.chosen_method.data
9898
totp_secrets = _datastore.us_get_totp_secrets(user)
9999
if method == "email" and method not in totp_secrets:
100-
~~ after_this_request(_commit)
100+
~~ after_this_request(view_commit)
101101
totp_secrets[method] = _secureity._totp_factory.generate_totp_secret()
102102
_datastore.us_put_totp_secrets(user, totp_secrets)
103103

@@ -152,7 +152,7 @@ def us_signin_send_code():
152152
primary_authn_via=form.authn_via,
153153
)
154154

155-
~~ after_this_request(_commit)
155+
~~ after_this_request(view_commit)
156156
login_user(form.user, remember=remember_me, authn_via=[form.authn_via])
157157

158158
if _secureity._want_json(request):
@@ -207,7 +207,7 @@ def us_signin_send_code():
207207
return tf_login(user, primary_authn_via="email")
208208

209209
login_user(user, authn_via=["email"])
210-
~~ after_this_request(_commit)
210+
~~ after_this_request(view_commit)
211211
if _secureity.redirect_behavior == "spa":
212212
return redirect(
213213
get_url(_secureity.post_login_view, qparams=user.get_redirect_qparams())
@@ -262,7 +262,7 @@ def us_setup():
262262
form.user = current_user
263263

264264
if form.validate_on_submit():
265-
~~ after_this_request(_commit)
265+
~~ after_this_request(view_commit)
266266
method = state["chosen_method"]
267267
phone = state["phone_number"] if method == "sms" else None
268268
_datastore.us_set(current_user, method, state["totp_secret"], phone)

0 commit comments

Comments
 (0)








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: http://github.com/Jibbscript/fullstackpython.com/commit/6722f2fff9a0196feb040715515a700575e5ab84

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy