zoukankan      html  css  js  c++  java
  • 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规则编写。



  • 相关阅读:
    ASP.NET小知识
    追溯ASP.NET发展史
    《ASP.NET MVC4 WEB编程》学习笔记------UrlHelper
    Python数据分析8-----网页文本处理
    sklearn学习9----LDA(discriminat_analysis)
    树(8)----路径和
    树(7)-----二叉树的序列化和反序列化
    xgboost学习
    Python笔记24-----迭代器、生成器的使用(如嵌套列表的展开、树的遍历等)
    算法20-----卡诺兰数
  • 原文地址:https://www.cnblogs.com/l520/p/10272677.html
Copyright © 2011-2022 走看看