700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Flask实现REST API之接收POST和GET请求

Flask实现REST API之接收POST和GET请求

时间:2018-11-04 11:59:38

相关推荐

Flask实现REST API之接收POST和GET请求

1、POST和GET的区别与选择

GETandPOSTare two different types of HTTP requests.

According toWikipedia:

GETrequests a representation of the specified resource. Note that GET should not be used for operations that cause side-effects, such as using it for taking actions in web applications. One reason for this is that GET may be used arbitrarily by robots or crawlers, which should not need to consider the side effects that a request should cause.

and

POSTsubmits data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource or the updates of existing resources or both.

So essentiallyGETis used to retrieve remote data, andPOSTis used to insert/update remote data.

2、伪代码框架:

from flask import Flaskfrom flask import requestapp = Flask(__name__)@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])def user(user_id):if request.method == 'GET':"""return the information for <user_id>"""...if request.method == 'POST':"""modify/update the information for <user_id>"""# you can use <user_id>, which is a str but could# changed to be int or whatever you want, along# with your lxml knowledge to make the required# changesdata = request.form # a multidict containing POST data...if request.method == 'DELETE':"""delete user with ID <user_id>"""...else:# POST Error 405 Method Not Allowed...

3、如何接收各种类型参数?

request.dataContains the incoming request data as string in case it came with a mimetype Flask does not handle.

request.args: the key/value pairs in the URL query stringrequest.form: the key/value pairs in the body, from a HTML post form, or JavaScript request that isn't JSON encodedrequest.files: the files in the body, which Flask keeps separate fromform. HTML forms must useenctype=multipart/form-dataor files will not be uploaded.request.values: combinedargsandform, preferringargsif keys overlaprequest.json: parsed JSON data. The request must have theapplication/jsoncontent type, or userequest.get_json(force=True)to ignore the content type.

All of these areMultiDictinstances (except forjson). You can access values using:

request.form['name']: use indexing if you know the key existsrequest.form.get('name'): usegetif the key might not existrequest.form.getlist('name'): usegetlistif the key is sent multiple times and you want a list of values.getonly returns the first value.

参考链接:

python - Flask example with POST - Stack Overflow/questions/22947905/flask-example-with-postpython - Get the data received in a Flask request - Stack Overflow/questions/10434599/get-the-data-received-in-a-flask-request

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。