搭建带管理模块的Python Flask应用
我之前做过几个小的Flask应用,都是只读的,过程让我很享受。现在我想在一个Flask应用里添加一个管理部分,想请教一下该怎么做。
我现在的文件夹结构是这样的:
├── Makefile
├── Procfile
├── app.py
├── requirements.txt
├── static
│ ├── css
│ ├── fonts
│ ├── img
│ └── js
└── templates
├── about.html
├── base.html
├── contact.html
└── index.html
我的app.py文件是这样的:
import os
from flask import Flask, render_template
app = Flask(__name__)
app.debug = True
# MAIN APPLICATION
@app.route('/')
@app.route('/work/<gallery>/')
def index(gallery='home'):
return render_template('index.html', gallery=gallery)
@app.route('/views/<view>/')
def view(view):
return render_template(view + '.html')
@app.route('/data/<gallery>/<size>/')
def data(gallery='home', size='md'):
data = '[\
{"image": "/static/img/photos/md/img_1.jpg","color": "white"},\
{"image": "/static/img/photos/md/img_2.jpg","color": "white"},\
{"image": "/static/img/photos/md/img_3.jpg","color": "black"}\
]'
return data
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
我做了一些研究,发现了Blueprints框架和Flask-Admin,这两个看起来可以一起使用。有没有人有其他的建议,可能会更高效或者更容易设置?
1 个回答
1
蓝图让你可以把功能分成独立的小模块。
如果你觉得你的服务会很小,那就没必要使用蓝图——你可以像在你的例子中那样,直接把路由添加到Flask应用里。
不过,如果你的应用会变得更大,使用蓝图把它拆分成更小的部分会更好。在你的例子中,“work”可以是第一个蓝图,“views”可以是另一个,等等。
Flask-Admin让你可以像Django的管理界面那样,建立一个管理界面。你怎么组织应用的其他部分都没关系——只要添加Flask-Admin,它就能正常工作。