1.请求
固定参数传值
# http://127.0.0.1:5000/login/11
# <>里面的是形参
# 传参路径的解析是是有的python转换器实现的
# 转换器有6种:整形、字符、浮点型、any、path、UUID
# 默认使用字符型兼容数值型
# 使用<数据类型:参数名>
# 默认值(字符型)可以省略数据类型
@app.route("/login/<User>")
def login(User):
print(User)
return User
2.自定义转换器
1.定义一个转换器类,继承自BaseConverter
2.把自定义转换器添加到转换器
# 自定义转换器类
class RegexMobileConverter(BaseConverter):
re = r'1[3-9]\d{9}'
# 将转换器类添加到转换器
app.url_map.converters['mobile'] = RegexMobileConverter
@app.route("/user/login/<mobile:phone>")
def mobilelogin(phone):
print(phone)
return phone
3.其他参数
1.args
@app.route('/args/')
def args():
# name = request.args['name']
name = request.args.get('name')
print(name)
return name
2.form
@app.route('/formdata',methods = ['POST'])
def formdata():
name = request.form.get('name')
print(name)
return name
3.files
@app.route('/image',methods = ['POST'])
def image():
image = request.files.get('image')
# with open('666.jpg','wb') as f:
# f.write(image.read())
# print(image)
image.save('./66.jpg')
return image
4.method url header
def others():
print(request.method)
print("*" *15)
print(request.url)
print("*" * 15)
print(request.headers)
return 'success'
结果:
GET
***************
http://127.0.0.1:5000/others/
***************
Host: 127.0.0.1:5000
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Sec-Ch-Ua: "Chromium";v="104", " Not A;Brand";v="99", "Google Chrome";v="104"
Sec-Ch-Ua-Mobile: ?0
Sec-Ch-Ua-Platform: "Windows"
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
4.响应
1.返回模板
from flask import Flask, request, render_template, redirect
@app.route('/')
def getIndex():
name = '123'
pwd = '456'
#返回模板
return render_template('index.html',name = name, pwd = pwd)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>index</h1>
<h2>{{name}}</h2>
<h2>{{pwd}}</h2>
</body>
</html>
2.重定向
from flask import Flask, request, render_template, redirect
@app.route('/')
def getIndex():
name = '123'
pwd = '456'
#返回模板
return render_template('index.html',name = name, pwd = pwd)
3.返回JSON
from flask import Flask, request, render_template, redirect, jsonify
@app.route('/jsondata')
def jsondata():
a = {
'name':'alisy',
'age':20
}
return jsonify(a)
import json
@app.route('/jsondata')
def jsondata():
a = {
'name':'alisy',
'age':20
}
# response返回的是json转换成字符串
jsondatastr = json.dumps(a)
return jsondatastr
# response返回的是json
# return jsonify(a)
4.返回元祖
@app.route('/yz')
def yz():
return ('返回元祖','6666',{'Server':'789'})