首先

pip install sanic
...
from sanic import Sanic

为什么是Sanic而不是Flask?因为这玩意儿异步呀~

Sanic doc

Sanic API

实例化Sanic对象

app = Sanic("MyApp")

Sanic对象相关设置

静态资源路径

app.static("/static", "./statics")

其中,/static为静态资源在网页缓存中的链接,./statics为静态资源中在项目中的位置。因此,在js之类的东西中要引用资源,就应该用/static(之前被路径问题搞麻了已经)

视图函数

定义路由的基本方式

@app.route("/")
async def hello_world(request):
    return text("suc!")

路由参数

单个参数

@app.route('/tag/<tag>')
async def tag_handler(request, tag):
    return text("Tag - {}".format(tag))
    
# OR

async def tag_handler(request):
    return text("Tag - {}".format(tag))


app.add_route(handler, "'/tag/<tag>'")

多个参数

@app.route("/detail/Class")
async def getDetailedMessage(request: request.Request):
    args = request.args
    try:
        buildingName, Time, date = args['bd'][0], args['t'][0], args['dt'][0]
        return json(ClassRoomData[urlMap0[buildingName]][Time][date])
    except Exception as e:
        return json({e})

返回值

返回html

没有模板渲染的html

@app.route('/')
async def main(request):
    return html('<!DOCTYPE html><html lang="en"><meta charset="UTF-8"><div>Hi 😎</div>')
import os
async def main(request):
    template = open(os.getcwd() + "/templates/index.html")
    return html(template.read())

返回被渲染的html

理论上用jinja可以的,但是不知道为啥跑不出来555

返回text

@app.route('/')
async def main(request):
    return text('hello world!')