如何向外部发送Django请求

2024-06-16 11:48:55 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我在django视图中使用了这个方法将文件发布到另一个服务器。我收到一个HTTP 415错误,它抱怨请求的媒体类型。我已经调试了请求,并将其内容复制粘贴到fiddler中。当我从fiddler发来同样的消息时,它起了作用。所以我不明白为什么使用python requests包不起作用。

有人能帮我吗?

谢谢。

def upload(request):
    if request.method == 'POST':
        url=settings.WEBSERVICES_URL+'validate'
        r = requests.post('http://localhost:9090/validate',data=request)
        r2 = requests.get('http://localhost:9090/test')
        return render_to_response("upload.html", context_instance=RequestContext(request))
    else:
        return render_to_response("upload.html", context_instance=RequestContext(request))

Tags: toinstancelocalhosthttpreturnresponserequesthtml
2条回答

如果你看一下documentation of requests,它显示了data关键字:

data – (optional) Dictionary, bytes, or file-like object to send in the body of the Request.

Django的request对象是^{}的实例。您应该尝试将必要的数据放入字典中,并将其传递给post()

执行以下操作:

r = requests.post('http://localhost:9090/validate', data=request.POST)

当您只需要post数据时,您正在将一个完整的django.http.HttpRequest对象传递给requests.post

相关问题 更多 >