zoukankan      html  css  js  c++  java
  • Sanic官翻-响应

    响应

    使用sanic.response模块中的函数来创建响应。

    Plain Text

    from sanic import response
    
    
    @app.route('/text')
    def handle_request(request):
        return response.text('Hello world!')
    

    HTML

    from sanic import response
    
    
    @app.route('/html')
    def handle_request(request):
        return response.html('<p>Hello world!</p>')
    

    JSON

    from sanic import response
    
    
    @app.route('/json')
    def handle_request(request):
        return response.json({'message': 'Hello world!'})
    

    File

    from sanic import response
    
    
    @app.route('/file')
    async def handle_request(request):
        return await response.file('/srv/www/whatever.png')
    

    Streaming

    from sanic import response
    
    @app.route("/streaming")
    async def index(request):
        async def streaming_fn(response):
            await response.write('foo')
            await response.write('bar')
        return response.stream(streaming_fn, content_type='text/plain')
    

    See Streaming for more information.

    File Streaming

    对于大型文件,请结合上述文件和流媒体

    from sanic import response
    
    @app.route('/big_file.png')
    async def handle_request(request):
        return await response.file_stream('/srv/www/whatever.png')
    

    Redirect

    from sanic import response
    
    
    @app.route('/redirect')
    def handle_request(request):
        return response.redirect('/json')
    

    Raw

    无需编码body即可响应

    from sanic import response
    
    
    @app.route('/raw')
    def handle_request(request):
        return response.raw(b'raw data')
    

    Empty

    RFC 2616中定义用于响应由定义的空消息

    from sanic import response@app.route('/empty')async def handle_request(request):    return response.empty()
    

    更改headers or status

    要修改标题或状态代码,请将headers,status参数传递给这些函数

    from sanic import response@app.route('/json')def handle_request(request):    return response.json(        {'message': 'Hello world!'},        headers={'X-Served-By': 'sanic'},        status=200    )
    
  • 相关阅读:
    bzoj-2748 2748: [HAOI2012]音量调节(dp)
    bzoj-2338 2338: [HNOI2011]数矩形(计算几何)
    bzoj-3444 3444: 最后的晚餐(组合数学)
    codeforces 709E E. Centroids(树形dp)
    codeforces 709D D. Recover the String(构造)
    codeforces 709C C. Letters Cyclic Shift(贪心)
    codeforces 709B B. Checkpoints(水题)
    codeforces 709A A. Juicer(水题)
    Repeat Number
    hdu 1003 Max Sum (动态规划)
  • 原文地址:https://www.cnblogs.com/fhkankan/p/14763551.html
Copyright © 2011-2022 走看看