疑问:init.py文件的作用
_init_.py 文件的作用是将文件夹变为一个Python模块,Python 中的每个模块的包中,都有init.py 文件。
Flask框架流程大概梳理
1.导入Flask
from flask import Flask //导入Flask,以便用于创建主app
2.创建Flask主app对象
app = Flask(__name__)
3.使用router绑定 路由 和 执行的视图函数 的关联关系
@app.route('/hello/')
def hello():
return 'hello world'
- 两种启动主app(启动整个项目)的方式
- 使用flask-script三方库中的Manage管理flask对象,并启动。
Manager只有一个参数—— Flask实例
调用manager.run()启动 Manager实例 接收命令行中的命令;manage可以从控制台命令行接收命令,进行动态的项目启动初始化设置:(具体各种命令这里待补充)
from flask_script import Manager
if __name__ == '__main__':
manage = Manager(app)//这里app是前面创建的flask实例
manage.run()
- 使用app.run(host=xxx, port=xxx, debug=True)方式
app.run(host='127.0.0.1', port=8000, debug=True)
对比:
第二种,端口和ip一开始就设置好了。
第一种,可以灵活的在命令行设置端口号和IP,通过Manage类进行获取
路由规则
Django和Flask路由规则简单对比
Django
int参数:path('/uid/<int:id>/',xxxx)
字符串参数:path('/uid/<name>/',xxxx)
字符串参数:path('/uid/<str:name>/',xxxx)
uuid参数:path('/uid/<uuid:uid>',xxxx)
path参数:path('/uid/<path:uid>',xxxx)
正则表达式,django2.0以上: re_path('/uid/(/d)',xxxx)
正则表达式,django2.0以下:url('/uid/uid(?P<id>/d+)',xxxx)
Flask
int参数:route('/uid/<int:id>/')
字符串:route('/uid/<name>/')
字符串:route('/uid/<string:name>/')
uuid: route('/uid/<uuid:uid>')
float:route('/uid/<float:float>/')
path路径:route('/uid/<path:pth>/')
几种不同类型格式的响应
- 响应字符串
return '响应的内容'
- 响应页面
return render_template('index.html')//需要导包Flask
- 响应json数据
return jsonify({'code': 200, 'msg': 'chenggong'})
- 响应中绑定cookie参数
response = make_response(render_template('index.html'), 200)//获取对象
response.set_cookie('token', '23456789', max_age=3000)//设置cookie
response.delete_cookie('token')//删除cookie
return response//返回响应
Flask初学思维导图