我阅读了有关如何运行 N 个 Tornado 进程的各种文章和教程,其中 N = 核心数。我的代码可以正常运行,在所有 16 个内核上运行,但我以某种方式搞砸了,我需要重新审视它。
import tornado.ioloop
import tornado.web
import tornado.httpserver
from core import settings
from core import coreService
import services
from tornado.options import define, options, parse_command_line
define("port", default=settings.SERVER_PORT, help="run on the given port", type=int)
app = tornado.web.Application([
(r'/upload', coreService.Upload)
])
if __name__ == "__main__":
tornado.options.parse_command_line()
server = tornado.httpserver.HTTPServer(app, max_buffer_size=1024*1024*201)
server.bind(options.port)
# autodetect cpu cores and fork one process per core
server.start(0)
try:
print 'running on port %s' % options.port
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
tornado.ioloop.IOLoop.instance().stop()
此代码抛出此错误:
File "/opt/tornado/tornado/process.py", line 112, in fork_processes
raise RuntimeError("Cannot run in multiple processes: IOLoop instance "
RuntimeError: Cannot run in multiple processes: IOLoop instance has already been initialized. You cannot call IOLoop.instance() before calling start_processes()
我只是没有看到它。谢谢
:编辑:
正如本所说,我的方法之一就是给我找麻烦。这是该方法的代码,有人可能会从中受益:
from tornado import gen
import motor
db = motor.MotorClient().open_sync().proba
class Upload(BaseHandler):
@gen.engine
def post(self):
fs = yield motor.Op(motor.MotorGridFS(db).open)
gridin = yield motor.Op(fs.new_file)
yield motor.Op(gridin.write, 'First part\n')
yield motor.Op(gridin.write, 'Second part')
yield motor.Op(gridin.close)
print gridin._id
self.write(str(gridin._id))
self.finish()
编辑 2
我找到了问题的最终解决方案。正如本所指出的,上面的方法给我带来了麻烦。在 Motor 文档中记录了将 Motor 包含在 Tornado 应用程序中的正确方法。这是一个对我有用的异常(exception):
if __name__ == "__main__":
tornado.options.parse_command_line()
try:
server = tornado.httpserver.HTTPServer(app, max_buffer_size=1024*1024*201)
server.bind(8888)
server.start(0) # autodetect cpu cores and fork one process per core
db = motor.MotorClient().open_sync().proba
print 'running on port %s' % options.port
# Delayed initialization of settings
app.settings['db'] = db # from this point on db is available as self.settings['db']
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
tornado.ioloop.IOLoop.instance().stop()
最佳答案
此异常在 tornado.web.Application 的 Debug模式下引发。
application = tornado.web.Application([
(r"/", hello),
],
debug=False)
将 debug 设置为 False 以解决此问题。
您可以启动多个进程来监听每个端口:
server = tornado.httpserver.HTTPServer(application)
server.bind(1234) # port
server.start(4)
tornado.ioloop.IOLoop.instance().start()
关于python - 运行多个 Tornado 进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22641015/