Python脚本自动上传反馈至Web服务:无需手动转字典的实现问询
Python Script to Auto-Upload Feedback Files to Django REST API
First, make sure you have the requests library installed—if not, run this command in your terminal:
pip install requests
Here's the complete script that follows your requirements:
import os import requests def upload_feedback(): # Define paths and API endpoint feedback_directory = '/data/feedback' api_endpoint = 'http://35.193.233.100/feedback' # Loop through all items in the feedback directory for file_name in os.listdir(feedback_directory): full_file_path = os.path.join(feedback_directory, file_name) # Skip directories, only process text files if not os.path.isfile(full_file_path): continue try: # Read and parse the content of each feedback file with open(full_file_path, 'r') as file: # Clean up lines: remove whitespace and empty lines cleaned_lines = [line.strip() for line in file if line.strip()] # Validate we have all required fields if len(cleaned_lines) < 4: print(f"Skipping {file_name}: Not enough content (needs title, name, date, feedback)") continue # Auto-generate the feedback dictionary feedback_dict = { 'title': cleaned_lines[0], 'name': cleaned_lines[1], 'date': cleaned_lines[2], 'feedback': '\n'.join(cleaned_lines[3:]) # Handles multi-line feedback } # Send the POST request to the Django API response = requests.post(api_endpoint, json=feedback_dict) # Print results for debugging if response.status_code == 201: print(f"✅ Successfully uploaded {file_name}! Status: {response.status_code}") else: print(f"❌ Failed to upload {file_name}. Status: {response.status_code} | Response: {response.text}") except Exception as error: print(f"⚠️ Error processing {file_name}: {str(error)}") if __name__ == "__main__": upload_feedback()
Breakdown of How It Works:
- File Listing: Uses
os.listdir()to get all items in the target directory, thenos.path.isfile()to ignore any subdirectories. - Auto-Dictionary Creation: Reads each file line by line, maps the first three lines to
title,name, anddate, and joins any remaining lines into thefeedbackfield (supports multi-line feedback text). - API Upload: Uses
requests.post()with thejsonparameter—this automatically converts the dictionary to JSON, so no manual conversion is needed. - Error Handling: Includes checks for incomplete files and general exceptions, plus prints status codes and server responses to help troubleshoot issues.
How to Run:
- Save the script as
feedback_uploader.py - Execute it with:
python feedback_uploader.py
You’ll get clear output for each file showing success or failure. A status code of 201 means the feedback was successfully created on the server.
内容的提问来源于stack exchange,提问作者karim reda
相关产品推荐
相关产品推荐

