使用Python的HTTP请求:TypeError:需要整数(get type socket)

2024-05-19 19:18:11 发布

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

我在尝试通过HTTP检索资源时遇到了一个非常奇怪的bug。这似乎发生在任何HTTP客户机上(尝试请求和urllib结果相同)。在

我的项目使用django,我使用tox和标准django命令python manage.py test运行测试。当我运行我的测试套件时,一个单元测试发出一个HTTP请求(例如通过requests.get('http://example.com')),测试失败并出现错误,测试套件继续到最后,并挂起。我必须通过命令行手动终止进程。在

经过一些调查,我在http请求周围放置了一个try / except块,得到了以下stacktrace:

File "/mycomputer/python3.4/site-packages/requests/api.py", line 68, in get
  return request('get', url, **kwargs)
File "/mycomputer/python3.4/site-packages/requests/api.py", line 50, in request
  response = session.request(method=method, url=url, **kwargs)
File "/mycomputer/python3.4/site-packages/requests/sessions.py", line 464, in request
  resp = self.send(prep, **send_kwargs)
File "/mycomputer/python3.4/site-packages/requests/sessions.py", line 576, in send
  r = adapter.send(request, **kwargs)
File "/mycomputer/python3.4/site-packages/requests/adapters.py", line 370, in send
  timeout=timeout
File "/mycomputer/python3.4/site-packages/requests/packages/urllib3/connectionpool.py", line 544, in urlopen
  body=body, headers=headers)
File "/mycomputer/python3.4/site-packages/requests/packages/urllib3/connectionpool.py", line 349, in _make_request
  conn.request(method, url, **httplib_request_kw)
File "/usr/lib/python3.4/http/client.py", line 1065, in request
  self._send_request(method, url, body, headers)
File "/usr/lib/python3.4/http/client.py", line 1103, in _send_request
  self.endheaders(body)
File "/usr/lib/python3.4/http/client.py", line 1061, in endheaders
  self._send_output(message_body)
File "/usr/lib/python3.4/http/client.py", line 906, in _send_output
  self.send(msg)
File "/usr/lib/python3.4/http/client.py", line 841, in send
  self.connect()
File "/mycomputer/python3.4/site-packages/requests/packages/urllib3/connection.py", line 155, in connect
  conn = self._new_conn()
File "/mycomputer/python3.4/site-packages/requests/packages/urllib3/connection.py", line 134, in _new_conn
  (self.host, self.port), self.timeout, **extra_kw)
File "/mycomputer/python3.4/site-packages/requests/packages/urllib3/util/connection.py", line 68, in create_connection
  sock = socket.socket(af, socktype, proto)
File "/usr/lib/python3.4/socket.py", line 123, in __init__
  _socket.socket.__init__(self, family, type, proto, fileno)
TypeError: an integer is required (got type socket)

我真的不明白这里的问题。从命令行运行同样的操作非常完美,因此这可能与我的项目架构有关。另外,在另一台计算机上运行测试套件也会以同样的方式失败。在

有人遇到过类似的问题吗?我能做些什么来追踪这个问题?在


Tags: inpyselfsendhttprequestlibpackages
2条回答

我在某个地方读到django不是一个完整的服务器,当您尝试将其作为一个完整的服务器使用时,可能会导致问题。也许这就是其中之一。在

你试过https://docs.djangoproject.com/en/1.8/topics/testing/advanced/?在

好的,问题是由HTTPretty引起的,这是我用来模仿的第三方包。在

相关问题 更多 >