📜  flask put 请求示例 - Python (1)

📅  最后修改于: 2023-12-03 15:15:05.720000             🧑  作者: Mango

Flask PUT Request Example - Python

In Flask, PUT requests can be used to update existing resources. Here's an example of how to handle a PUT request in Flask using Python.

Prerequisites
  • Python 3
  • Flask
Code Example
from flask import Flask, request, jsonify

app = Flask(__name__)

data = {'name': 'John Doe', 'age': 30}

@app.route('/', methods=['PUT'])
def update_data():
    new_data = request.get_json()
    data.update(new_data)
    return jsonify(data), 200

if __name__ == '__main__':
    app.run(debug=True)

In this example, we first import the necessary packages including Flask and request for handling HTTP requests.

Next, we define our data as a dictionary containing two key-value pairs. This is the resource we'll be updating with our PUT request.

We then define a route for handling PUT requests to '/', which is our root URL.

Inside the route function, we get the request data using request.get_json(). This expects JSON data in the request body, which we'll be sending in our example.

Next, we update our dictionary with the new data using data.update(new_data).

Finally, we return the updated data in JSON format using jsonify(data), along with a 200 status code indicating success.

Testing the Example

To test the example, you can use a tool like cURL or Postman to send a PUT request to the server.

Example cURL command:

curl -X PUT -H "Content-Type: application/json" -d '{"age": 35}' http://localhost:5000/

This sends a PUT request with JSON data {"age": 35} to our root URL http://localhost:5000/.

If everything is working correctly, you should receive a response like:

{
  "name": "John Doe",
  "age": 35
}

This indicates that our data was successfully updated with the new age value.

Conclusion

In conclusion, handling PUT requests in Flask is simple using the request module. With the above example code, you should be able to easily handle PUT requests in your own Flask applications.