小编典典

带有POST的flask示例

flask

假设以下路由访问xml文件,以给定的xpath(?key =)替换特定标签的文本:

@app.route('/resource', methods = ['POST'])
def update_text():
    # CODE

然后,我将使用cURL这样:

curl -X POST http://ip:5000/resource?key=listOfUsers/user1 -d "John"

xpath扩展listOfUsers/user1应该访问标记<user1>以将其当前文本更改为“ John”。

我不知道如何实现这一目标,因为我才刚刚开始学习Flask和REST,在这种情况下我找不到很好的例子。另外,我想使用lxml来操纵xml文件,因为我已经知道了。

有人可以提供帮助并提供示例指导我吗?


阅读 702

收藏
2020-04-07

共1个答案

小编典典

在实际回答你的问题之前:

URL key=listOfUsers/user1中的GET参数(例如)是参数,你不应将其用于POST请求。关于GET和POST之间的区别的快速说明可以在这里找到。

就你而言,要利用REST原理,你可能应该具有:

http://ip:5000/users
http://ip:5000/users/<user_id>

然后,在每个网址,你可以定义不同的HTTP方法的行为(GET,POST,PUT,DELETE)。例如,在上/users/,你需要以下内容:

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> 

所以,在你的榜样,你想要做一个POST/users/user_1与POST数据是"John"。然后,应该向用户隐藏XPath表达式或你要访问数据的任何其他方式,并且不要与URL紧密耦合。这样,如果你决定更改存储和访问数据的方式,而不是更改所有URL,则只需更改服务器端的代码即可。

现在,你的问题的答案:下面是基本的半伪代码,说明如何实现我上面提到的内容:

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
        .
        .
        .

还有很多其他事情需要考虑,例如POST请求内容类型,但我认为到目前为止我所说的应该是一个合理的起点。我知道我没有直接回答你所问的确切问题,但希望对你有所帮助。我稍后也会进行一些编辑/添加。

2020-04-07