1.flask使用插件flask-script
安装 pip3 install flask-script
修改代码
参数说明
-d是否开启调试模式
-r 是否自动重新加载文件
-h 指定主机
-p 指定端口号
-threaded 是否使用多线程
-?,--help 查看帮助
终端执行
python app.py runserver -d -r -h 0.0.0.0 -p 9000
代码结构
static静态资源文件
创建css文件
访问路径http://0.0.0.0:9000/static/css/hello_css.css
templates模板文件
默认两个都可以直接使用
直接使用相对路径
模板渲染
render_template()
其实也是分为两个过程,加载和渲染
可使用 template= Template("<h2>1111</h2>")
template.render()
静态使用,相当于反向解析
url_for('static',filename = 'hello.css')
创建模板文件
修改app.py
访问路径
路由中知识点:
flask中的参数
都是关键字参数
默认标识都是尖括号
name需要和对应的视图函数的参数名字保持一致
参数允许有默认值,如果有默认值,参数可不传,
如果没有必须传
#获取参数(路由中参数和绑定的函数的参数的个数一一对应,关键字参数)
@app.route('/params/<hehe>/')
def params(hehe,oo='11'):
print(hehe)
return '获取参数'
路由变量规则
通过使用通过使用 <converter:variable_name>
命名变量,类型如下:
#匹配路径
@app.route('/path/<path:path>')
def path(path):
print(path)
return '匹配路径'
#匹配UUID路由
@app.route('/get/<uuid:name>/')
def get(name):
print(name)
return '获取UUID'
# 获取UUID
@app.route('/getuuid/')
def getuuid():
return str(uuid.uuid4());
any类似于枚举
#从列出的数据中选择一个
@app.route('/any/<any(a,b,c):an>/')
def any(an):
print(an)
return '枚举'
请求方法,只需要在路由后追加methods方法
可使用
postman
httpie模拟网络请求
反向解析:通过函数找路由
客户端请求服务器flask会自动创建request对象
服务器返回
页面重定向
#页面重定向
@app.route('/redirect/')
def redir():
response = redirect(url_for('hello'))
return response
页面终止访问
#禁止访问
@app.route('/abort/')
def ab():
abort(403)
返回json数据
#返回json数据
@app.route('/json/')
def json_data():
# result = json.jsonify({'name':'value'})#第一种写法
# result = json.jsonify(name='Value',age=18)#第二种写法
# result= json.dumps({'name':'Value'})
# print(type(result))
result = '{"name":"Tom"}'
response = Response(response=result,content_type='application/json')
return response
如果用jsonify 将数据格式化为json格式,同时设置返回类型为application、json
如果用dumps将数据格式化为json格式,没有设置返回的数据类型,默认为text/html
1.为了解决模块拆分引入蓝图
安装蓝图
pip install flask-blueprint
初始化一个蓝图
在views类中
from flask import Blueprint
blue = Blueprint('first_blue',__name__)#初始化蓝图
@blue.route('/')#使用蓝图
def hello_world():
return 'Hello World!'
在manager.py中注册
在views中使用蓝图
什么是cookie
cookie是保存在客户端的,支持过期,不能跨域名,不能跨浏览器,且cookie不支持中文
flask中的cookie,可以支持中文(被转码了)
设置cookie
resp = Response(response='登录成功%s'%username)
resp.set_cookie('user',username)
获取cookie
username= request.cookies.get('user')
删除cookie
resp = redirect(url_for('first_blue.home'))
print(type(resp))#<class 'werkzeug.wrappers.response.Response'>
resp.delete_cookie('user')
session是在存储在服务器内存中,容易丢失,不能够多台电脑操作
设置session
session['user']=username
获取session
username = session.get('user')
manager中配置secret_key,不设置会报错
app.config['SECRET_KEY']='EEEQEQEQDYI23Y933'#为session设置secret_key