在实际回答您的问题之前:
URL 中的参数(例如key=listOfUsers/user1)是GET 参数,您不应该将它们用于POST 请求。可以在here 找到有关 GET 和 POST 之间区别的快速说明。
在您的情况下,要利用 REST 原则,您可能应该:
http://ip:5000/users
http://ip:5000/users/<user_id>
然后,在每个 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>
因此,在您的示例中,您希望使用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 请求内容类型,但我认为到目前为止我所说的应该是一个合理的起点。我知道我没有直接回答您提出的确切问题,但我希望这对您有所帮助。稍后我也会进行一些编辑/添加。
谢谢,我希望这会有所帮助。如果我做错了什么,请告诉我。