sanic入门

开始

确保两样都有 pip 以及至少3.6版的Python。Sanic使用新的 async/await 语法,所以早期版本的python将不起用。

pip3 install sanic

配置

Sanic在 config 应用程序对象的属性。配置对象只是一个对象,可以使用点符号或类似字典进行修改:

app = Sanic('myapp')
app.config.DB_NAME = 'appdb'
app.config['DB_USER'] = 'appuser'
db_settings = {
    'DB_HOST': 'localhost',
    'DB_NAME': 'appdb',
    'DB_USER': 'appuser'
}
app.config.update(db_settings)

从文件加载配置

app.update_config("/path/to/my_config.py")

日志

from sanic import Sanic
from sanic.log import logger
from sanic.response import text

app = Sanic('logging_example')

@app.route('/')
async def test(request):
    logger.info('Here is your log')
    return text('Hello World!')

if __name__ == "__main__":
  app.run(debug=True, access_log=True)

自配日志

app = Sanic('logging_example', log_config=LOGGING_CONFIG)

关闭日志

if __name__ == "__main__":
  app.run(access_log=False)
posted @ 2021-05-31 11:00  大神归来  阅读(246)  评论(0)    收藏  举报