tornado 中的阻塞求指教

2014-03-30 19:49:49 +08:00
 nilai
如下代码:
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import time
import os

from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)

class IndexHandler(tornado.web.RequestHandler):
def get(self):
print "begin"
#time.sleep(10)
os.system("ping www.baidu.com -c 10")

if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(handlers=[(r"/sleep", IndexHandler)])
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()




现在当浏览器请求地址:
http://127.0.0.1:8000/sleep 会一直ping 10次百度,此时有另一个用户也访问这个地址, 但是另一个用户会被阻塞掉,一直等到第一个用户ping执行完后 第二个用户才能执行, 怎么样实现非阻塞的操作.
5185 次点击
所在节点    Python
27 条回复
ggarlic
2014-03-31 23:01:57 +08:00
@nilai very easy
使用ProcessProtocol
https://twistedmatrix.com/documents/13.0.0/core/howto/process.html

之前看到有人用twisted写爬虫用urlopen嫌慢,其实twisted也有异步的urlopen版本twisted.web.client.getPage

写异步用同步的time.sleep之类的不是自己给自己找麻烦么
zenliver
2014-03-31 23:31:31 +08:00
@ggarlic 顶, 呵呵,,,
zenliver
2014-03-31 23:34:14 +08:00
@CMGS 分析的很好, 不过time.sleep不就相当于一个cpu密集型的operation吗
CMGS
2014-04-01 01:01:23 +08:00
@zenliver time.sleep 其实比较特殊,为什么说特殊呢,原本是用来模拟大循环(业务向)的CPU密集操作,但是在event-driven的驱动里面,比喻起来应该是suspend,和时间循环是相关的
nilai
2014-04-01 16:01:44 +08:00
@ggarlic
能不能像 kingxsp 来个可用的改写
ggarlic
2014-04-01 22:17:24 +08:00
<script src="https://gist.github.com/ggarlic/f0d5c4135a98cce96c7a.js"></script>
在我这测试能用,请自行修改ping的路径。
然后,web开发我不熟,我拿twisted都是写别的东西。用同一个浏览器同时打开几个页面还是会顺序访问,用不同浏览器,或者直接终端里同时跑几个curl就没事。Twisted Network Programming Essentials, 2nd EditionEssential Twisted里关于这个的说明:
If you run Example 4-10 and then load multiple instances of http://localhost:8000 in a browser, you may still find that the requests are processed serially. This is not Twisted’s fault: some browsers, notably Chrome, serialize requests to the same resource. You can verify that the web server isn’t blocking by issuing several simultaneous requests through cURL or a quick Python script.
ggarlic
2014-04-01 22:21:48 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/106539

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX