1、POST和GET的区别与选择
GET
andPOST
are 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 essentiallyGET
is used to retrieve remote data, andPOST
is 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.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 from
request.data
Contains the incoming request data as string in case it came with a mimetype Flask does not handle.
form
. HTML forms must useenctype=multipart/form-data
or files will not be uploaded.request.values: combinedargs
andform
, preferringargs
if keys overlaprequest.json: parsed JSON data. The request must have theapplication/json
content 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')
: useget
if the key might not existrequest.form.getlist('name')
: usegetlist
if the key is sent multiple times and you want a list of values.get
only 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