为什么通过 python 请求调用 post rest api 时出现 500 Internal Server Error? [英] Why am I getting 500 Internal Server Error when calling post rest api via python request?

查看:108
本文介绍了为什么通过 python 请求调用 post rest api 时出现 500 Internal Server Error?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 python requests 库调用 post rest API.当我使用邮递员请求时,我能够得到正确的响应.当我尝试使用 python 请求库调用它时,出现内部服务器错误.

I'm trying to call a post rest API using python requests library. I'm able to get a proper response when I request using postman. When I tried to call it using python request library I get an internal server error.

import requests

url = "http://192.188.9.146:9886/getcontext/"

payload = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"project\"\r\n\r\ndaynight\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"file\"; filename=\"D:\\Downloads\\GTA.Imaging.Services\\GTA.Imaging.Services.Wrapper.TestApp\\PatternMatchingdata\\Go_To_Setting_Screen.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--"
headers = {
    'content-type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
    'cache-control': "no-cache",
    'Postman-Token': "79668e4b-305b-404e-904f-92fc71a12f9f"
    }

response = requests.request("POST", url, data=payload, headers=headers)

print(response.text)

这给了我如下错误

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request.  Either the server is overloaded or there is an error in the application.</p>

当我使用邮递员客户端应用程序时,我得到了预期响应的输出邮递员客户端我究竟做错了什么?任何指导都会非常有帮助,谢谢.

When I use the postman client app I get output with the expected response Postman client what am I doing wrong? Any guidance will be very helpful thanks.

推荐答案

删除 payload 参数并添加 files.请参阅请求文档 解释了 requests.request 函数的这个选项.

Remove the payload parameter and add files. Refer to requests documentation which explains this option of requests.request function.

import requests

url = "http://192.188.9.146:9886/getcontext/"

files = {'file': open('PATH_TO_FILE\Go_To_Setting_Screen.jpg','rb')}
data  = {'project': 'daynight'}

response = requests.request("POST", url, files = files, data = data)

print(response.text)

这篇关于为什么通过 python 请求调用 post rest api 时出现 500 Internal Server Error?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆