https://github.com/honmaple/flask-maple
flask tips
https://github.com/honmaple/flask-maple
Last synced: 3 months ago
JSON representation
flask tips
- Host: GitHub
- URL: https://github.com/honmaple/flask-maple
- Owner: honmaple
- License: bsd-3-clause
- Created: 2016-04-18T10:12:14.000Z (about 10 years ago)
- Default Branch: master
- Last Pushed: 2019-05-13T14:44:06.000Z (about 7 years ago)
- Last Synced: 2025-09-20T22:45:03.895Z (9 months ago)
- Language: Python
- Homepage:
- Size: 3.49 MB
- Stars: 6
- Watchers: 3
- Forks: 3
- Open Issues: 0
-
Metadata Files:
- Readme: README.org
- License: LICENSE
Awesome Lists containing this project
README
* Flask-Maple
[[https://pypi.python.org/pypi/Flask-Maple][https://img.shields.io/badge/pypi-v0.5.5-brightgreen.svg]]
[[https://pypi.python.org/pypi/Flask-Maple][https://img.shields.io/badge/python-3.4-brightgreen.svg]]
[[LICENSE][https://img.shields.io/badge/license-BSD-blue.svg]]
** 安装
To install Flask-Maple:
#+BEGIN_SRC python
pip install flask-maple
#+END_SRC
Or alternatively, you can download the repository and install manually by doing:
#+BEGIN_SRC python
git clone git@github.com:honmaple/flask-maple.git
cd flask-maple
python setup.py install
#+END_SRC
** 用户系统
在 *flask_maple/auth/model.py* 中默认实现了 *GroupMixin* 与 *UserMixin*
如果要创建 user 表与 group 表,只需要
#+BEGIN_SRC python
from flask_maple.auth.models import UserMixin, GroupMixin
class User(db.Model, UserMixin):
pass
class Group(db.Model, GroupMixin):
pass
#+END_SRC
即可
*user* 表默认创建以下字段, 可添加更多想要的字段
- id
- username
- password
- email
- is_superuser
- is_confirmed
- register_time
- last_login
- groups
*group* 表默认创建以下字段
- id
- name
- users
- parent_group
- child_groups
** 权限
*** 使用
#+BEGIN_SRC python
from flask_maple.permission.models import PermissionMixin
class Permission(db.Model, PermissionMixin):
pass
#+END_SRC
user 表与 group 表可继承 *flask_maple.permission.models.UserMixin* 与 *flask_maple.permission.models.GroupMixin*
或者直接使用 *flask_maple.auth.models.UserMixin* 与 *flask_maple.auth.models.GroupMixin*
- 添加权限
#+BEGIN_SRC python
identity = user # or group
identity.add_perm(
action,
resource,
resource_type='endpoint',
description=None)
#+END_SRC
- 删除权限
#+BEGIN_SRC python
identity.remove_perm(
action,
resource,
resource_type='endpoint')
#+END_SRC
- 检查权限
#+BEGIN_SRC python
identity.has_perm(action, resource, resource_type='endpoint', and_=False)
#+END_SRC
*** 权限缓存
默认权限会从数据库获取, 如果经常使用,可自行添加缓存, 并在添加删除权限后自行对缓存进行操作
#+BEGIN_SRC python
class User(db.Model, UserMixin):
def perm_cache(self,
action,
resource,
resource_type='endpoint',
and_=False):
return
#+END_SRC
** 登录
依赖于 *flask-login*, *flask-mail*
*** 使用
#+BEGIN_SRC python
from flask_maple import auth
auth.init_app(app)
# 或者
from flask_maple.auth.views import Auth
Auth(app)
#+END_SRC
将会创建 6个 *url*
- /login
- /logout
- /register
- /forget
- /confirm
- /confirm/
可以自定义登陆,注册,忘记密码页面,以登陆页面为例 (templates/maple/login.html)
#+BEGIN_SRC html
{% extends "base/base.html" %}
{%- block content -%}
{% import 'maple/auth.html' as auth %}
{% endblock %}
#+END_SRC
*** 注意事项
登陆与登出默认使用 *user.login(remember)* , *user.logout()*, 如果未使用 *flask_maple/auth/model.py* 中的 *UserMixin*,则需要自己定义
** 验证码
使用 *Pillow* 生成验证码
#+BEGIN_SRC python
pip install pillow
#+END_SRC
*** 使用
#+BEGIN_SRC python
from flask_maple import Captcha
captcha = Captcha(app)
# 因为字体可能存在侵权,所以需要指定自己服务器字体, 默认为 /usr/share/fonts/TTF/DejaVuSans.ttf
captcha = Captcha(app, font="")
#+END_SRC
然后访问 [[http://127.0.0.1/captcha][http://127.0.0.1/captcha]]
*** 配置
#+BEGIN_SRC python
CAPTCHA_URL = "The captcha url,default 'captcha'"
#+END_SRC
** 错误处理
主要是对发生错误时的页面进行定制(403,404,500)
#+BEGIN_SRC python
from flask_maple import Error
error = Error(app)
#+END_SRC
定制图片源于*flask*官网,侵删
** 邮箱
依赖于 *flask-mail*, 区别使用多线程发送
#+BEGIN_SRC python
from flask_maple.mail import Mail
mail = Mail(app)
mail.send_email(*args, **kwargs)
#+END_SRC
此外,还有一个 *MailMixin*,实现了邮箱验证需要的密钥,
#+BEGIN_SRC python
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))
#+END_SRC
** 表单
** 数据库
像 django 一样使用 *flask-sqlalchemy*
*djang orm* 与 sqlalchemy 相比,为什么很多人都认为 django orm 更好用,大概就是因为 django orm 更方便
*** 基本查询(已实现)
- gt
- lt
- lte
- gte
- contains
- in
- exact
- iexact
- startswith
- istartswith
- iendswith
- endswith
- isnull
- range
- year
- month
- day
示例:
#+BEGIN_SRC python
Post.query.filter_by(title__contains = 'sql').all()
Post.query.exclude_by(title__contains = 'sql').all()
#+END_SRC
*** 关系查询
#+BEGIN_SRC python
Post.query.filter_by(tags__name__contains = 'sql').all()
#+END_SRC
*** 其它
#+BEGIN_SRC python
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')
#+END_SRC
** 序列化
把 *sqlalchemy* 对象序列化为 *json*, 使用方法参考于 *django rest framework*
*** 多个实例
#+BEGIN_SRC python
from flask_maple.serializer import Serializer
posts = Post.query.all()
serializer = Serializer(posts)
data = serializer.data
#+END_SRC
*** 单个实例
#+BEGIN_SRC python
post = Post.query.first()
serializer = Serializer(post)
data = serializer.data
#+END_SRC
*** 排除字段
#+BEGIN_SRC python
serializer = Seralizer(post,exclude=['title'])
#+END_SRC
*** 仅包括字段
#+BEGIN_SRC python
serializer = Seralizer(post,include=['title'])
#+END_SRC
*** 关系查询深度
#+BEGIN_SRC python
serializer = Seralizer(post,depth=3)
#+END_SRC
depth 默认为*2*
*** 额外的字段
#+BEGIN_SRC python
class Post(Model):
......
def get_post_count(self):
return 11
serializer = Serializer(post,extra=['get_post_count'])
#+END_SRC
*** 自定义
#+BEGIN_SRC python
from flask_maple.serializer import Serializer
class PostSerializer(Serializer):
class Meta:
include = []
depth = 2
include = []
exclude = []
extra = ['count']
serializer = PostSerializer(post,include=['title'])
#+END_SRC
** 中间件
参考于 *django*
#+BEGIN_SRC python
from flask_maple.middleware import Middleware
app = ...
Middleware(app)
#+END_SRC
中间件写法(以一个简单的性能测试中间件为例)
#+BEGIN_SRC python
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
#+END_SRC
*重要* ,需要加入中间件配置
#+BEGIN_EXAMPLE
MIDDLEWARE = ["path.to.ProfileMiddleware"]
#+END_EXAMPLE
** 日志
记录 *info* 和 *error* 两个日志 level, 使用很简单
#+BEGIN_SRC python
from flask_maple.log import Logging
app = ...
Logging(app)
#+END_SRC
配置文件
#+BEGIN_SRC python
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
'''
}
#+END_SRC
当*send_mail*为 *True*时, 配置依赖于 *flask_mail*的配置(主要是不想写多份)
#+BEGIN_EXAMPLE
MAIL_USERNAME
MAIL_PASSWORD
MAIL_SERVER
MAIL_PORT
MAIL_DEFAULT_SENDER
#+END_EXAMPLE
** App
创建两个常用的 *url*
- /robots.txt
- /favicon.ico
*** 使用
#+BEGIN_SRC python
from flask_maple.app import App
App(app)
#+END_SRC
此外,因为国际化等原因,可以传递 *flask_maple.json.CustomJSONEncoder* 给 App
#+BEGIN_SRC python
from flask_maple.app import App
from flask_maple.json import CustomJSONEncoder
App(app, json=CustomJSONEncoder)
#+END_SRC
*** 配置
参考于 django,可以懒加载 blueprint
#+BEGIN_EXAMPLE
INSTALLED_APPS = [
"path.to.blueprint1",
"path.to.blueprint2",
{
"kwargs":{},
"blueprint":{}
}
]
#+END_EXAMPLE
** Bootstrap
主要是个人经常使用的一些模板,比如 bootstrap 的js,css 文件,分页模板, 上下撑满等
并依赖于 *flask-assets* ,对 js,css 文件进行压缩
*** 使用
#+BEGIN_SRC python
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'),
auth=True)
#+END_SRC
或者
#+BEGIN_SRC python
bootstrap = Bootstrap()
bootstrap.init_app(app)
#+END_SRC
*** 模板
#+BEGIN_SRC html
{% extends 'maple/base.html' %}
{% block main -%}
submit
{% endblock -%}
#+END_SRC
*** 配置
#+BEGIN_SRC python
AUTHOR_NAME = "This will show you name at html footer"
#+END_SRC
** Redis
默认会加载 *rediscluster.StrictRedisCluster* ,如果 rediscluster 未安装则加载 *redis.StrictRedis*
*** 使用
#+BEGIN_SRC python
from flask_maple.redis import Redis
redis = Redis(app)
# 像平时使用 redispy 一样使用
print(redis.get(...))
#+END_SRC
*** 配置
#+BEGIN_EXAMPLE
REDSI = {...}
#+END_EXAMPLE