尝试仅在python中请求带有requests / urllib的url时出现重定向错误

时间:2016-09-24 20:52:57

标签: python django redirect curl urllib

我试图将数据发布到我的服务器中的网址...但我发送任何请求到该网址(该服务器上的任何网址)这里是一个例如

http://apimy.in/page/test

网站是用python3.4 / django1.9编写的

我可以curl php发送请求,不会有任何问题

但任何使用python的请求都会导致某种重定向错误

起初我尝试了requests lib

我收到了这个错误

TooManyRedirects at /api/sender
Exceeded 30 redirects.
Request Method: GET
Request URL: http://localhost:8000/api/sender
Django Version: 1.9.6
Exception Type: TooManyRedirects
Exception Value:

Exceeded 30 redirects.

我认为requests可能有问题,所以我尝试了urllib

request_data = urllib.parse.urlencode({"DATA": 'aaa'}).encode()
response = urllib.request.urlopen("http://apimy.in/page/test" , data=request_data)



HTTPError at /api/sender
HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop.
The last 30x error message was:
Found
Request Method: GET
Request URL:    http://localhost:8000/api/sender
Django Version: 1.9.6
Exception Type: HTTPError
Exception Value:    
HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop.
The last 30x error message was:
Found
Exception Location: c:\Python344\lib\urllib\request.py in http_error_302, line 675

我使用mod_wsgi和apache来提供网站

1 个答案:

答案 0 :(得分:0)

由于您使用的是requests模块,您是否尝试告诉请求模块忽略重定向?

import requests
response = requests.get('your_url_here', allow_redirects=False)

也许这项工作。 如果这不起作用,您还可以尝试更改user-agent,以防服务器配置为出于安全原因而丢弃script-requests

import requests
headers = {'user-agent': 'some_user_agent'}
response = requests.get(url, headers=headers)