flask_之参数传递

参数篇

request接收数据

request对象
    method:当前请求方法(POST,GET等)
    url:当前链接地址
    path:当前链接的路径
    environ:潜在的WSGI环境
    headers:传入的请求头作为字典类对象
    data:包含传入的请求数据作为
    args:请求链接中的参数(GET参数),解析后
    form:form提交中的参数,解析后
    values:args和forms的集合
    json:json格式的body数据,解析后
    cookies:cookie读取
request对象
#1 生成response对象
response = make_response(render_template(index.html))  
方法
    status:响应状态
    headers:响应头,设置http字段
    set_coockie:设置一个cookie
response对象

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()

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]>>
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)
@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)

 文件上传

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设置

@app.route('/index')
def index():
    response = make_response(render_template('index.html',title='Index'))
    reqparse.set_cookie('username', '')
    return response

 自定义错误页面

from flask import abort
@app.errorhandler(404)
def page_not_not_found(error):
    return render_template('404.html'), 404

验证格式

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

 

posted @ 2017-07-02 19:39  总要做些什么  阅读(12942)  评论(0编辑  收藏  举报