运行Python脚本时请求状态码500

时间:2020-06-25 06:14:33

标签: python python-3.x dictionary python-requests readlines

这是我应该做的:

  1. 列出data / feedback文件夹中的所有文件
  2. 扫描所有文件,并创建带有标题,名称,日期和反馈的嵌套字典(所有文件均为标题,名称,日期和反馈格式,每个文件都在不同的文件行中,这就是使用rstrip函数的原因)
  3. 将字典发布到给定的网址中

以下是我的代码:

   #!/usr/bin/env python3
   import os
   import os.path
   import requests
   import json

   src = '/data/feedback/'
   entries = os.listdir(src)
   Title, Name, Date, Feedback = 'Title', 'Name', 'Date', 'Feedback'
   inputDict = {}
   for i in range(len(entries)):
       fileName = entries[i]
       completeName = os.path.join(src, fileName)
       with open(completeName, 'r') as f:
            line = f.readlines ()
            line tuple = (line[0],line[1],line[2],line[3])
            inputDict[fileName] = {}
            inputDict[fileName][Title] = line_tuple[0].rstrip()
            inputDict[fileName][Name] = line_tuple[1].rstrip()
            inputDict[fileName][Date] = line_tuple[2].rstrip()
            inputDict[fileName][Feedback] = line_tuple[3].rstrip()


   x = requests.get ("http://website.com/feedback")
   print (x.status_code)
   r = requests.post ("http://Website.com/feedback” , data=inputDict)
   print (r.status_code)

我运行它后,得到给出200个代码,但发布给出500个代码。 我只想知道我的脚本是否引起了错误?

1 个答案:

答案 0 :(得分:0)

r = requests.post ("http://Website.com/feedback” , data=inputDict)

如果您的其余api端点期望使用json数据,则上面的行没有这样做;它会以表单编码的形式发送字典inputDict,就像您在HTML页面上提交表单一样。

您可以在json函数中使用post参数,该函数将标头中的内容类型设置为application/json

r = requests.post ("http://Website.com/feedback", json=inputDict)

或手动设置标题:

headers = {'Content-type': 'application/json'}
r = requests.post("http://Website.com/feedback", data=json.dumps(inputDict), headers=headers)
相关问题