-
Notifications
You must be signed in to change notification settings - Fork 538
/
app_with_local_proxy.py
78 lines (55 loc) · 1.55 KB
/
app_with_local_proxy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# coding=utf-8
import random
from flask import Flask, render_template
from werkzeug.local import LocalStack, LocalProxy
from ext import db
from users import User
app = Flask(__name__, template_folder='../../templates')
app.config.from_object('config')
db.init_app(app)
_user_stack = LocalStack()
def get_current_user():
top = _user_stack.top
if top is None:
raise RuntimeError()
return top
current_user = LocalProxy(get_current_user)
@app.before_first_request
def setup():
db.drop_all()
db.create_all()
fake_users = [
User('xiaoming', 'xiaoming@dongwm.com'),
User('dongwweiming', 'dongwm@dongwm.com'),
User('admin', 'admin@dongwm.com')
]
db.session.add_all(fake_users)
db.session.commit()
@app.before_request
def before_request():
users = User.query.all()
user = random.choice(users)
_user_stack.push(user)
@app.teardown_appcontext
def teardown(exc=None):
if exc is None:
db.session.commit()
else:
db.session.rollback()
db.session.remove()
_user_stack.pop()
@app.context_processor
def template_extras():
return {'enumerate': enumerate, 'current_user': current_user}
@app.errorhandler(404)
def page_not_found(error):
return 'This page does not exist', 404
@app.template_filter('capitalize')
def reverse_filter(s):
return s.capitalize()
@app.route('/users')
def user_view():
users = User.query.all()
return render_template('chapter3/section4/user.html', users=users)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=9000)