[学习记录]flask初步

先放上官方文档

起步:

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

这就完成了最简单的flask应用

@app.route为路由,当你访问该路径时,flask会启动下方的函数

如果app.run(host='0.0.0.0')意味着监听公网ip

路由中可以添加变量例如

1 @app.route('/user/<username>/<password>')
2 def show_user_profile(username,password):
3     # show the user profile for that user
4     return 'User %s' % username
5 
6 @app.route('/post/<int:post_id>')
7 def show_post(post_id):
8     # show the post with the given id, the id is an integer
9     return 'Post %d' % post_id

如果是字符串则不用添加转换器,转换器支持int,float,path。可以携带多个变量

可以在装饰器中添加http方法

@app.route('/login',methods=['GET,'POST'])

至此已经完成了基本的flask搭建,可以用来向前端返回数据了。

原文地址:https://www.cnblogs.com/trickofjoker/p/11041862.html