每次请求之间都是独立的
- URL路径参数(动态路由)
@app.route('/users/<user_id>')
# 此处的<>就是一个转换器,默认为字符串类型,将该位置的数据以字符串格式进行匹配、并以字符串为数据类型类型、 user_id为参数名传入视图。
def user_info(user_id):
print(type(user_id))
return 'hello user {}'.format(user_id)
- 通过阅读源码可以发现,Flask还提供其它类型的转换器:
- 同时通过阅读源码我还学习到了一个新的知识:re.compole()可以写一个正则表达式,返回一个正则表达式的对象,在routing的源码中就使用了这种方式,方便阅读
#: the default converter mapping for the map.
DEFAULT_CONVERTERS = {
"default": UnicodeConverter,
"string": UnicodeConverter,
"any": AnyConverter,
"path": PathConverter,
"int": IntegerConverter,
"float": FloatConverter,
"uuid": UUIDConverter,
}
any转换器:
需要在转换器后添加括号来给出可选值,在写这个变量的值时,如果在可选值范围内,就会执行视图函数的逻辑,否则会报404错误
- 在Flask中想要以指定类型接收参数,可以做如下操作
from flask import Flask
app = Flask(__name__)
# 这里的int:就是表示需要接收的参数user_id应该是int类型
@app.route('/users/<int:user_id>')
# 此处接收到的user_id应该以参数的形式传递给函数,如下
def user_info(user_id):
print(type(user_id))
return 'hello user {}'.format(user_id)
if __name__ == '__main__':
app.run()
如果遇到需要匹配类似手机号数据,那么Flask内置的几种转换器是满足不了需求的,那么就需要我们自定义转换器(3步):
- 1、定义类,继承自基础转换器
- 2、定义一个变量,实现自定义正则
- 3、给默认转换器字典添加自定义的转换器
下面是自定义转换器的实现代码:
- -创建转换器类,保存匹配时的正则表达式
# 创建类,集成自BaseConverter,在类中保存匹配时的正则表达式
class MobileConverter(BaseConverter):
regex = r'1[3-9]\d{9}'
- 将自定义的转换器在Flask应用,将自定义转换器添加到转换器字典中,指定转换器使用时名字为mobile
app.url_map.converters['mobile'] = MobileConverter
- 使用自定义的转换器
@app.route('/user/<mobile:user_id>')
def index(user_id):
return 'hello world{}'.format(user_id)
处理请求
url的请求参数有两种:
- 查询字符串:问号后面、等号传值、与号分隔
- 固定参数
url中固定参数的获取: - 使用转换器(内置6种):正则表达式 ‘/<>’ url中<>为固定参数,必须要传给视图
- ‘hello world {}’.format()
- <> 默认为字符串类型
- 自定义转换器:提取url中固定参数,手机号
class MobileConverter(BaseConverter):
regex = ''
request对象
请求对象request,Flask的请求上下文对象
request的属性
request.data() ----->记录请求的数据,并转换为字符串
request.args.get('参数名') ----->获取请求中的查询参数的值
request.method() ----->获取请求方式
request.form.get() ----->获取请求中的表单数据
request.cookie() ----->获取请求中的cookie信息
request.url() ----->获取请求的URL地址
reuqest.headers: ----->获取请求中的报文头信息
Accept:接收的类型
Accept-Encoding:
Upgrade-Insecure-Request:1 ----->升级不安全请求
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Host: 127.0.0.1:5000
Connection: keep-alive
Accept-Encoding: gzip, deflate, sdch
User-Agent:用户代理(用户是谁)
Accept-Language: zh-CN,zh;q=0.8
image = request.file.get('') ----->上传的文件
image.save('./') ----->提供了save方法, ./路径
response响应
- 返回模板:使用render_template方法渲染模板并返回
from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route('/')
def index():
username = 'lww'
password = 1234567890
return render_template('demo.html', username=username, password=password)
if __name__ == '__main__':
app.run()
- 重定向
@app.route('/')
def index2():
# redirect中写的是想要重定向的网址
return redirect('http://www.baidu.com')
- request获取json数据
关于json:
- json.dumps():把字典转成json字符串,响应信息中Content-type类型是text/html
- json.loads():把json字符串转成字典
- 他们操作的都是变量(变量是存储在内存中的)。
- request.json.get(key) ----->json.get 是拿到json中的键
- request.get_json ----->拿到包
- dump( fp:文件对象 ) 字典不能写文件
- dumps 把字典转成json loads把json转字典
- json.dump()和json.load(),操作的是文件对象(具有read和write方法的对象,存在硬盘中)
- jsonfy是flask封装的扩展包
- jsonify就是将字典转换成json字符串,响应信息中Content-type类型是application/json
from flask import jsonfy
@app.route('/demo3')
def demo3():
json_dict = {
"user_id": 10,
"user_name": "laowang"
}
return jsonify(json_dict) -
- 自定义的状态码作用:实现前后端的数据交互
- 元组:
return 字符串,状态码,响应头信息(字典)
make_response:手动返回响应,可以自定义响应信息,相当于Django中的HttpResponse
@app.route('/demo5')
def index():
response = make_response('make_response11111')
response.headers['username'] = 'PPPPP'
return response
- make_response想要返回页面,不能直接写:make_response(‘hello.html’)必须以下面的方式返回页面
render_template('hello.heml')
Cookie和Session:
- cookie:存储在客户端浏览器中,实现状态保持;本质都是键值对形式的字符串
res = make_response()
res.set_cookie(key,value)
@app.route('/demo6')
def index():
response = make_response('username is not found')
# max_age可以设置有效期(秒)
response.set_cookie('username','password',max_age=3600)
# 读取cookie中的信息
# resp = request.cookie.get('username')
# 删除cookie中的信息
# response.delete_cookie('username')
return response
- session:存储在服务器中,实现状态保持,使用前需要先设置SECRET_KEY
session['key'] = value
from flask import Flask,session
app = Flask(__name__)
class DefaultConfig(object):
SECRET_KEY = '123ASDAFCVZCVAEFSDFSDFSDFSDCXVczxczx'
app.config.from_object(DefaultConfig)
@app.route('/')
def index():
session['username'] = 'password'
return 'set session ok'
if __name__ == '__main__':
app.run()
课外回顾:
- 冻结依赖包
pip freeze > requirement.txt
- 安装依赖包
pip install -r requirement.txt
- http使用80端口 https使用443端口
- 重定向状态码:302(永久重定向) 307(临时重定向)