You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask中从POST请求JSON数据提取参数并赋值变量出错问题求助

Fixing Flask POST JSON Data Retrieval Issue

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:

  1. Route Path Match: Your requests.post is targeting /predict_api, but your original route was /predict—make sure these paths align! That's a common easy-to-miss mistake.
  2. JSON Parsing: request.get_json() automatically converts the JSON payload into a Python dict, as long as the request has the correct Content-Type: application/json header (which requests.post(json={...}) sets automatically for you, so no extra work needed there).
  3. Safe Value Retrieval: Using .get() on the dictionary lets you handle missing fields gracefully (it returns None instead of throwing a KeyError). You can even add default values if needed, like request_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 04:02:46