我前段时间开始学习Tornado框架.我遇到了缺乏经验的用户的文档,并检查了asyncio模块文档.所以问题是,我在asyncio中有一些简单的代码:
import asyncio
@asyncio.coroutine
def compute(x, y):
print("Compute %s + %s ..." % (x, y))
yield from asyncio.sleep(1.0)
return x + y
@asyncio.coroutine
def print_sum(x, y):
result = yield from compute(x, y)
print("%s + %s = %s" % (x, y, result))
loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1, 2))
loop.close()
Run Code Online (Sandbox Code Playgroud)
然后我尝试使用Tornado框架做同样的事情:
from tornado.ioloop import IOLoop
from tornado import gen
@gen.coroutine
def compute(x, y):
print("Compute %s + %s ..." % (x, y))
yield gen.sleep(1.0)
return (x+y)
@gen.coroutine
def print_sum(x, y):
result = yield compute(x, …Run Code Online (Sandbox Code Playgroud) 我有一个使用 Aiohttp 的非常简单的文件服务器:
import os.path
from os import listdir
import asyncio
from aiohttp import web
import aiohttp_jinja2
import jinja2
@aiohttp_jinja2.template('template2.html')
@asyncio.coroutine
def get(request):
root = os.path.abspath(os.path.dirname(__file__))
files = [file_name for file_name in listdir(os.path.join(root,'files'))
if os.path.isfile(os.path.join(root, 'files', file_name))]
return {'files': files}
if __name__ == "__main__":
app = web.Application()
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('/root/async'))
app.router.add_route('GET', '/', get)
app.router.add_static('/files/' , '/root/async/files')
loop = asyncio.get_event_loop()
f = loop.create_server(app.make_handler(), '0.0.0.0', 8080)
srv = loop.run_until_complete(f)
print(' serving on ', srv.sockets[0].getsockname())
try:
loop.run_forever()
except KeyboardInterrupt:
pass
Run Code Online (Sandbox Code Playgroud)
当我使用 siege 工具测试它时,例如,这样的命令:
siege …Run Code Online (Sandbox Code Playgroud)