Skip to content

Commit 850703a

Browse files
committed
building out flask example pages
1 parent 9403031 commit 850703a

File tree

5 files changed

+244
-0
lines changed

5 files changed

+244
-0
lines changed

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,10 @@ message board or send private messages in plain text or
5151
FlaskBB is provided as open source
5252
[under this license](https://github.com/flaskbb/flaskbb/blob/master/LICENSE).
5353

54+
FlaskBB's code examples can be found on:
55+
56+
* [flask request](/flask-request-examples.html)
57+
5458

5559
### Flasky
5660
[Flasky](https://github.com/miguelgrinberg/flasky) is the wonderful
Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
title: flask redirect Example Python Code
2+
category: page
3+
slug: flask-redirect-examples
4+
sortorder: 50104
5+
toc: False
6+
sidebartitle: flask redirect
7+
meta: Python code examples for the redirect function from the Flask project used for building web applications.
8+
9+
10+
The [Flask](/flask.html)
11+
[redirect](https://flask.palletsprojects.com/en/1.1.x/api/#flask.redirect)
12+
([source code](https://github.com/pallets/werkzeug/blob/master/src/werkzeug/utils.py))
13+
function appropriately sends a redirect status code, one of
14+
301, 302, 303, 305, 307, or 308.
15+
16+
17+
## Example 1 from FlaskBB
18+
[FlaskBB](https://github.com/flaskbb/flaskbb)
19+
([project website](https://flaskbb.org/)) is a [Flask](/flask.html)-based
20+
forum web application. The web app allows users to chat in an open
21+
message board or send private messages in plain text or
22+
[Markdown](/markdown.html). FlaskBB is provided as open source
23+
[under this license](https://github.com/flaskbb/flaskbb/blob/master/LICENSE).
24+
25+
This example can be slightly confusing because it wraps `redirect` and calls
26+
`self.redirect` to invoke the wrapper function.
27+
28+
[**flaskbb / flaskbb / user / views.py**](https://github.com/flaskbb/flaskbb/blob/master/flaskbb/user/views.py)
29+
30+
```python
31+
# -*- coding: utf-8 -*-
32+
"""
33+
flaskbb.user.views
34+
------------------
35+
The user view handles the user profile
36+
and the user settings from a signed in user.
37+
:copyright: (c) 2014 by the FlaskBB Team.
38+
:license: BSD, see LICENSE for more details.
39+
"""
40+
import logging
41+
42+
import attr
43+
~~from flask import Blueprint, flash, redirect, request, url_for
44+
from flask.views import MethodView
45+
from flask_babelplus import gettext as _
46+
from flask_login import current_user, login_required
47+
from pluggy import HookimplMarker
48+
49+
50+
## ... code abbreviated here to get to the appropriate examples ...
51+
52+
53+
@attr.s(frozen=True, cmp=False, hash=False, repr=True)
54+
class UserSettings(MethodView):
55+
form = attr.ib(factory=settings_form_factory)
56+
settings_update_handler = attr.ib(factory=settings_update_handler)
57+
58+
decorators = [login_required]
59+
60+
def get(self):
61+
return self.render()
62+
63+
def post(self):
64+
if self.form.validate_on_submit():
65+
try:
66+
self.settings_update_handler.apply_changeset(
67+
current_user, self.form.as_change()
68+
)
69+
except StopValidation as e:
70+
self.form.populate_errors(e.reasons)
71+
return self.render()
72+
except PersistenceError:
73+
logger.exception("Error while updating user settings")
74+
flash(_("Error while updating user settings"), "danger")
75+
return self.redirect()
76+
77+
flash(_("Settings updated."), "success")
78+
return self.redirect()
79+
return self.render()
80+
81+
def render(self):
82+
return render_template("user/general_settings.html", form=self.form)
83+
84+
def redirect(self):
85+
~~ return redirect(url_for("user.settings"))
86+
87+
88+
@attr.s(frozen=True, hash=False, cmp=False, repr=True)
89+
class ChangePassword(MethodView):
90+
form = attr.ib(factory=change_password_form_factory)
91+
password_update_handler = attr.ib(factory=password_update_handler)
92+
decorators = [login_required]
93+
94+
def get(self):
95+
return self.render()
96+
97+
def post(self):
98+
if self.form.validate_on_submit():
99+
try:
100+
self.password_update_handler.apply_changeset(
101+
current_user, self.form.as_change()
102+
)
103+
except StopValidation as e:
104+
self.form.populate_errors(e.reasons)
105+
return self.render()
106+
except PersistenceError:
107+
logger.exception("Error while changing password")
108+
flash(_("Error while changing password"), "danger")
109+
return self.redirect()
110+
111+
flash(_("Password updated."), "success")
112+
return self.redirect()
113+
return self.render()
114+
115+
def render(self):
116+
return render_template("user/change_password.html", form=self.form)
117+
118+
def redirect(self):
119+
~~ return redirect(url_for("user.change_password"))
120+
121+
122+
@attr.s(frozen=True, cmp=False, hash=False, repr=True)
123+
class ChangeEmail(MethodView):
124+
form = attr.ib(factory=change_email_form_factory)
125+
update_email_handler = attr.ib(factory=email_update_handler)
126+
decorators = [login_required]
127+
128+
def get(self):
129+
return self.render()
130+
131+
def post(self):
132+
if self.form.validate_on_submit():
133+
try:
134+
self.update_email_handler.apply_changeset(
135+
current_user, self.form.as_change()
136+
)
137+
except StopValidation as e:
138+
self.form.populate_errors(e.reasons)
139+
return self.render()
140+
except PersistenceError:
141+
logger.exception("Error while updating email")
142+
flash(_("Error while updating email"), "danger")
143+
return self.redirect()
144+
145+
flash(_("Email address updated."), "success")
146+
return self.redirect()
147+
return self.render()
148+
149+
def render(self):
150+
return render_template("user/change_email.html", form=self.form)
151+
152+
def redirect(self):
153+
~~ return redirect(url_for("user.change_email"))
154+
155+
156+
## ... code continues from here with similar redirect examples ...
157+
```
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
title: flask request Example Python Code
2+
category: page
3+
slug: flask-request-examples
4+
sortorder: 50103
5+
toc: False
6+
sidebartitle: flask request
7+
meta: Python code examples for the request object from the Flask project used for building web applications.
8+
9+
10+
The [Flask](/flask.html)
11+
[request](https://flask.palletsprojects.com/en/1.1.x/reqcontext/)
12+
([source code](https://github.com/pallets/flask/blob/master/src/flask/globals.py))
13+
object is critical for [building web applications](/web-development.html)
14+
with this [web framework](/web-framework.html). The request context
15+
allows you to obtain data sent from the client such as a web browser
16+
so that you can appropriately handle generating the response.
17+
18+
19+
## Example 1 from FlaskBB
20+
[FlaskBB](https://github.com/flaskbb/flaskbb)
21+
([project website](https://flaskbb.org/)) is a [Flask](/flask.html)-based
22+
forum web application. The web app allows users to chat in an open
23+
message board or send private messages in plain text or
24+
[Markdown](/markdown.html). FlaskBB is provided as open source
25+
[under this license](https://github.com/flaskbb/flaskbb/blob/master/LICENSE).
26+
27+
[**flaskbb / flaskbb / app.py**](https://github.com/flaskbb/flaskbb/blob/master/flaskbb/app.py)
28+
29+
```python
30+
# -*- coding: utf-8 -*-
31+
"""
32+
flaskbb.app
33+
-----------
34+
manages the app creation and configuration process
35+
:copyright: (c) 2014 by the FlaskBB Team.
36+
:license: BSD, see LICENSE for more details.
37+
"""
38+
import logging
39+
import logging.config
40+
import os
41+
import sys
42+
import time
43+
import warnings
44+
from datetime import datetime
45+
46+
~~from flask import Flask, request
47+
from flask_login import current_user
48+
from sqlalchemy import event
49+
from sqlalchemy.engine import Engine
50+
from sqlalchemy.exc import OperationalError, ProgrammingError
51+
52+
53+
## ... code abbreviated here due to several hundred non-relevant lines ...
54+
55+
56+
def configure_before_handlers(app):
57+
"""Configures the before request handlers."""
58+
59+
~~ @app.before_request
60+
def update_lastseen():
61+
"""Updates `lastseen` before every reguest if the user is
62+
authenticated."""
63+
if current_user.is_authenticated:
64+
current_user.lastseen = time_utcnow()
65+
db.session.add(current_user)
66+
db.session.commit()
67+
68+
if app.config["REDIS_ENABLED"]:
69+
70+
~~ @app.before_request
71+
def mark_current_user_online():
72+
if current_user.is_authenticated:
73+
mark_online(current_user.username)
74+
else:
75+
~~ mark_online(request.remote_addr, guest=True)
76+
77+
app.pluggy.hook.flaskbb_request_processors(app=app)
78+
```

content/pages/meta/00-change-log.markdown

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ on GitHub.
1919
* Merged [PR #215](https://github.com/mattmakai/fullstackpython.com/pull/215)
2020
to fix a typo on the [serverless](/serverless.html) page. Thanks
2121
[Kyle](https://github.com/kylekizirian)!
22+
* Added new [Flask](/flask-code-examples.html) code examples:
23+
* [flask request](/flask-request-examples.html)
24+
* [flask redirect](/flask-redirect-examples.html)
2225
* Added new [Django](/django-code-examples.html) code examples pages:
2326
* [django.contrib.auth get_user_model](/django-contrib-auth-get-user-model-examples.html)
2427
* [django.contrib.auth.decorators login_required](/django-contrib-auth-decorators-login-required-examples.html)

theme/templates/table-of-contents.html

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,8 @@ <h4 class="bp"><a href="/django-utils-timezone-examples.html">django.utils.timez
256256
</div>
257257
<div class="c6">
258258
<h3 style="margin-top:16px"><a href="/flask-core-extensions-code-examples.html">Flask core and extensions examples</a></h3>
259+
<h4 class="bp"><a href="/flask-redirect-examples.html">flask redirect</a></h4>
260+
<h4 class="bp"><a href="/flask-request-examples.html">flask request</a></h4>
259261
<h4 class="bp"><a href="/flask-sqlalchemy-model-examples.html">flask_sqlalchemy.SQLAlchemy.Model</a></h4>
260262

261263
</div>

0 commit comments

Comments
 (0)