如何用Python3的requests库发送含图片与文本的MultipartForm请求?
To replicate your Node.js multipart POST request in Python using the requests library, here's a straightforward, equivalent implementation:
Step 1: Import Required Libraries
Start by importing the necessary modules for HTTP requests and JSON serialization:
import requests import json
Step 2: Define Variables and Helper Logic
Recreate your original variables and the RequestData function (adjust the function body to match your Node.js logic):
file_path = "xxx.jpeg" text = "xxx" api_url = "http://xxx" def request_data(text_input): # Replace this with your actual RequestData implementation from Node.js return {"text_content": text_input}
Step 3: Prepare Multipart Form Data
Use a list of tuples to construct your multipart parts—this preserves the order of parts (matching your Node.js code) and supports custom content types:
# Add your authorization header (replace with real credentials/token) headers = { "Authorization": "YourAuthTokenOrCredentialsHere" } # Safely handle the image file with a `with` block to avoid resource leaks with open(file_path, "rb") as image_file: multipart_parts = [ # Image part: matches Node.js's Content-Disposition and Content-Type ("file", (file_path, image_file, "image/jpeg")), # JSON payload part: custom content type, no filename needed ("payload", (None, json.dumps(request_data(text)), "application/specified-content-type-xxx")) ] # Send the POST request response = requests.post(api_url, files=multipart_parts, headers=headers)
Step 4: Process the Response
Handle the API response based on your needs:
# Check request success print(f"Status Code: {response.status_code}") # Parse JSON response if applicable try: response_json = response.json() print("Response Data:", response_json) except ValueError: print("Non-JSON Response:", response.text)
Key Details to Note:
- Part Order: Using a list ensures the image is sent first, followed by the JSON payload—this matches your Node.js code and may be required by the API.
- Custom Content Type: The JSON part uses
Noneas the filename (since it's not a file) and explicitly sets your custom content type. - File Safety: The
withstatement automatically closes the image file after the request completes. - Authorization: Don't forget to replace the placeholder in the
headersdictionary with your actual authorization token or credentials.
If your original Node.js code specified a different name for the JSON payload in Content-Disposition (it wasn't included in your snippet), replace "payload" in the second tuple with that name.
内容的提问来源于stack exchange,提问作者Maiko Ohkawa

