flask在其他文件中添加路由

应用文件为:app.py

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

如果不想在这个文件中添加新路由,怎么办?

  • 有个直观的办法, 新建test.py
1 def  add_new_routes(app):
2     @app.route("/test")
3     def test():
4         return 'test'

然后在app.py中添加调用,

1 from test import add_new_routes
2 
3 add_new_routes(app)
  • 前面的办法缩进有点多啊!换个方法,将test.py的代码改为:
1 def hello():
2     return 'hello world'
3 
4 def add_new_routes(app):
5 
6     app.add_url_rule('/hello', view_func=hello)

同理,在Blueprint中,也可以这么干。

哈哈,终于又写了一篇。懒病总是需要克服!

猜你喜欢

转载自www.cnblogs.com/lyg-blog/p/9499227.html