-
Notifications
You must be signed in to change notification settings - Fork 9
/
example.py
75 lines (61 loc) · 1.86 KB
/
example.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
# -*- coding: utf-8 -*-
from collections import namedtuple
from flask import Flask, g, render_template, render_template_string, abort
from flask_sqlalchemy import SQLAlchemy
from flask_perm import Perm
from flask_script import Manager
app = Flask(__name__)
manager = Manager(app)
db = SQLAlchemy()
perm = Perm()
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'secret key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/flask_perm.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['PERM_ADMIN_ECHO'] = True
db.app = app
db.init_app(app)
perm.app = app
perm.init_app(app)
perm.register_commands(manager)
class User(namedtuple('User', 'id nickname')):
pass
@app.before_request
def before_request():
g.user = User(**{'id': 1, 'nickname': 'user1'})
@perm.user_loader
def load_user(user_id):
return User(**{'id': user_id, 'nickname': 'user%d' % user_id})
@perm.users_loader
def load_users(filter_by, sort_field, sort_dir, offset, limit):
return [User(**{'id': id, 'nickname': 'user%d' % id}) for id in range(20)]
@perm.current_user_loader
def load_current_user():
return g.user
@app.errorhandler(perm.Denied)
def permission_denied(e):
return 'FORBIDDEN', 403
@app.route('/post/publish')
@perm.require_permission('post.publish')
def publish_post():
return 'Hey, you can publish post!'
@app.route('/post/publish/template')
def template_level_visible():
return render_template_string("""
{% if require_permission('post.publish') %}
Hey, you can publish post!
{% else %}
No, you can't see this.
{% endif %}
""")
if __name__ == '__main__':
"""
To create superadmin, run
$ python example.py perm create_superadmin your_admin_account
Please input password:
Please input password again:
Success!
To run server, run
$ python example.py runserver
"""
manager.run()