「Flask笔记」 蓝图

「Flask笔记」 蓝图

资源介绍参数
资源类别: Python
如遇问题: 联系客服/留言反馈

flask — 蓝图

使用蓝图

蓝图可以用来将项目分块,使项目结构更清晰,方便项目管理

  1. #test/blue.py
  2. from flask import Blueprint
  3. test = Blueprint('test',__name__)
  4. @test.route('/test/')
  5. def hello_word():
  6. return 'hello__world'

app文件注册蓝图

  1. from flask import Flask
  2. from test.blue import test
  3. app = Flask(__name__)
  4. app.register_blueprint(test)
  5. @app.route('/')
  6. def hello_world():
  7. return 'Hello World!'
  8. if __name__ == '__main__':
  9. app.run()

如果希望蓝图下所有域名有个前缀,入/user/test/可以指定url_prefix参数

  1. test = Blueprint('test',__name__,url_prefix='/user')
  2. #注意url_prefix后面没有 / 如果这里加了 / , 那么再注册url的时候前面不要加。即 @app.route('test/')否则路径会出现两个 /

蓝图使用模板

普通使用方法和app下使用的方法一样

  1. @test.route('/test/')
  2. def hello_word():
  3. return render_template('test.html')

还可以给蓝图指定模板文件的路径,可以是相对路径或者绝对路径

  1. test = Blueprint('test',__name__,url_prefix='/user',template_folder='blup_template')

这两种方法会优先从template模板中寻找

蓝图中使用静态文件

如果使用url_for(‘static’)来加载,那么就只会在app制定的静态文件夹下查找
如果指定蓝图的名字,test.static,那么就就再蓝图指定的static_folder下查找静态文件

  1. test = Blueprint('test',__name__,url_prefix='/user',static_folder='test_static')

蓝图下url_for反转url的注意事项

  1. from flask import Flask,url_for
  2. from sql.blue import test
  3. app = Flask(__name__)
  4. app.register_blueprint(test)
  5. @app.route('/')
  6. def hello_world():
  7. print(url_for('test.hello_word'))
  8. return 'Hello World!'
  9. if __name__ == '__main__':
  10. app.run()

要在反转url的函数名前添加蓝图名称
同理再模板文件中反转url是一致的

子域名的实现

  1. #app.py
  2. from flask import Flask,url_for
  3. from blue.cms import cms
  4. app = Flask(__name__)
  5. app.config['SERVER_NAME'] = 'test.com:5000'
  6. #设置了这个就不能通过127.0.0.1:5000来访问flask服务器了
  7. app.register_blueprint(cms)
  8. @app.route('/')
  9. def hello_world():
  10. return 'Hello World!'
  11. if __name__ == '__main__':
  12. app.run()
  1. from flask import Blueprint
  2. cms = Blueprint('cms',__name__,subdomain='cms')
  3. @cms.route('/')
  4. def index():
  5. return 'cms index'

这样运行后还不能访问,因为flask不支持ip地址的子域名,需要修改hosts文件,我这里把127.0.0.1 映射到test.com,cms.test.com这样cms.test.com,test.com都可以成功访问,实现子域名。

声明:本文为原创作品,版权归作者所有。未经许可,不得转载或用于任何商业用途。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
0 条回复 A文章作者 M管理员
欢迎您,新朋友,感谢参与互动!
    暂无讨论,说说你的看法吧