「Flask笔记」 蓝图

栏目: Python · 发布时间: 6年前

内容简介:蓝图可以用来将项目分块,使项目结构更清晰,方便项目管理主如果希望蓝图下所有域名有个前缀,入

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 都可以成功访问,实现子域名。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

失业的程序员

失业的程序员

沈逸 / 2014-5-1 / 39.00元

这是一个程序员从失业到自行创业的奋斗历程,虽然囧事连连、过程曲折,却充满了趣味。本书以作者的真实创业经历为主线,文字幽默诙谐,情节生动真实,包括了招聘、团队管理和用户公关,以及技术架构设计、核心代码编写、商务谈判、项目运作等场景经验。 从初期的创业伙伴、领路人,到商业竞争对手,各种复杂的关系在各个关键时刻却都发生了意想不到的逆转。在历经千辛万苦,眼看快要成功时,主人公却几乎再次失业。 ......一起来看看 《失业的程序员》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

MD5 加密
MD5 加密

MD5 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试