Tornado是Python的异步Web框架,适合高并发场景。它基于非阻塞I/O和事件循环,支持WebSocket、实时推送和大量并发连接。使用pip install tornado安装,通过tornado.web.Application定义路由,支持路径参数与多HTTP方法。推荐用async/await语法实现异步处理,避免阻塞主线程。可配置template_path和static_path以使用模板和静态文件,通过render()渲染页面。原生支持WebSocket,适用于实时通信应用。生产环境建议结合Nginx反向代理,使用supervisord管理进程,并通过bind()+start(n)启动多进程提升性能。核心要点是避免同步阻塞代码,正确启动IOLoop,充分发挥其异步优势。

Tornado 是一个基于 Python 的开源 Web 框架和异步网络库,最初由 FriendFeed 开发。它最大的特点是使用非阻塞 I/O 实现高性能,特别适合长连接、实时服务(如 WebSocket)和需要处理大量并发连接的场景。
与 Django 或 Flask 这类同步框架不同,Tornado 能通过单线程处理成千上万的并发连接,这得益于它的事件循环机制。因此,如果你要做聊天应用、实时推送系统或高并发 API 服务,Tornado 是个不错的选择。
使用 pip 安装 Tornado:
pip install tornado
立即学习“Python免费学习笔记(深入)”;
下面是一个最基础的 “Hello, World” 示例:
import tornado.ioloop
import tornado.web
<p>class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, World")</p><p>def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])</p><p>if <strong>name</strong> == "<strong>main</strong>":
app = make_app()
app.listen(8888)
print("Server starting on <a href="https://www.php.cn/link/4f10ac32425eaa39b2f93cd9c67ff456">https://www.php.cn/link/4f10ac32425eaa39b2f93cd9c67ff456</a>")
tornado.ioloop.IOLoop.current().start()</p>运行后访问 https://www.php.cn/link/4f10ac32425eaa39b2f93cd9c67ff456 就能看到返回内容。
Tornado 使用元组列表定义 URL 路由,格式为 (路径, 处理类)。你可以提取路径参数:
<pre class="brush:php;toolbar:false;">class UserHandler(tornado.web.RequestHandler):
def get(self, user_id):
self.write(f"User ID: {user_id}")
<h1>路由</h1><p>(r"/user/(\d+)", UserHandler)
支持的方法包括 get()、post()、put()、delete() 等,按需实现即可。
使用 @tornado.web.asynchronous 或更推荐的 async/await 语法来写异步接口:
import tornado.gen
import tornado.web
import tornado.httpclient
import asyncio
<p>class AsyncHandler(tornado.web.RequestHandler):
async def get(self):
http_client = tornado.httpclient.AsyncHTTPClient()
try:
response = await http_client.fetch("<a href="https://www.php.cn/link/4d2fe2e8601f7a8018594d98f28706f2">https://www.php.cn/link/4d2fe2e8601f7a8018594d98f28706f2</a>")
self.write(response.body)
except Exception as e:
self.set_status(500)
self.write(f"Error: {e}")
这样不会阻塞主线程,能同时处理多个请求。
项目结构建议:
project/
├── app.py
├── templates/
│ └── index.html
└── static/
└── style.css
配置模板和静态文件目录:
app = tornado.web.Application(
handlers=[
(r"/", MainHandler),
],
template_path="templates",
static_path="static"
)
在 RequestHandler 中使用 render() 方法渲染模板:
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html", message="Hello from Tornado")
Tornado 原生支持 WebSocket,适合做实时通信:
class EchoWebSocket(tornado.websocket.WebSocketHandler):
def open(self):
print("WebSocket opened")
<pre class="brush:php;toolbar:false;"><code>def on_message(self, message):
self.write_message(f"You said: {message}")
def on_close(self):
print("WebSocket closed")(r"/ws", EchoWebSocket)
开发阶段可以直接运行脚本。生产环境建议:
示例:
if __name__ == "__main__":
app = make_app()
app.bind(8888)
app.start(4) # 启动 4 个进程
tornado.ioloop.IOLoop.current().start()
基本上就这些。Tornado 不复杂但容易忽略细节,比如别忘了启动 IOLoop,也别在 handler 里写阻塞代码。掌握好异步编程模型,就能发挥它的真正性能优势。
以上就是python tornado是什么?怎么用?的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号