【问题标题】:Request Status Code 500 when running Python Script运行 Python 脚本时请求状态码 500
【发布时间】:2020-10-15 12:48:19
【问题描述】:

这是我应该做的:

  1. 列出数据/反馈文件夹中的所有文件
  2. 扫描所有文件,并制作包含标题、名称、日期和反馈的嵌套字典(所有文件均为标题、名称、日期和反馈格式,每个文件位于不同的文件行中,这就是使用 rstrip 功能的原因)
  3. 在给定的 url 中发布字典

以下是我的代码:

   #!/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)

运行后,get 给出 200 个代码,但 post 给出 500 个代码。 我只想知道我的脚本是否导致错误?

【问题讨论】:

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


    【解决方案1】:
    r = requests.post ("http://Website.com/feedback” , data=inputDict)
    

    如果您的 REST API 端点需要 json 数据,那么上面的行没有这样做;它以表单编码的形式发送字典inputDict,就像您在 HTML 页面上提交表单一样。

    您可以在post 函数中使用json 参数,它将标头中的内容类型设置为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)
    

    【讨论】:

    • 感谢您的帮助。另外,我正在制作的 inputDict 。我的代码也可以吗?
    • @NitishBerry 您的代码看起来可以用于创建字典。请尝试我对post 的回答。
    • @NitishBerry 状态码 500 是内部服务器错误。如果您在尝试我的回答后仍然得到答案,我会检查您的 json 数据(来自您的字典)的格式是否正确。那里可能有错误,例如不正确的键名等。
    • 对不起,我睡着了,我还没有时间检查它。我会尽快更新你。非常感谢
    • 它有帮助。谢谢
    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 2023-01-02
    相关资源
    最近更新 更多