直接通过aiohttp启动服务
import logging
import asyncio
from aiohttp import web
async def index(request):
return web.Response(text="Welcome home!")
async def init(loop):
app = web.Application(loop=loop)
app.router.add_route('GET', '/', index)
server = await loop.create_server(app.make_handler(), '0.0.0.0', 9000)
logging.info('server started at http://127.0.0.1:9000...')
return server
if __name__ == '__main__':
event_loop = asyncio.get_event_loop()
try:
event_loop.run_until_complete(init(event_loop))
event_loop.run_forever()
except KeyboardInterrupt:
pass
except BaseException as e:
logging.error(e)
单独通过gunicorn启动
安装gunicorn:
pip install gunicorn
需要web.Application()
示例: 在app.py
文件中:
from aiohttp import web
def index(request):
return web.Response(text="Welcome home!")
app = web.Application()
app.router.add_route('GET', '/', index)
将程序在localhost
的8080
端口启动:
gunicorn app:app -k aiohttp.worker.GunicornWebWorker -b localhost:8080
将程序在0.0.0.0
的9000
端口启动:
gunicorn app:app -k aiohttp.worker.GunicornWebWorker -b 0.0.0.0:9000
通过gunicorn+Nginx部署(推荐)
首先,对Nginx进行配置.
这里以9000
端口为例子:
为了和Nginx的主配置分开,我们可以在Nginx的配置文件的http中加入
include /srv/www/server/conf/nginx/*.conf;
在/srv/www/server/conf/nginx/
目录下创建新的配置文件:hhuua.com.conf
hhuua.com.conf
server {
charset utf-8;
listen 9000;
server_name www.hhuua.com;
location / {
proxy_set_header Host $host;
proxy_pass http://unix:/tmp/www.hhuua.com.socket;
}
}
重启Nginx
启动gunicorn
进入到项目目录
aiohttp
的代码例子如开头,文件名为:app_main.py
启动:
gunicorn app_main:app --bind unix:/tmp/www.hhuua.com.socket --worker-class aiohttp.GunicornWebWorker
部署完成,进行测试