Sanic

Sanic (http://sanic.readthedocs.io/) is another interesting project, which specifically tries to provide a Flask-like experience with coroutines.

Sanic uses uvloop (https://github.com/MagicStack/uvloop) for its event loop, which is a Cython implementation of the asyncio loop protocol using libuv, allegedly making it faster. The difference might be negligible in most of your microservices, but ;is good to take any speed gain when it is just a transparent switch to a specific event loop implementation.

If we write the previous example in Sanic, it's very close to Flask:

    from sanic import Sanic, response 
 
    app = Sanic(__name__) 
 
    @app.route("/api") 
    async def api(request): 
        return response.json({'some': 'data'}) 
 
    app.run() 

Needless to say, the whole framework is inspired by Flask, and you will find most of the features that made it a success, such as Blueprints.

Sanic also has its original features, like the ability to write your views in a class (HTTPMethodView) that represents one endpoint, with one method per verb (GET, POST, PATCH, and so on).

The framework also provides middleware to change the request or response.

In the next example, if a view returns a dictionary, it will be automatically converted to JSON:

    from sanic import Sanic 
    from sanic.response import json 
 
    app = Sanic(__name__) 
 
    @app.middleware('response') 
    async def convert(request, response): 
        if isinstance(response, dict): 
            return json(response) 
        return response 
 
    @app.route("/api") 
    async def api(request): 
        return {'some': 'data'} 
 
    app.run() 

This little middleware function simplifies your views if your microservice produces only JSON mappings.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset