0

我有一个 Django 应用程序,它使用美味派提供 RESTful API。

我正在使用 Django 的开发runserver进行测试。

当我通过浏览器访问它时,它可以正常工作,并且使用 Curl 也可以正常工作:

curl "http://localhost:8000/api/v1/host/?name__regex=&format=json"

在带有 runserver 的控制台上,我看到:

[02/Oct/2012 17:24:20] "GET /api/v1/host/?name__regex=&format=json HTTP/1.1" 200 2845

但是,当我尝试使用 Python 请求模块(http://docs.python-requests.org/en/latest/)时,我得到一个 404 作为输出:

>>> r = requests.get('http://localhost:8000/api/v1/host/?name__regex=&format=json')
>>> r
<Response [404]>

或者:

>>> r = requests.get('http://localhost:8000/api/v1/host/?name__regex=&amp;format=json')
>>> r
<Response [404]>

此外,在 Django runserver 控制台上,我看到:

[02/Oct/2012 17:25:01] "GET http://localhost:8000/api/v1/host/?name__regex=&format=json HTTP/1.1" 404 161072

出于某种原因,当我使用请求时,它会打印出整个请求 URL,包括 localhost - 但在我使用浏览器或 curl 时不会。

我假设这与它发送的编码、用户代理或请求类型有关?

4

1 回答 1

0

I'm not very familiar with Requests, but I think your encoding idea might be sound. That is Requests might process the URL somehow? Perhaps instead of passing everything in the URL directly, try doing what Requests docs suggest:

request_params = { 'name_regex' : '', 'format' : 'json' }
r = requests.get( 'http://localhost:8000/api/v1/host/', params = request_params )
于 2012-10-03T09:16:06.760 回答