美文网首页
Flask获取参数

Flask获取参数

作者: jinjin1009 | 来源:发表于2022-03-01 14:22 被阅读0次

    一、参数在url中
    1、HTTP请求

    POST /test?params=test HTTP/1.1
    Host: 127.0.0.1:5000
    cache-control: no-cache
    

    2、CURL请求

    curl -X POST 
      'http://127.0.0.1:5000/test?params=test' 
      -H 'cache-control: no-cache'
    

    3、python代码

    request.values.get('params')
    request.args.get('params')
    

    二、参数在header中
    1、HTTP请求

    POST /test HTTP/1.1
    Host: 127.0.0.1:5000
    token: this is a token
    cache-control: no-cache
    

    2、CURL请求

    curl -X POST 
      http://127.0.0.1:5000/test 
      -H 'cache-control: no-cache' 
      -H 'token: this is a token'
    

    3、python代码

    request.headers.get('token')
    

    三、body下的form-data
    1、HTTP请求

    POST /test HTTP/1.1
    Host: 127.0.0.1:5000
    cache-control: no-cache
    Content-Type: multipart/form-data; 
    Content-Disposition: form-data; name="key"
    value
    Content-Disposition: form-data; name="file"; filename="C:Usersx1cDesktop3.jpg
    

    2、CURL请求

    curl -X POST 
      http://127.0.0.1:5000/test 
      -H 'cache-control: no-cache' 
      -H 'content-type: multipart/form-data;'
      -F key=value 
      -F 'file=@C:Usersx1cDesktop3.jpg'
    

    3、python代码

    request.form.get('key') 或者 request.form['key']
    request.files
    # 结果
    value
    ImmutableMultiDict([('file', <FileStorage: '3.jpg' ('image/jpeg')>)])
    

    文件类型

    image.png
    jmeter_report = request.files['file']
    dst = os.path.join(os.path.dirname(__file__), jmeter_report.name)
    jmeter_report.save(dst)
    with open(dst, 'r') as file:
            #如果是json类型的文件可以这样
            file_all = json.load(file)
            #非json类型的文件就按照普通文件处理
            for line in file:
                line=line.strip()
    request_parms = {}
    request_parms['sampleCount'] = file_all.get('Total', {}).get('sampleCount', '')
    

    四、body下的json
    1、HTTP请求

    POST /test HTTP/1.1
    Host: 127.0.0.1:5000
    Content-Type: application/json
    cache-control: no-cache
    {"key":"this is a json"}
    

    2、CURL请求

    curl -X POST 
      http://127.0.0.1:5000/test 
      -H 'Content-Type: application/json' 
      -H 'cache-control: no-cache' 
      -d '{"key":"this is a json"}'
    

    3、python代码

    request.json
    # 结果
    {'key': 'this is a json'}
    

    五、获取cookie
    1、postman设置

    image.png
    2、python代码
    request.cookies
    # 结果
    ImmutableMultiDict([('Cookie', 'this is a cookie')])
    

    相关文章

      网友评论

          本文标题:Flask获取参数

          本文链接:https://www.haomeiwen.com/subject/khralrtx.html