flask_之参数传递
参数篇
request接收数据

request对象
method:当前请求方法(POST,GET等)
url:当前链接地址
path:当前链接的路径
environ:潜在的WSGI环境
headers:传入的请求头作为字典类对象
data:包含传入的请求数据作为
args:请求链接中的参数(GET参数),解析后
form:form提交中的参数,解析后
values:args和forms的集合
json:json格式的body数据,解析后
cookies:cookie读取

#1 生成response对象 response = make_response(render_template(index.html)) 方法 status:响应状态 headers:响应头,设置http字段 set_coockie:设置一个cookie
1.get请求
request.args.get("key") 获取get请求参数
2.post请求
request.form.get("key", type=str, default=None) 获取表单数据
request.values.get("key") 获取所有参数
# 参数解析对象生成
parser = reqparse.RequestParser()
args = parser.parse_args()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | parser.add_argument( "username" , type = str , required = True ) parser.add_argument( "password" , required = True ) parser.add_argument( "cpuCount" , type = int , required = True ) parser.add_argument( "memorySize" , type = int , required = True ) parser.add_argument( "diskSize" , type = int , required = True ) args = parser.parse_args() print 'flask_restful%s' % args # {'username': 'zk', 'diskSize': 1000, 'cpuCount': 2, 'password': u'123456789', 'memorySize': 512} inf_json = request.json print 'json%s' % inf_json # None inf_get_json = request.get_json print 'get_json%s' % inf_get_json # <bound method Request.get_json of <Request 'http://127.0.0.1:5000/login' [POST]>> inf_valus = request.values print 'valus%s' % inf_valus # valusCombinedMultiDict([ImmutableMultiDict([]), ImmutableMultiDict([('username', u'zk'), ('memorySize', u'512'), ('password', u'123456789'), ('cpuCount', u'2'), ('diskSize', u'1000')])]) inf_form = request.form print 'form%s' % inf_form # formImmutableMultiDict([('username', u'zk'), ('memorySize', u'512'), ('password', u'123456789'), ('cpuCount', u'2'), ('diskSize', u'1000')]) inf_get_data = request.get_data print 'get_data%s' % inf_get_data # get_data<bound method Request.get_data of <Request 'http://127.0.0.1:5000/login' [POST]>> |
1 2 3 4 | username = request.form.get( "username" ) password = request.form.get( "password" , type = str , default = None ) cpuCount = request.form.get( "cpuCount" , type = int , default = None ) memorySize = request.form.get( "memorySize" , type = int , default = None ) |
1 2 3 4 5 6 7 8 9 10 11 12 13 | @app .route( '/login' ,methods = [ "GET" , "POST" ]) def login(): if request.method = = "POST" : # 以POST方式传参数,通过form取值 # 如果Key之不存在,报错KeyError,返回400的页面 username = request.form[ 'username' ] password = request.form[ 'password' ] print username,password else : # 以GET方式传参数,通过args取值 username = request.args[ 'username' ] print username return render_template( 'login.html' , req_method = request.method) |
文件上传
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | from werkzeug.utils import secure_filename @app .route( '/uploads' , methods = [ 'GET' , 'POST' ]) def uploads(): if request.method = = "POST" : fe = request.files[ 'files' ] # basepath = os.path.dirname(os.path.abspath(__file__)) basepath = os.path.abspath(os.path.dirname(__file__)) upload_path = os.path.join(basepath, 'static' , 'upload' ) # f.filename可以拿到文件名,但是是客户端定义的名,不要相信这个名称,用secure_filename包装一下 fe.save(upload_path + '/' + secure_filename(fe.filename)) # 这里的url_for 和jinja的前端用法不一样,可以忽略.的引用 # url_for重定向 return redirect(url_for( 'uploads' )) return render_template( 'upload.html' ) |
cookie设置
1 2 3 4 5 | @app .route( '/index' ) def index(): response = make_response(render_template( 'index.html' ,title = 'Index' )) reqparse.set_cookie( 'username' , '') return response |
自定义错误页面
1 2 3 4 | from flask import abort @app .errorhandler( 404 ) def page_not_not_found(error): return render_template( '404.html' ), 404 |
验证格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | import jsonschema #定义格式要求 #https://jsonschema.net/#/editor json_layout = { "$schema" : "http://json-schema.org/draft-04/schema#" , "type" : "object" , "properties" : { "username" : { "type" : "string" }, "password" : { "type" : "string" }, "cpuCount" : { "type" : "integer" }, "memorySize" : { "type" : "integer" }, "diskSize" : { "type" : "integer" } }, "required" : [ "username" , "password" , "cpuCount" , "memorySize" , "diskSize" ] } def login(): if request.method = = "POST" : # 以POST方式传参数,通过form取值 # 如果Key之不存在,报错KeyError,返回400的页面 parser.add_argument( "username" , required = True ) parser.add_argument( "password" , required = True ) parser.add_argument( "cpuCount" , type = int , required = True ) parser.add_argument( "memorySize" , type = int , required = True ) parser.add_argument( "diskSize" , type = int , required = True ) args = parser.parse_args() # 获取到参数后,传入,验证 jsonschema.validate(args, json_layout) return u 'login返回' 格式正常无返回值( None ) 格式错误报错ValidationError |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?