Skip to content

Commit f978222

Browse files
committed
new code examples for flask
1 parent cfd095c commit f978222

File tree

6 files changed

+635
-5
lines changed

6 files changed

+635
-5
lines changed

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,17 @@ JavaScript plugin with the
4141
library. flask-phone-input is provided as open source under the
4242
[MIT license](https://github.com/miguelgrinberg/flask-phone-input/blob/1a1c227c044474ce0fe133493d7f8b0fb8312409/LICENSE).
4343

44+
### flaskSaaS
45+
[flaskSaas](https://github.com/alectrocute/flaskSaaS) is a boilerplate
46+
starter project to build a software-as-a-service (SaaS) web application
47+
in [Flask](/flask.html), with [Stripe](/stripe.html) for billing. The
48+
boilerplate relies on many common Flask extensions such as
49+
[Flask-WTF](https://flask-wtf.readthedocs.io/en/latest/),
50+
[Flask-Login](https://flask-login.readthedocs.io/en/latest/),
51+
[Flask-Admin](https://flask-admin.readthedocs.io/en/latest/), and
52+
many others. The project is provided as open source under the
53+
[MIT license](https://github.com/alectrocute/flaskSaaS/blob/master/LICENSE).
54+
4455

4556
### Flasky
4657
[Flasky](https://github.com/miguelgrinberg/flasky) is a wonderful

content/pages/examples/flask/flask-globals-request.markdown

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -644,7 +644,60 @@ def generate_csrf(secret_key=None, token_key=None):
644644
```
645645
646646
647-
## Example 6 from newspie
647+
## Example 6 from flaskSaaS
648+
[flaskSaas](https://github.com/alectrocute/flaskSaaS) is a boilerplate
649+
starter project to build a software-as-a-service (SaaS) web application
650+
in [Flask](/flask.html), with [Stripe](/stripe.html) for billing. The
651+
boilerplate relies on many common Flask extensions such as
652+
[Flask-WTF](https://flask-wtf.readthedocs.io/en/latest/),
653+
[Flask-Login](https://flask-login.readthedocs.io/en/latest/),
654+
[Flask-Admin](https://flask-admin.readthedocs.io/en/latest/), and
655+
many others. The project is provided as open source under the
656+
[MIT license](https://github.com/alectrocute/flaskSaaS/blob/master/LICENSE).
657+
658+
[**flaskSaaS / app / admin.py**](https://github.com/alectrocute/flaskSaaS/blob/master/app/./admin.py)
659+
660+
```python
661+
# admin.py
662+
import os.path as op
663+
664+
~~from flask import request, Response
665+
from werkzeug.exceptions import HTTPException
666+
from flask_admin import Admin
667+
from flask.ext.admin.contrib.sqla import ModelView
668+
from flask.ext.admin.contrib.fileadmin import FileAdmin
669+
670+
from app import app, db
671+
from app.models import User
672+
673+
674+
admin = Admin(app, name='Admin', template_mode='bootstrap3')
675+
676+
class ModelView(ModelView):
677+
678+
def is_accessible(self):
679+
~~ auth = request.authorization or request.environ.get('REMOTE_USER') # workaround for Apache
680+
if not auth or (auth.username, auth.password) != app.config['ADMIN_CREDENTIALS']:
681+
raise HTTPException('', Response('You have to an administrator.', 401,
682+
{'WWW-Authenticate': 'Basic realm="Login Required"'}
683+
))
684+
return True
685+
686+
# Users
687+
admin.add_view(ModelView(User, db.session))
688+
689+
# Static files
690+
path = op.join(op.dirname(__file__), 'static')
691+
admin.add_view(FileAdmin(path, '/static/', name='Static'))
692+
693+
694+
## ... source file continues with no further request examples...
695+
696+
697+
```
698+
699+
700+
## Example 7 from newspie
648701
[NewsPie](https://github.com/skamieniarz/newspie) is a minimalistic news
649702
aggregator created with [Flask](/flask.html) and the
650703
[News API](https://newsapi.org/).
@@ -853,7 +906,7 @@ if __name__ == '__main__':
853906
```
854907
855908
856-
## Example 7 from sandman2
909+
## Example 8 from sandman2
857910
[sandman2](https://github.com/jeffknupp/sandman2)
858911
([project documentation](https://sandman2.readthedocs.io/en/latest/)
859912
and

content/pages/examples/flask/flask-globals-session.markdown

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,3 +372,93 @@ def _get_config(
372372

373373
```
374374

375+
376+
## Example 4 from flaskSaaS
377+
[flaskSaas](https://github.com/alectrocute/flaskSaaS) is a boilerplate
378+
starter project to build a software-as-a-service (SaaS) web application
379+
in [Flask](/flask.html), with [Stripe](/stripe.html) for billing. The
380+
boilerplate relies on many common Flask extensions such as
381+
[Flask-WTF](https://flask-wtf.readthedocs.io/en/latest/),
382+
[Flask-Login](https://flask-login.readthedocs.io/en/latest/),
383+
[Flask-Admin](https://flask-admin.readthedocs.io/en/latest/), and
384+
many others. The project is provided as open source under the
385+
[MIT license](https://github.com/alectrocute/flaskSaaS/blob/master/LICENSE).
386+
387+
[**flaskSaaS / app / logger_setup.py**](https://github.com/alectrocute/flaskSaaS/blob/master/app/./logger_setup.py)
388+
389+
```python
390+
# logger_setup.py
391+
:Example:
392+
>>> from website import logger
393+
>>> logger.info('event', foo='bar')
394+
**Levels**:
395+
- logger.debug('For debugging purposes')
396+
- logger.info('An event occured, for example a database update')
397+
- logger.warning('Rare situation')
398+
- logger.error('Something went wrong')
399+
- logger.critical('Very very bad')
400+
You can build a log incrementally as so:
401+
>>> log = logger.new(date='now')
402+
>>> log = log.bind(weather='rainy')
403+
>>> log.info('user logged in', user='John')
404+
'''
405+
406+
import datetime as dt
407+
import logging
408+
from logging.handlers import RotatingFileHandler
409+
import pytz
410+
411+
~~from flask import request, session
412+
from structlog import wrap_logger
413+
from structlog.processors import JSONRenderer
414+
415+
from app import app
416+
417+
# Set the logging level
418+
app.logger.setLevel(app.config['LOG_LEVEL'])
419+
420+
# Remove the stdout handler
421+
app.logger.removeHandler(app.logger.handlers[0])
422+
423+
TZ = pytz.timezone(app.config['TIMEZONE'])
424+
425+
426+
def add_fields(_, level, event_dict):
427+
''' Add custom fields to each record. '''
428+
now = dt.datetime.now()
429+
event_dict['timestamp'] = TZ.localize(now, True).astimezone(pytz.utc).isoformat()
430+
event_dict['level'] = level
431+
432+
~~ if session:
433+
~~ event_dict['session_id'] = session.get('session_id')
434+
435+
if request:
436+
try:
437+
event_dict['ip_address'] = request.headers['X-Forwarded-For'].split(',')[0].strip()
438+
except:
439+
event_dict['ip_address'] = 'unknown'
440+
441+
return event_dict
442+
443+
444+
# Add a handler to write log messages to a file
445+
if app.config.get('LOG_FILENAME'):
446+
file_handler = RotatingFileHandler(filename=app.config['LOG_FILENAME'],
447+
maxBytes=app.config['LOG_MAXBYTES'],
448+
backupCount=app.config['LOG_BACKUPS'],
449+
mode='a',
450+
encoding='utf-8')
451+
file_handler.setLevel(logging.DEBUG)
452+
app.logger.addHandler(file_handler)
453+
454+
# Wrap the application logger with structlog to format the output
455+
logger = wrap_logger(
456+
app.logger,
457+
processors=[
458+
459+
460+
## ... source file continues with no further session examples...
461+
462+
463+
```
464+

0 commit comments

Comments
 (0)