Sanic学习(二) - 基础

路由

  • 路由方面其实和flask很类似,flask不熟悉的话可以去看看我前面关于flask的基础教程
  • 但是这里有一点不同,就是必须使用async def语法定义Sanic处理程序函数,因为它们是异步函数。
  • 路由设置上通常使用@app.route装饰器指定路径。但是,这个装饰器实际上只是该app.add_route 方法的包装器,使用方法如下:
from sanic.response import text

# Define the handler functions
async def handler1(request):
    return text('OK')

async def handler2(request, name):
    return text('Folder - {}'.format(name))

async def person_handler2(request, name):
    return text('Person - {}'.format(name))

# Add each handler function as a route
app.add_route(handler1, '/test')
app.add_route(handler2, '/folder/<name>')
app.add_route(person_handler2, '/person/<name:[A-z]>', methods=['GET'])

通常使用@add.route比较方便也容易记忆

@app.route("/")
async def test(request):
    return json({"hello": "world"})

请求参数

请求参数同样通过<>括起来,如果要指定类型,则用" : "指定,并将它作为关键字参数传递给路由处理函数。

from sanic.response import text

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

@app.route('/number/<integer_arg:int>')
async def integer_handler(request, integer_arg):
    return text('Integer - {}'.format(integer_arg))

@app.route('/number/<number_arg:number>')
async def number_handler(request, number_arg):
    return text('Number - {}'.format(number_arg))

@app.route('/person/<name:[A-z]+>')
async def person_handler(request, name):
    return text('Person - {}'.format(name))

@app.route('/folder/<folder_id:[A-z0-9]{0,4}>')
async def folder_handler(request, folder_id):
    return text('Folder - {}'.format(folder_id))

HTTP请求

可以在路由设置里面设置对应请求方式以及设置默认主机

from sanic.response import text

@app.route('/post', methods=['POST'])
async def post_handler(request):
    return text('POST request - {}'.format(request.json))

@app.route('/get', methods=['GET'])
async def get_handler(request):
    return text('GET request - {}'.format(request.args))

#host设置

@app.route('/get', methods=['GET'], host='example.com')
async def get_handler(request):
    return text('GET request - {}'.format(request.args))

# if the host header doesn't match example.com, this route will be used
@app.route('/get', methods=['GET'])
async def get_handler(request):
    return text('GET request in default - {}'.format(request.args))

url_for

为了有效避免URL硬编码,可以使用路由反转,这里不懂可以回看我之前flask里面关于url_for的地方,通过函数名返回函数路由,并可以传入关键字参数构建路由,后面的参数会默认跟在函数的路由后面构建成为新的URL


@app.route('/posts/<post_id>')
async def post_handler(request, post_id):
    return text('Post - {}'.format(post_id))

url = app.url_for('post_handler', post_id=5, arg_one='one', arg_two='two')
# /posts/5?arg_one=one&arg_two=two
  • 必须传递所有有效参数才能url_for构建URL。如果未提供参数,或者参数与指定的类型不匹配,URLBuildError则将抛出a。

静态文件

可以使用url_for静态文件URL构建。如果直接用于文件,filename可以忽略。
静态文件这里开始没看懂,大家初学可以不用太过在意里面蓝图方面的内容,name也只是给一个命名方便之后调用,这里静态文件的设置主要就是设置一个路由对应一个本地文件路径,例如:

  • app.static('/pic.jpg', './static/images'),路由上访问/pic.jpg即是访问本地./static/images/pic.jpg下的pic.jpg,这里和其他的诸如flask或者django的设置类似,可以在配置文件中给出一个基础路径base_dir地址,然后static在基础路径的基础上拼接出静态文件的路径
app = Sanic('test_static')
app.static('/static', './static')
app.static('/uploads', './uploads', name='uploads')
app.static('/the_best.png', '/home/ubuntu/test.png', name='best_png')

bp = Blueprint('bp', url_prefix='bp')
bp.static('/static', './static')
bp.static('/uploads', './uploads', name='uploads')
bp.static('/the_best.png', '/home/ubuntu/test.png', name='best_png')
app.blueprint(bp)

# then build the url
app.url_for('static', filename='file.txt') == '/static/file.txt'
app.url_for('static', name='static', filename='file.txt') == '/static/file.txt'
app.url_for('static', name='uploads', filename='file.txt') == '/uploads/file.txt'
app.url_for('static', name='best_png') == '/the_best.png'

# blueprint url building
app.url_for('static', name='bp.static', filename='file.txt') == '/bp/static/file.txt'
app.url_for('static', name='bp.uploads', filename='file.txt') == '/bp/uploads/file.txt'
app.url_for('static', name='bp.best_png') == '/bp/static/the_best.png'

毕竟现在来说sanic还是一个相对比较新的web框架,网上的资源也相对比较少,老实讲光是看中信高科的官方文档确实有点头大,网上各路大佬的教程有突然开始飙车,很难找到那种能一步一步带你走的教程,所以更多的还是需要自己摸索,从基础案例开始练练手,因为方法是死的,只要原理懂了其实具体操作起来难度也不会很大,各个框架之间都是有联系的,比如后面的蓝图模块,也是和flask中的很类似,小编也是初接触,接下来准备去练练手,到时候再回来给大家总结一下

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 22年12月更新:个人网站关停,如果仍旧对旧教程有兴趣参考 Github 的markdown内容[https://...
    tangyefei阅读 35,235评论 22 257
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,982评论 19 139
  • Flask简介 Flask是一个相对于Django而言轻量级的Web框架。 和Django大包大揽不同,Flask...
    爱码小士阅读 13,772评论 1 11
  • 我来北京的第一年,也是我毕业后的第一个春节,因为和父母赌气故意没有买回老家的车票,骗他们说买不到票所以不回去。 一...
    晚安亲爱的阅读 493评论 0 0
  • 一夜冷风骤,凄雨入离愁。提笔欲尽心事,未语泪先流。独倚空阁寒舍,孤唱悲词旧曲,求醉解烦忧。漫道旧情去,清瘦是何由?...
    燕白痴阅读 331评论 0 3