# 服务启动类详解
> 首先,我们来看下入口文件引用的库
~~~
# ./web.py
from vendor import logger # 日志库
from vendor.framework import App 服务启动类
import os
~~~
> 日志文件:./vendor/logger.py
~~~
# -*- coding=utf-8 -*-
import logging
import logging.handlers
import time, os
'''
日志模块
'''
# 定义日志保存的目录
log_path = ('./runtime/log/%s' % time.strftime('%Y-%m'))
if not os.path.exists(log_path):
os.makedirs(log_path)
filename = ('/%s.log' % time.strftime('%d'))
LOG_FILENAME = log_path + filename
logger = logging.getLogger('aiohttp.access')
def set_logger():
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
file_handler = logging.handlers.RotatingFileHandler(
LOG_FILENAME, maxBytes=10485760, backupCount=5, encoding="utf-8")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
set_logger()
~~~
> 服务启动基类:./vendor/framework/App.py
~~~
from web import ROOT_PATH
import os
import asyncio
from aiohttp import web
from config.config import SYSCONF
# 配置文件全局路由
from config import routes
# 模板文件配置
import aiohttp_jinja2
from jinja2 import FileSystemLoader
# 加载全局中间件
from application.middleware import middlewares
class App(object):
def __init__(self):
self.app = None
self.root_path = ROOT_PATH
# 获取根目录
def get_root_path(self):
return self.root_path
# 获取应用目录
def get_app_path(self):
return os.path.join(self.root_path, 'application')
def get_loop(self):
return asyncio.get_event_loop()
def create_app(self):
"""
@ 创建应用
@ return: Application
"""
loop = self.get_loop()
self.app = web.Application(loop=loop)
return self.app
def init_templet(self):
"""
@ 模板文件配置
@ return None
"""
path = os.path.join(self.root_path, 'templates')
aiohttp_jinja2.setup(app=self.app, loader=FileSystemLoader(path))
# 静态文件 注册路由
self.app.router.add_static('/static', os.path.join(self.root_path, 'static'), append_version=True)
return None
def start_server(self):
"""
@ 启动服务
@ return:None
"""
self.create_app()
# 加载静态文件、模板
self.init_templet()
# 注册中间件
self.load_middlewares()
# 注册全局路由
routes.reg_routes(self.app)
web.run_app(
self.app,
host=SYSCONF.get('app').get('app_host'),
port=SYSCONF.get('app').get('app_port'),
access_log_format='%a %P "%r" %s bs:[%b] rs:[%Tf] "%{Referer}i" "%{User-Agent}i"')
return None
def load_middlewares(self):
"""
@ 加载全局中间件, 注册中间件前,一定要先开启session
@ return:None
"""
for middle in middlewares:
self.app.middlewares.append(middle)
~~~