即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

Flask中怎么样简便从Request中提取请求的参数值

编程语言 blueheart20 11℃ 0评论

引言: Flask是Python非常著名的微服务Web框架,但是其并未提供简便的从Request中提取参数的方式,本文将介绍一种简便的方式。

1.  Flask-Request-Params

   来自第三方的Flask插件,方便从Request中提取相应的参数值。

2.  安装步骤

   首先确认系统中已经按照了pip, 如果您还不知道什么pip的话,还请直接问问度娘即可。

   >> pip install flask-request-params  

[root@xxxx]# pip install flask-request-params
Collecting flask-request-params
  Downloading http://mirrors.aliyun.com/pypi/packages/33/14/f41ab27df8d0c59ddfe5063a5bdfcb687174e7573eac62ded2f758b7447f/Flask-request-params-0.3.0.tar.gz
Building wheels for collected packages: flask-request-params
  Running setup.py bdist_wheel for flask-request-params ... done
  Stored in directory: /root/.cache/pip/wheels/f6/31/ef/c20696a93be9b3472ef70a5774cac5cfe3959dc7623f4f6a04
Successfully built flask-request-params
Installing collected packages: flask-request-params
Successfully installed flask-request-params-0.3.0

 检查一下pip是否安装成功:

 >> pip show flask-request-params

[root@xxxx]# pip show flask-request-params
Name: Flask-request-params
Version: 0.3.0
Summary: Flask-request-params provides Rails-like interface to HTTP Request Parameters for Flask.
Home-page: https://github.com/bluele/flask-request-params
Author: bluele
Author-email: jksmphone@gmail.com
License: MIT
Location: /opt/python36env/lib/python3.6/site-packages
Requires: 

3.  如何使用?

  客户端代码:

$ curl -X POST http://localhost:5000/echo/user -d 'user[name]=john&user[password]=pass'
{
  "path": "user",
  "user": {
    "name": "john",
    "password": "pass"
  }
}

# support array type
$ curl -X POST http://localhost:5000/echo/lang -d 'languages[]=python&languages[]=golang'
{
  "path": "lang",
  "languages": [
    "python",
    "golang"
  ]
}

# support strong_parameters
$ curl -X POST http://localhost:5000/user -d 'user[name]=bluele&user[password]=password'
{
  "name": "bluele",
  "password": "password"
}

服务端代码:

from flask import Flask, request, render_template, jsonify
from flask_request_params import bind_request_params


app = Flask(__name__)
app.secret_key = 'secret'
# bind rails like params to request.params
app.before_request(bind_request_params)

# just return request.params
@app.route('/echo/', methods=['GET', 'POST'])
def echo(path):
    return jsonify(request.params)

@app.route('/user', methods=['POST'])
def create_user():
    user = request.params.require('user').permit('name', 'password')
    # do something
    return jsonify(user)

# serve at localhost:5000
app.run(debug=True)

核心的代码方法是:  request.params.require(‘xx”).permit(),以及, request.params方法

 url地址中的参数,以参数的形式传递进入处理函数体之内。

4.  如何获取GET请求中的params?

from flask import request

@app.route('/data')
def data():
    # here we want to get the value of user (i.e. ?user=some-value)
    user = request.args.get('user')
    param_str = request.query_string

5.  总结

  这里列举了三种方式方法来获取Http Request中的参数处理过程,综合来说,还是非常简单易用的。

转载请注明:CodingBlog » Flask中怎么样简便从Request中提取请求的参数值

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情