Python 带有 POST 的烧瓶示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22947905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask example with POST
提问by bulkmoustache
Suppose the following route which accesses an xml file to replace the text of a specific tag with a given xpath (?key=):
假设以下路由访问 xml 文件以使用给定的 xpath (?key=) 替换特定标记的文本:
@app.route('/resource', methods = ['POST'])
def update_text():
# CODE
Then, I would use cURL like this:
然后,我会像这样使用 cURL:
curl -X POST http://ip:5000/resource?key=listOfUsers/user1 -d "John"
The xpath expreesion listOfUsers/user1
should access the tag <user1>
to change its current text to "John".
xpath 表达式listOfUsers/user1
应该访问标记<user1>
以将其当前文本更改为“John”。
I have no idea on how to achieve this because I'm just starting to learn Flask and REST and I can't find any good example for this specific case. Also, I'd like to use lxml to manipulate the xml file since I already know it.
我不知道如何实现这一点,因为我刚刚开始学习 Flask 和 REST,我找不到任何关于这个特定案例的好例子。另外,我想使用 lxml 来操作 xml 文件,因为我已经知道了。
Could somebody help and provide an example to guide me?
有人可以帮助并提供一个示例来指导我吗?
回答by s16h
Before actually answering your question:
在实际回答您的问题之前:
Parameters in a URL (e.g. key=listOfUsers/user1
) are GET
parameters and you shouldn't be using them for POST
requests. A quick explanation of the difference between GET and POST can be found here.
URLkey=listOfUsers/user1
中的GET
参数(例如)是参数,您不应该将它们用于POST
请求。可以在此处找到对 GET 和 POST 之间差异的快速说明。
In your case, to make use of REST principles, you should probably have:
在您的情况下,要利用 REST 原则,您可能应该拥有:
http://ip:5000/users
http://ip:5000/users/<user_id>
Then, on each URL, you can define the behaviour of different HTTP methods (GET
, POST
, PUT
, DELETE
). For example, on /users/<user_id>
, you want the following:
然后,在每个 URL 上,您可以定义不同 HTTP 方法(GET
、POST
、PUT
、DELETE
)的行为。例如,在 上/users/<user_id>
,您需要以下内容:
GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id>
So, in your example, you want do a POST
to /users/user_1
with the POST data being "John"
. Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.
所以,在你的榜样,你想要做一个POST
对/users/user_1
与POST数据是"John"
。然后应该对用户隐藏 XPath 表达式或您想要访问数据的任何其他方式,而不是与 URL 紧密耦合。这样,如果您决定更改存储和访问数据的方式,而不是更改所有 URL,您只需更改服务器端的代码。
Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:
现在,您的问题的答案:以下是如何实现我上面提到的基本半伪代码:
from flask import Flask
from flask import request
app = 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
# changes
data = request.form # a multidict containing POST data
.
.
.
if request.method == 'DELETE':
"""delete user with ID <user_id>"""
.
.
.
else:
# POST Error 405 Method Not Allowed
.
.
.
There are a lot of other things to consider like the POST
request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.
还有很多其他事情需要考虑,比如POST
请求内容类型,但我认为到目前为止我所说的应该是一个合理的起点。我知道我没有直接回答您所问的确切问题,但我希望这对您有所帮助。稍后我也会进行一些编辑/添加。
Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.
谢谢,我希望这会有所帮助。如果我做错了什么,请告诉我。
回答by Shahzaib Ali
Here is the example in which you can easily find the way to use Post,GET method and use the same way to add other curd operations as well..
这是一个示例,您可以在其中轻松找到使用 Post,GET 方法的方法,并使用相同的方法添加其他 Curd 操作。
#libraries to include
import os
from flask import request, jsonify
from app import app, mongo
import logger
ROOT_PATH = os.environ.get('ROOT_PATH')<br>
@app.route('/get/questions/', methods=['GET', 'POST','DELETE', 'PATCH'])
def question():
# request.args is to get urls arguments
if request.method == 'GET':
start = request.args.get('start', default=0, type=int)
limit_url = request.args.get('limit', default=20, type=int)
questions = mongo.db.questions.find().limit(limit_url).skip(start);
data = [doc for doc in questions]
return jsonify(isError= False,
message= "Success",
statusCode= 200,
data= data), 200
# request.form to get form parameter
if request.method == 'POST':
average_time = request.form.get('average_time')
choices = request.form.get('choices')
created_by = request.form.get('created_by')
difficulty_level = request.form.get('difficulty_level')
question = request.form.get('question')
topics = request.form.get('topics')
##Do something like insert in DB or Render somewhere etc. it's up to you....... :)