python高性能web框架Sanic学习--url

本文基于sanic 官方文档解释及自己阅读后的感想.

首先什么是sanic?

sanic是一款用python3.5+写的web framework。它有一下几个特点:

1.flask-like的语法风格,简单易学

2.轻量

3.基于python3.5 async/await 及uvloop 它的性能非常好

4.支持websocket

…………

特性先不BB了。

让我们切入正题, 首先建立一个简单的http应用

from sanic import Sanic
from sanic.response import text

app = Sanic()

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

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

是不是很简单!

首先我们导入sanic库的Sanic类以及sanic.response类中的text方法

接着通过@app.route装饰器编写我们的url地址

然后我们写了一个test的api,这个方法定义了当有人访问时返回一个hello world的字符串

注意async关键字

玩py3.5的小伙伴肯定很熟悉了吧?没错这个接口是异步调用。
至于异步调用的好处 我这里也就不再累述了。

接着我们打开浏览器,输入我们的主机ip+8000 我们就能看到hello world了

当然我们也可以在url中带入我们需要的参数,例如:

from sanic.response import text

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

我们在原始url后面添加<>标记代表需要额外再url中传递的参数。这时当我们访问ip/tag/1 的时候,浏览器会显示出 Tag -1 的字样。

如果刚才的实例我只想让int类型的数据传递进来,有什么方便的方法吗? 答案是肯定的,我们把才的代码稍加修改一下,变成下面这样:

@app.route('/tag/<tag:int>')
async def tag_handler(request, tag):
    return text('Tag - %s'%tag)

没错 我只是加了个:int 就完成了这个功能。并且当传参不是int类型时页面将自动跳转到404页面。是不是很棒呢!这样再也不需要在方法中去判断限制了。

当然了我们还可以做其他的限制,比如用正则表达式限制该传参必须是字母。

@app.route('/tag/<tag:[A-z]+>')
async def tag_handler(request, tag):
    return text('Tag - %s'%tag)

到现在为止我们都是基于get的操作请求,那我要用POST提交数据呢?这个也很简单。只要在@app.route 装饰器中添加 methods=['POST']就可以了。
如以下代码:

@app.route('/tag/<tag:int>', methods=['POST'])
async def tag_handler(request, tag):
    return text('Tag - %s'%tag)

有时候不想在每个方法上都写一个url装饰器,那怎么办?那我们可以这样写:

async def tag_handler(request, tag):
    return text('Tag - %s'%tag)

app.add_route(tag_handler, '/tag')

ok接下来介绍一个很有趣的东西. url_for

它能根据api的处理方法生成url。

@app.route('/')
async def index(request):
    # generate a URL for the endpoint `post_handler`
    url = app.url_for('post_handler', post_id=5)
    # the URL is `/posts/5`, redirect to it
    return redirect(url)


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

当我访问/ 首页时 会自动跳转到/post 还会自动在url中携带post_id=5的参数

最后我访问/ 首页时 获得是 Post - 5 的数据信息。

当然它拥有很多的传参类型 下面的代码展示的就是不同类型下传参的格式变化

url = app.url_for('post_handler', post_id=5, arg_one='one', _anchor='anchor')
# /posts/5?arg_one=one#anchor

url = app.url_for('post_handler', post_id=5, arg_one='one', _external=True)
# //server/posts/5?arg_one=one
# _external requires passed argument _server or SERVER_NAME in app.config or url will be same as no _external

url = app.url_for('post_handler', post_id=5, arg_one='one', _scheme='http', _external=True)
# http://server/posts/5?arg_one=one
# when specifying _scheme, _external must be True

# you can pass all special arguments one time
url = app.url_for('post_handler', post_id=5, arg_one=['one', 'two'], arg_two=2, _anchor='anchor', _scheme='http', _external=True, _server='another_server:8888')
# http://another_server:8888/posts/5?arg_one=one&arg_one=two&arg_two=2#anchor

最后介绍下websocket的路由方法

@app.websocket('/feed')
async def feed(request, ws):
    while True:
        data = 'hello!'
        print('Sending: ' + data)
        await ws.send(data)
        data = await ws.recv()
        print('Received: ' + data)

是不是也很简单呢?

同样我们也可以用app.add_websocket_route(feed, '/feed')

来使用不基于装饰器的url规则编写。

下一节,我将分享sanic如何接收数据处理后并返回数据。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,124评论 19 139
  • 1. 入门 Sanic 是一款类似Flask的Web服务器,它运行在Python 3.5+上。 除了与Flask功...
    JasonJe阅读 14,738评论 4 37
  • 元旦假期前的最后一小时, 公司同事提前一个小时下班, 提前一天进入癫痫状态…… 也许是2016有太多的事情,太多的...
    囚徒_9527阅读 3,173评论 1 0
  • 爱着爱着慢慢就深了
    无聊的小豆子阅读 1,396评论 0 0
  • 倾南海之水如何尽东山之石怎样云海之颠山雨之幻美的让人肝肠寸断奈何过客无缘自叹山水有源 除西墙之尘可好登北屋之顶聊赖...
    子升阅读 2,338评论 0 0

友情链接更多精彩内容