内容简介:蓝图可以用来将项目分块,使项目结构更清晰,方便项目管理主如果希望蓝图下所有域名有个前缀,入
flask -- 蓝图
使用蓝图
蓝图可以用来将项目分块,使项目结构更清晰,方便项目管理
#test/blue.py from <a href="https://www.miaoroom.com/tag/flask" data-toggle="tooltip" title="查看更多关于 flask 的文章" target="_blank">flask</a> import Blueprint test = Blueprint('test',__name__) @test.route('/test/') def hello_word(): return 'hello__world'
主 app
文件注册蓝图
from <a href="https://www.miaoroom.com/tag/flask" data-toggle="tooltip" title="查看更多关于 flask 的文章" target="_blank">flask</a> import Flask from test.blue import test app = Flask(__name__) app.register_blueprint(test) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run()
如果希望蓝图下所有域名有个前缀,入 /user/test/
可以指定 url_prefix
参数
test = Blueprint('test',__name__,url_prefix='/user') #注意url_prefix后面没有 / 如果这里加了 / , 那么再注册url的时候前面不要加。即 @app.route('test/')否则路径会出现两个 /
蓝图使用模板
普通使用方法和 app
下使用的方法一样
@test.route('/test/') def hello_word(): return render_template('test.html')
还可以给蓝图指定模板文件的路径,可以是相对路径或者绝对路径
test = Blueprint('test',__name__,url_prefix='/user',template_folder='blup_template')
这两种方法会优先从 template
模板中寻找
蓝图中使用静态文件
如果使用url_for('static')来加载,那么就只会在 app
制定的静态文件夹下查找
如果指定蓝图的名字, test.static
,那么就就再蓝图指定的 static_folder
下查找静态文件
test = Blueprint('test',__name__,url_prefix='/user',static_folder='test_static')
蓝图下 url_for
反转url的注意事项
from flask import Flask,url_for from sql.blue import test app = Flask(__name__) app.register_blueprint(test) @app.route('/') def hello_world(): print(url_for('test.hello_word')) return 'Hello World!' if __name__ == '__main__': app.run()
要在反转url的函数名前添加蓝图名称
同理再模板文件中反转url是一致的
子域名的实现
#app.py from flask import Flask,url_for from blue.cms import cms app = Flask(__name__) app.config['SERVER_NAME'] = 'test.com:5000' #设置了这个就不能通过127.0.0.1:5000来访问flask服务器了 app.register_blueprint(cms) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run()
from flask import Blueprint cms = Blueprint('cms',__name__,subdomain='cms') @cms.route('/') def index(): return 'cms index'
这样运行后还不能访问,因为 flask
不支持 ip地址
的子域名,需要修改 hosts
文件,我这里把 127.0.0.1
映射到 test.com
, cms.test.com
这样 cms.test.com
, test.com
都可以成功访问,实现子域名。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- flask蓝图构建小项目
- 5. 使用Flask蓝图(blueprint)
- flask使用蓝图规划大型项目
- React 16.x 蓝图[双语版]
- 简单解决大型 Flask 蓝图的路由划分
- [Flask] Flask 基于子域名的蓝图管理
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Building Social Web Applications
Gavin Bell / O'Reilly Media / 2009-10-1 / USD 34.99
Building a social web application that attracts and retains regular visitors, and gets them to interact, isn't easy to do. This book walks you through the tough questions you'll face if you're to crea......一起来看看 《Building Social Web Applications》 这本书的介绍吧!