Flask新手技术咨询:如何获取请求字段并处理后连同额外值POST至其他URI
Hey there! Let's break this down step by step since you're already off to a good start with grabbing the age field. I'll walk you through defining the age-processing function and sending the POST request to another URI.
First, a quick fix to your current code:
request.get_jsonis a method, so you need to call it with parentheses:request.get_json()- Your route should start with a slash:
@app.route('/link', methods=['GET','POST']) - Adding basic error handling will prevent crashes if the
agefield is missing.
Step 1: Define your age-processing function
Let's create a simple, customizable function that takes the age value and generates your desired extra value. For example, we could calculate the birth year (assuming current year is 2024) or double the age—adjust this logic to fit your needs:
def process_age(age): # Example 1: Calculate birth year birth_year = 2024 - age # Example 2: Double the age (swap this in if needed) # doubled_age = age * 2 return birth_year
Step 2: Send POST request to another URI
To send data to an external endpoint, we'll use the requests library (install it first with pip install requests). We'll build a payload that includes both the original age and our processed extra value, then send it via POST.
Full Working Code
Here's everything put together with robustness improvements:
from flask import Flask, request import requests app = Flask(__name__) # Custom age processing function - tweak this to your use case! def process_age(age): return 2024 - age # Returns birth year as the extra value @app.route('/link', methods=['POST']) # Focus on POST since we're handling incoming data def handle_request(): # Fetch incoming JSON data data = request.get_json() # Validate the request has the 'age' field if not data or 'age' not in data: return "Missing 'age' field in request", 400 original_age = data['age'] # Generate the extra value using our function extra_value = process_age(original_age) # Build the payload to send to the target URI payload = { 'original_age': original_age, 'extra_value': extra_value, # Uncomment below to include other original fields if needed # 'phone_number': data.get('phone_number'), # 'name': data.get('name'), # 'gender': data.get('gender') } # Replace this with your actual target URI target_uri = "https://your-target-endpoint.com/receive-data" try: # Send the POST request to the target response = requests.post(target_uri, json=payload) # Raise an error if the target returns an HTTP error code response.raise_for_status() return f"Data sent successfully! Target response: {response.text}", 200 except requests.exceptions.RequestException as e: # Handle any issues with sending the request return f"Failed to send data: {str(e)}", 500 if __name__ == "__main__": app.run(port=2000, debug=True)
Key Tips:
- Customize
process_age: Swap the birth year logic with whatever calculation you need (e.g., age eligibility, category grouping, etc.). - Include other fields: If you want to forward the full original request data to the target URI, just add those fields to the
payloaddictionary. - Debug mode: With
debug=True, Flask will auto-reload when you edit code—perfect for testing changes quickly.
内容的提问来源于stack exchange,提问作者Mee

