通过Blueprint进行模块化的Flask应用开发[转]

来源:互联网 发布:淘宝保证金提现 编辑:程序博客网 时间:2024/05/05 08:05

转自 http://note.costony.com/article/modular-applications-with-blueprints-in-flask

Flask使用Blueprint让应用实现模块化,在Flask中,Blueprint具有如下属性:

  • 一个应用可以具有多个Blueprint
  • 可以将一个Blueprint注册到任何一个未使用的URL下比如 “/”、“/sample”或者子域名
  • 在一个应用中,一个模块可以注册多次
  • Blueprint可以单独具有自己的模板、静态文件或者其它的通用操作方法,它并不是必须要实现应用的视图和函数的
  • 在一个应用初始化时,就应该要注册需要使用的Blueprint

但是一个Blueprint并不是一个完整的应用,它不能独立于应用运行,而必须要注册到某一个应用中。

Blueprint 的概念

简单来说,Blueprint 是一个存储操作方法的容器,这些操作在这个Blueprint 被注册到一个应用之后就可以被调用与招待,Flask 可以通过Blueprint来组织URL以及处理请求。

一个简单的 Blueprint 示例:sample.py

#!/usr/bin/env python # encoding: utf-8 
from flask import Blueprint 
sample = Blueprint('sample',__name__) 
@sample.route('/') 
@sample.route('/hello') 
def index(): 
return "This page is a blueprint page"

在 app 应用中注册我们的Blueprint:app.py

#!/usr/bin/env python # encoding: utf-8 
from flask import Flask 
from sample import sample 
app = Flask(__name__) 
app.register_blueprint(sample) 
if __name__ == "__main__": 
app.run()

上面的代码在一个名为 app 的应用中注册一个名为 sample 的Blueprint,现在我们运行这个应用,则可以通过我们在Blueprint中定义的方法来访问它并获得 This page is a blueprint page的返回结果:

$python app.py

我们需要访问的网址是:http://127.0.0.1:5000 或者 http://127.0.0.1:5000/hello 都可以得到同样的结果。

但是如果你希望所有的 Blueprint 的请求都基于某一个固定的URL之后,刚我们可以在注册的时候指定其根路径的URL,比如我们想使用 http://127.0.0.1:5000/sample 这个地址来访问 sample 这个 Blueprint,刚可以使用下面这样的注册方法:

app.register_blueprint(sample,url_prefix='/sample')
0 0
原创粉丝点击