To install Flask-Maple:css
pip install flask-maple
Or alternatively, you can download the repository and install manually by doing:html
git clone git@github.com:honmaple/flask-maple.git cd flask-maple python setup.py install
在 flask_maple/auth/model.py 中默認實現了 GroupMixin 與 UserMixin
若是要建立 user 表與 group 表,只須要python
from flask_maple.auth.models import UserMixin, GroupMixin class User(db.Model, UserMixin): pass class Group(db.Model, GroupMixin): pass
便可git
user 表默認建立如下字段, 可添加更多想要的字段github
group 表默認建立如下字段redis
from flask_maple.permission.models import PermissionMixin class Permission(db.Model, PermissionMixin): pass
user 表與 group 表可繼承 flask_maple.permission.models.UserMixin 與 flask_maple.permission.models.GroupMixin
或者直接使用 flask_maple.auth.models.UserMixin 與 flask_maple.auth.models.GroupMixinsql
添加權限數據庫
identity = user # or group identity.add_perm( action, resource, resource_type='endpoint', description=None)
刪除權限django
identity.remove_perm( action, resource, resource_type='endpoint')
檢查權限json
identity.has_perm(action, resource, resource_type='endpoint', and_=False)
默認權限會從數據庫獲取, 若是常常使用,可自行添加緩存, 並在添加刪除權限後自行對緩存進行操做
class User(db.Model, UserMixin): def perm_cache(self, action, resource, resource_type='endpoint', and_=False): return
依賴於 flask-login, flask-mail
from flask_maple import auth auth.init_app(app) # 或者 from flask_maple.auth.views import Auth Auth(app)
將會建立6個 url
能夠自定義登錄,註冊,忘記密碼頁面,以登錄頁面爲例 (templates/maple/login.html)
{% extends "base/base.html" %} {%- block content -%} {% import 'maple/auth.html' as auth %} <div class="panel panel-primary"> <div class="panel-heading"> <a href="{{ url_for('auth.login') }}" style="color:#fff">{{ _('Login')}}</a> </div> <div class="panel-body"> {{ auth.login()}} </div> </div> {% endblock %}
登錄與登出默認使用 user.login(remember) , user.logout(), 若是未使用 flask_maple/auth/model.py 中的 UserMixin,則須要本身定義
使用 Pillow 生成驗證碼
pip install pillow
from flask_maple import Captcha captcha = Captcha(app) # 由於字體可能存在版權問題,因此須要指定本身服務器字體, 默認爲 /usr/share/fonts/TTF/DejaVuSans.ttf captcha = Captcha(app, font="")
CAPTCHA_URL = "The captcha url,default 'captcha'"
主要是對發生錯誤時的頁面進行定製(403,404,500)
from flask_maple import Error error = Error(app)
定製圖片源於flask官網,侵刪
依賴於 flask-mail, 區別使用多線程發送
from flask_maple.mail import Mail mail = Mail(app) mail.send_email(*args, **kwargs)
此外,還有一個 MailMixin,實現了郵箱驗證須要的密鑰,
from flask_maple.mail import MailMixin class User(db.Model, MailMixin): pass print(user.email_token) print(User.check_email_token(token, max_age=259200))
像django同樣使用 flask-sqlalchemy
djang orm 與sqlalchemy相比,爲何不少人都認爲django orm更好用,大概就是由於django orm更方便
示例:
Post.query.filter_by(title__contains = 'sql').all() Post.query.exclude_by(title__contains = 'sql').all()
Post.query.filter_by(tags__name__contains = 'sql').all()
Post.query.filter_by(tags__name__contains = 'sql').or(Post.id == 1,Post.id == 2).all() Post.query.filter_by(tags__name__contains = 'sql').and(Post.id == 1,Post.id == 2).all() Post.query.filter_by(tags__name__contains = 'sql').exists() Post.query.load_only('title')
把 sqlalchemy 對象序列化爲 json, 使用方法參考於 django rest framework
from flask_maple.serializer import Serializer posts = Post.query.all() serializer = Serializer(posts) data = serializer.data
post = Post.query.first() serializer = Serializer(post) data = serializer.data
serializer = Seralizer(post,exclude=['title'])
serializer = Seralizer(post,include=['title'])
serializer = Seralizer(post,depth=3)
depth默認爲2
class Post(Model): ...... def get_post_count(self): return 11 serializer = Serializer(post,extra=['get_post_count'])
from flask_maple.serializer import Serializer class PostSerializer(Serializer): class Meta: include = [] depth = 2 include = [] exclude = [] extra = ['count'] serializer = PostSerializer(post,include=['title'])
參考於 django
from flask_maple.middleware import Middleware app = ... Middleware(app)
中間件寫法(以一個簡單的性能測試中間件爲例)
class ProfileMiddleware(object): def preprocess_request(self): pr = cProfile.Profile() pr.enable() request.pr = pr def process_response(self, response): pr = request.pr pr.disable() s = StringIO() sortby = 'cumulative' ps = pstats.Stats(pr, stream=s).sort_stats(sortby) ps.print_stats() print(s.getvalue()) return response
重要 ,須要加入中間件配置
MIDDLEWARE = ["path.to.ProfileMiddleware"]
記錄 info 和 error 兩個日誌level, 使用很簡單
from flask_maple.log import Logging app = ... Logging(app)
配置文件
LOGGING = { 'info': 'logs/info.log', # 記錄info level的日誌,與配置文件同級下的logs目錄,可修改 'error': 'logs/error.log', # 記錄error level的日誌 'send_mail': False, # 當有錯誤發生時,是否發送郵件到管理員郵箱 'toaddrs': [], # 管理員郵箱,可爲多個 'subject': 'Your Application Failed', 'formatter': ''' Message type: %(levelname)s Location: %(pathname)s:%(lineno)d Module: %(module)s Function: %(funcName)s Time: %(asctime)s Message: %(message)s ''' }
當send_mail爲 True時, 配置依賴於 flask_mail的配置(主要是不想寫多份)
MAIL_USERNAME MAIL_PASSWORD MAIL_SERVER MAIL_PORT MAIL_DEFAULT_SENDER
建立兩個經常使用的 url
from flask_maple.app import App App(app)
此外,由於國際化等緣由,能夠傳遞 flask_maple.json.CustomJSONEncoder 給App
from flask_maple.app import App from flask_maple.json import CustomJSONEncoder App(app, json=CustomJSONEncoder)
參考於 django,能夠懶加載 blueprint
INSTALLED_APPS = [ "path.to.blueprint1", "path.to.blueprint2", { "kwargs":{}, "blueprint":{} } ]
主要是我的常常使用的一些模板,好比bootstrap的js,css文件,分頁模板, 上下撐滿等
並依賴於 flask-assets ,對js,css文件進行壓縮
from flask_maple import Bootstrap bootstrap = Bootstrap( app, css=('styles/monokai.css', 'styles/mine.css'), js=('styles/upload.js', 'styles/forums.js', 'styles/following.js', 'styles/topic.js'), use_auth=True)
或者
bootstrap = Bootstrap() bootstrap.init_app(app)
{% extends 'maple/base.html' %} {% block main -%} <button class="btn btn-primary">submit</button> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> {% endblock -%}
AUTHOR_NAME = "This will show you name at html footer"
默認會加載 rediscluster.StrictRedisCluster ,若是rediscluster未安裝則加載 redis.StrictRedis
from flask_maple.redis import Redis redis = Redis(app) # 像平時使用redispy同樣使用 print(redis.get(...))
REDSI = {...}
具體例子可查看maple-bbs/extension