Skip to main content
 首页 » 编程设计

python之将django服务器与grequests一起使用时出现神秘错误

2024年08月20日32telwanggs

目前,我在 Ubuntu 14.04 上运行一个 vagrant 服务器,我使用简单的 python manage.py runserver 0.0.0.0:8000 测试我所有的 django 模块。

因为我通过 http://localhost:8000 使用 chrome 连接到 django 网络服务器并且服务器在 VM 上运行,我通过使用 Vagrantfile 中的以下设置进行端口转发

config.vm.network "forwarded_port", guest: 8000, host: 8000

一切正常运行(所有模块/ View /测试都按预期运行),但是,自从我开始使用 grequests我收到这个奇怪的错误

Exception happened during processing of request from ('10.0.2.2', 63520) 
Traceback (most recent call last): 
  File "/home/vagrant/anaconda3/lib/python3.6/socketserver.py", line 639, in process_request_thread 
    self.finish_request(request, client_address) 
  File "/home/vagrant/anaconda3/lib/python3.6/socketserver.py", line 361, in finish_request 
    self.RequestHandlerClass(request, client_address, self) 
  File "/home/vagrant/anaconda3/lib/python3.6/socketserver.py", line 696, in __init__ 
    self.handle() 
  File "/home/vagrant/anaconda3/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 159, in handle 
    self.raw_requestline = self.rfile.readline(65537) 
  File "/home/vagrant/anaconda3/lib/python3.6/socket.py", line 586, in readinto 
    return self._sock.recv_into(b) 
  File "/home/vagrant/anaconda3/lib/python3.6/site-packages/gevent/_socket3.py", line 385, in recv_into 
    self._wait(self._read_event) 
  File "/home/vagrant/anaconda3/lib/python3.6/site-packages/gevent/_socket3.py", line 157, in _wait 
    self.hub.wait(watcher) 
  File "/home/vagrant/anaconda3/lib/python3.6/site-packages/gevent/hub.py", line 651, in wait 
    result = waiter.get() 
  File "/home/vagrant/anaconda3/lib/python3.6/site-packages/gevent/hub.py", line 899, in get 
    return self.hub.switch() 
  File "/home/vagrant/anaconda3/lib/python3.6/site-packages/gevent/hub.py", line 630, in switch 
    return RawGreenlet.switch(self) 
gevent.hub.LoopExit: ('This operation would block forever', <Hub at 0x7f3b777e8af8 epoll pending=0 ref=0 fileno=34>) 

请注意,我没有使用 grequests并且简单地导入它似乎会导致这个错误,即使它没有被调用或任何东西

有人有什么想法吗?

请您参考如下方法:

这是底层依赖项之一 - gevent 的问题,它覆盖了 python 内置的默认行为,例如 time 等。

你将不得不使用 monkeypatch。 像这样的东西:

from gevent import monkey 
monkey.patch_all() 

这里是相关的gevent documentation .

我最近遇到了这个问题 - 所以停止使用 grequests 并实现了我自己的异步请求逻辑