Flask中从POST请求JSON数据提取参数并赋值变量出错问题求助
Hey there! I see exactly where the problem is here. You're sending a JSON payload with your POST request, but trying to fetch the data using request.values.get()—that's why you're getting incorrect or empty values. Let me break this down and fix it for you.
Why Your Current Code Isn't Working
request.values in Flask combines data from URL query parameters and form-encoded request bodies (like application/x-www-form-urlencoded). It doesn't parse JSON payloads, which is what your requests.post(url, json={...}) call is sending. So those get() calls are probably returning None or garbage data because they can't access the JSON data hiding in the request body.
Corrected Flask Route Code
Here's how you should retrieve the JSON data properly using request.get_json():
from flask import Flask, request app = Flask(__name__) @app.route('/predict_api', methods=['POST']) # Important: Your request targets /predict_api, not /predict! def predict(): # Parse the JSON request body into a Python dictionary request_data = request.get_json() # Retrieve values from the parsed dictionary city = request_data.get('City') Country = request_data.get('Country') Target_PtoD = request_data.get('Target_PtoD') start = request_data.get('Start Date') end = request_data.get('End Date') # Optional: Add error handling for missing fields if not all([city, Country, Target_PtoD, start, end]): return "Missing required fields in request", 400 # Your existing logic here (the code that worked with manual assignments) print(f"Received valid data: {city}, {Country}, {Target_PtoD}, {start}, {end}") return "Data received successfully", 200 if __name__ == '__main__': app.run(debug=True)
Key Details to Note:
- Route Path Match: Your
requests.postis targeting/predict_api, but your original route was/predict—make sure these paths align! That's a common easy-to-miss mistake. - JSON Parsing:
request.get_json()automatically converts the JSON payload into a Python dict, as long as the request has the correctContent-Type: application/jsonheader (whichrequests.post(json={...})sets automatically for you, so no extra work needed there). - Safe Value Retrieval: Using
.get()on the dictionary lets you handle missing fields gracefully (it returnsNoneinstead of throwing aKeyError). You can even add default values if needed, likerequest_data.get('City', 'Unknown City').
Testing with Your Existing request.py
Your request.py code is totally fine—no changes needed there, since it's correctly sending JSON data:
import requests url = 'http://localhost:5000/predict_api' r = requests.post(url,json={'City':'Berlin', 'Country':'DE', 'Target_PtoD':36,'Start Date':"1/8/2021",'End Date':"14/8/2021"}) print(r.text) # Should print "Data received successfully" if everything works
Run your Flask app first, then execute request.py—you'll see the correct values printed in the Flask console, and no more incorrect data storage issues.
内容的提问来源于stack exchange,提问作者Datalearner

