簡體   English   中英

使用 Python 字典處理文本文件並上傳到運行 Web 服務實驗室

[英]Process Text Files with Python Dictionaries and Upload to Running Web Service lab

我想編寫一個 Python 腳本,該腳本將自動上傳反饋,而無需將其轉換為字典。 腳本現在應該遵循以下結構:

  • 列出 /data/feedback 目錄下的 all.txt 文件,其中包含要在公司網站上顯示的實際反饋。 提示:為此使用 os.listdir() 方法,它返回指定路徑中所有文件和目錄的列表。

  • 您現在應該有一個列表,其中包含路徑 /data/feedback 中的所有反饋文件。 遍歷每個文件,並根據這些文本文件的內容,通過分別將標題、名稱、日期和反饋作為內容值的鍵來創建字典。

  • 現在,您需要一個包含鍵及其各自值(來自反饋文件的內容)的字典。 這將通過 Django REST API 上傳。

  • 使用 Python 請求模塊將字典發布到公司網站。 使用 request.post() 方法向 http:///feedback 發出 POST 請求。 替換為 35.193.233.100。

  • 確保不返回錯誤消息。 您可以打印響應對象的 status_code 和文本來檢查發生了什么。 您還可以使用響應 status_code 201 來創建指示請求已成功的成功狀態響應代碼。

#! /usr/bin/env python3
import os
import requests
 
dir="/data/feedback/"
url= "http://1.1.1.1/feedback/"
#IMPORTANT: Replace 1.1.1.1 with your
#  Qwiklab's "corpweb" IP Address
 
for file in os.listdir(dir):
    tipos = ["title","name","date","feedback"]
    datos = {}
    lineas = []
    print(file)
    with open(dir+"/"+file,"r") as txtfile:
        x = 0
        for line in txtfile:
            datos[tipos[x]] = line.rstrip('\n')
            x += 1
    print(datos)
    response = requests.post(url,json=datos)
#! /usr/bin/env python3

import os
import requests

feedbacks_dir = '/data/feedback'
url = 'http://<corpweb-external-IP>/feedback/' #Replace <corpweb-external-IP> with your external ip

files = os.listdir(feedbacks_dir)

for file in files:
  file_obj = open(os.path.join(feedbacks_dir, file), 'r')

  lines = [ line.replace('\n', '') for line in file_obj ]

  feedback_dict = { "title": lines[0], "name": lines[1], "date": lines[2], "feedback": lines[3] }

  res = requests.post(url, data=feedback_dict)

  if not res.status_code == 201:
    print('Something went wrong')

  file_obj.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM