网站开发字体选择,国家企业信息信用信息系统查询,网站cms系统源码,我做钓鱼网站自首了我最近接触到了一个极为出色的Flask后台库——pear-admin-flask#xff0c;这个库具有很高的二次开发价值。借此机会学习并吸收其中Flask开发的一些高级技巧。
1. flask 自定义命令 pear-admin-flask/applications/common/script/admin.py
from flask.cli import AppGroup …我最近接触到了一个极为出色的Flask后台库——pear-admin-flask这个库具有很高的二次开发价值。借此机会学习并吸收其中Flask开发的一些高级技巧。
1. flask 自定义命令 pear-admin-flask/applications/common/script/admin.py
from flask.cli import AppGroup # 导入库
admin_cli AppGroup(admin) # 定义子命令 admin
...admin_cli.command(init) # 定义子命令操作 init
def init_db(): # 函数db.session.add_all(userdata)...命令行调用
flask admin init2. 权限管理
a. 数据库定义权限 pear-admin-flask/applications/common/script/admin.py
# 作者提供了非常有效的权限管理过程
powerdata [Power(id1,name系统管理,type0,code,urlNone,open_typeNone,parent_id0,iconlayui-icon layui-icon-set-fill,sort1,create_timenow_time,enable1,),...
]
b. 定义权限拦截函数 pear-admin-flask/applications/common/utils/rights.py
def authorize(power: str, log: bool False):用户权限判断用于判断目前会话用户是否拥有访问权限:param power: 权限标识:type power: str:param log: 是否记录日志, defaults to False:type log: bool, optionaldef decorator(func):login_requiredwraps(func)def wrapper(*args, **kwargs):# 定义管理员的id为1if current_user.username current_app.config.get(SUPERADMIN):return func(*args, **kwargs)if not power in session.get(permissions):if log:admin_log(requestrequest, is_accessFalse)if request.method GET:abort(403)else:return jsonify(successFalse, msg权限不足!)if log:admin_log(requestrequest, is_accessTrue)return func(*args, **kwargs)return wrapperreturn decorator
c. 加载权限 pear-admin-flask/applications/view/system/passport.py
session[permissions] user_powerd. 使用过程 多个文件中都有使用, 例如: pear-admin-flask/applications/view/system/dept.py bp.get(/)
authorize(system:dept:main, logTrue)
def main():return render_template(system/dept/main.html)
3. Blueprint 的使用, 这个我在另外一个项目中也用过, 可以将 flask 接口分到多个文件实现. pear-admin-flask/applications/view/system/dept.py
# 导入 Blueprint
from flask import Blueprint, render_template, request, jsonify
# 初始化
bp Blueprint(dept, __name__, url_prefix/dept)
# 使用修饰器实现接口
bp.get(/)
authorize(system:dept:main, logTrue)
def main():return render_template(system/dept/main.html)
然后 统一初始化 api. /pear-admin-flask/applications/view/system/__init__.py
from flask import Flask, Blueprintfrom applications.view.system.dict import bp as dict_bp
...system_bp Blueprint(system, __name__, url_prefix/system)def register_system_bps(app: Flask):# 在admin_bp下注册子蓝图system_bp.register_blueprint(user_bp)...
接下来就可以通过浏览器 GET http://ip:port/system/dept 访问到 pear-admin-flask/applications/view/system/dept.py 中接口函数.
4. flask_login 登陆管理,
a. 定义用户登陆函数 pear-admin-flask/applications/extensions/init_login.py login_manager.user_loaderdef load_user(user_id):from applications.models import Useruser User.query.get(int(user_id))return user
b. 登陆登出 pear-admin-flask/applications/view/system/passport.py
from flask_login import current_user, login_user, login_required, logout_user# 登录
bp.post(/login)
def login_post():...login_user(user, rememberremember)...
# 登出
bp.post(/logout)
login_required
def logout():logout_user()session.pop(permissions)return success_api(msg注销成功)
c. 会话管理, 验证是否登陆,没有登陆就禁止访问, pear-admin-flask/applications/common/utils/rights.py from flask_login import login_required, current_userlogin_required # 登陆许可修饰器
wraps(func)
def wrapper(*args, **kwargs):5. flask_uploads 用于管理文件上传操作, pear-admin-flask/applications/extensions/init_upload.py
# 导入
from flask_uploads import UploadSet, IMAGES
# 定义集合与路径
photos UploadSet(photos, IMAGES)def init_upload(app: Flask):# 关联 appconfigure_uploads(app, photos)
使用 photos 在上传接口接收文件 pear-admin-flask/applications/view/system/file.py
# 上传接口
bp.post(/upload)
authorize(system:file:add, logTrue)
def upload_api():if file in request.files:photo request.files[file]mime request.files[file].content_typefile_url upload_curd.upload_one(photophoto, mimemime)res {msg: 上传成功,code: 0,success: True,data:{src: file_url}}return jsonify(res)return fail_api()6. flask_sqlalchemy 数据库管理
这个可以单独写一节, 主要是感觉数据库的内容挺多的,这里看看库的样例, 大致样式如下 pear-admin-flask/applications/models/admin_user_role.py
from applications.extensions import db# 创建中间表
user_role db.Table(admin_user_role, # 中间表名称db.Column(id, db.Integer, primary_keyTrue, autoincrementTrue, comment标识), # 主键db.Column(user_id, db.Integer, db.ForeignKey(admin_user.id), comment用户编号), # 属性 外键db.Column(role_id, db.Integer, db.ForeignKey(admin_role.id), comment角色编号), # 属性 外键
)
不明白的可以留言讨论或者自行在百度即可.
7. flask_marshmallow 可将 SQLAlchemy 数据 转换为 RESTful API 格式 , 具体查看项目 内容 pear-admin-flask/applications/extensions/init_sqlalchemy.py
from flask_sqlalchemy import SQLAlchemy
from flask_sqlalchemy.query import Query as BaseQuery
from flask_marshmallow import Marshmallow
...
# 重写 BaseQuery
class Query(BaseQuery):...def all_json(self, schema: Marshmallow().Schema):return schema(manyTrue).dump(self.all())def layui_paginate(self):return self.paginate(pagerequest.args.get(page, typeint),per_pagerequest.args.get(limit, typeint),error_outFalse)def layui_paginate_json(self, schema: Marshmallow().Schema):返回dict_res self.paginate(pagerequest.args.get(page, typeint),per_pagerequest.args.get(limit, typeint),error_outFalse)return schema(manyTrue).dump(_res.items), _res.total, _res.page, _res.per_pagedb SQLAlchemy(query_classQuery)
ma Marshmallow()8. flask_migrate 提供数据库的版本管理等功能 9. flask_mail 提供邮件发送功能 10. flask_session 管理会话 11. 我在使用 flask 的时候, 经常 flask_restx 提供的一些方法, 供大家参考 flask-restx 基于 flask 的 restful 风格的插件
from flask import Flask
from flask_restx import Api, Resourceapi Api()app Flask(__name__)
api.init_app(app)api.route(/hello,strict_slashesFalse)
class HelloWorld(Resource):def get(self):# 如果使用模板的块需要使用 make_response# return make_response(render_template(index.html, datares), 200)# 使用 jsonify 是为了返回json数据的同时相比于 json.dumps() 其会自动修改 content-type 为 application/json# 另外如果使用 jsonify()的同时还想自定义返回状态码可以使用 make_response(jsonify(datadata), 201)return jsonify({hello: world})def post(self):passdef put(self):passdef delete(self):passif __name__ __main__:app.run(debugTrue)也可以使用 flask_restx 提供的参数校验.
from flask_restx import reqparsedef create_reqparse(args):rp reqparse.RequestParser()for i in args:rp.add_argument(i[0],**i[1])return rpcreate_annotation create_reqparse([[image_id,{type:int,required:True,location:json}],[category_id,{type:int,location:json}]])api.route(/)
class AnnotatorData(Resource):api.expect(create_annotation)def post(self):args create_annotation.parse_args()...还推荐一个延时任务工具 celery, 目前 pear 项目没有使用, 大家可以百度其用法. 文章转载自: http://www.morning.hlwzd.cn.gov.cn.hlwzd.cn http://www.morning.kgkph.cn.gov.cn.kgkph.cn http://www.morning.jqpyq.cn.gov.cn.jqpyq.cn http://www.morning.xbmwm.cn.gov.cn.xbmwm.cn http://www.morning.jfzbk.cn.gov.cn.jfzbk.cn http://www.morning.gfkb.cn.gov.cn.gfkb.cn http://www.morning.jbztm.cn.gov.cn.jbztm.cn http://www.morning.smmrm.cn.gov.cn.smmrm.cn http://www.morning.byxs.cn.gov.cn.byxs.cn http://www.morning.skbhl.cn.gov.cn.skbhl.cn http://www.morning.zmpqh.cn.gov.cn.zmpqh.cn http://www.morning.cbqqz.cn.gov.cn.cbqqz.cn http://www.morning.bksbx.cn.gov.cn.bksbx.cn http://www.morning.rjyd.cn.gov.cn.rjyd.cn http://www.morning.xczyj.cn.gov.cn.xczyj.cn http://www.morning.wdxr.cn.gov.cn.wdxr.cn http://www.morning.fqzz3.cn.gov.cn.fqzz3.cn http://www.morning.ryxdf.cn.gov.cn.ryxdf.cn http://www.morning.ntqlz.cn.gov.cn.ntqlz.cn http://www.morning.skbkq.cn.gov.cn.skbkq.cn http://www.morning.mrlls.cn.gov.cn.mrlls.cn http://www.morning.bmpjp.cn.gov.cn.bmpjp.cn http://www.morning.krkwp.cn.gov.cn.krkwp.cn http://www.morning.qcdhg.cn.gov.cn.qcdhg.cn http://www.morning.wpydf.cn.gov.cn.wpydf.cn http://www.morning.jrwbl.cn.gov.cn.jrwbl.cn http://www.morning.nrfrd.cn.gov.cn.nrfrd.cn http://www.morning.jqsyp.cn.gov.cn.jqsyp.cn http://www.morning.wfysn.cn.gov.cn.wfysn.cn http://www.morning.lbqt.cn.gov.cn.lbqt.cn http://www.morning.hrtwt.cn.gov.cn.hrtwt.cn http://www.morning.nbwyk.cn.gov.cn.nbwyk.cn http://www.morning.mwpcp.cn.gov.cn.mwpcp.cn http://www.morning.wbysj.cn.gov.cn.wbysj.cn http://www.morning.wdlyt.cn.gov.cn.wdlyt.cn http://www.morning.sbczr.cn.gov.cn.sbczr.cn http://www.morning.hdscx.cn.gov.cn.hdscx.cn http://www.morning.dhpjq.cn.gov.cn.dhpjq.cn http://www.morning.hsjfs.cn.gov.cn.hsjfs.cn http://www.morning.kzcfr.cn.gov.cn.kzcfr.cn http://www.morning.ndlww.cn.gov.cn.ndlww.cn http://www.morning.xkwrb.cn.gov.cn.xkwrb.cn http://www.morning.frxsl.cn.gov.cn.frxsl.cn http://www.morning.kkhf.cn.gov.cn.kkhf.cn http://www.morning.kfwrq.cn.gov.cn.kfwrq.cn http://www.morning.hybmz.cn.gov.cn.hybmz.cn http://www.morning.clpkp.cn.gov.cn.clpkp.cn http://www.morning.qbzfp.cn.gov.cn.qbzfp.cn http://www.morning.lywcd.cn.gov.cn.lywcd.cn http://www.morning.kgmkl.cn.gov.cn.kgmkl.cn http://www.morning.gbxxh.cn.gov.cn.gbxxh.cn http://www.morning.kjyqr.cn.gov.cn.kjyqr.cn http://www.morning.syfty.cn.gov.cn.syfty.cn http://www.morning.tkyxl.cn.gov.cn.tkyxl.cn http://www.morning.wqpsf.cn.gov.cn.wqpsf.cn http://www.morning.taojava.cn.gov.cn.taojava.cn http://www.morning.ndpwg.cn.gov.cn.ndpwg.cn http://www.morning.rjrz.cn.gov.cn.rjrz.cn http://www.morning.lrplh.cn.gov.cn.lrplh.cn http://www.morning.sgpny.cn.gov.cn.sgpny.cn http://www.morning.rwrn.cn.gov.cn.rwrn.cn http://www.morning.bmmhs.cn.gov.cn.bmmhs.cn http://www.morning.nmbbt.cn.gov.cn.nmbbt.cn http://www.morning.ywpcs.cn.gov.cn.ywpcs.cn http://www.morning.hrydl.cn.gov.cn.hrydl.cn http://www.morning.rnpnn.cn.gov.cn.rnpnn.cn http://www.morning.rqqkc.cn.gov.cn.rqqkc.cn http://www.morning.gbsby.cn.gov.cn.gbsby.cn http://www.morning.jcnmy.cn.gov.cn.jcnmy.cn http://www.morning.rcmwl.cn.gov.cn.rcmwl.cn http://www.morning.jgrjj.cn.gov.cn.jgrjj.cn http://www.morning.hwnnm.cn.gov.cn.hwnnm.cn http://www.morning.rdlfk.cn.gov.cn.rdlfk.cn http://www.morning.nqcwz.cn.gov.cn.nqcwz.cn http://www.morning.ztdlp.cn.gov.cn.ztdlp.cn http://www.morning.ryfq.cn.gov.cn.ryfq.cn http://www.morning.nfcxq.cn.gov.cn.nfcxq.cn http://www.morning.bxbkq.cn.gov.cn.bxbkq.cn http://www.morning.yymlk.cn.gov.cn.yymlk.cn http://www.morning.mcgsq.cn.gov.cn.mcgsq.cn