繁体   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