Python Web Development with the Sanic Framework

Get into the habit of writing together! This is the 12th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

asyncio module

As an asynchronous Python 3.7+ web framework, Sanic's most basic building block is the asyncio module in the Python standard library .

Python 3.4, released in early 2014, was the first step in bringing the concept of coroutines to the standard library in the newly added asyncio module. Using standard Python generators, the execution of a function can be paused while other things happen, and data can then be injected into the function to resume execution. If there is an object "looping" through the list of tasks that needs work at that time, we can enter and exit the execution of multiple functions at the same time. This enables "concurrency" in a single thread, and is the basis of the idea of ​​asyncio.

A quick look at what asynchronous programming looks like in Python 3.4:

import asyncio


@asyncio.coroutine
def get_value():
    yield from asyncio.sleep(1)
    return 123

@asyncio.coroutine
def slow_operation():
    value = yield from get_value()
    print(">>", value)
    
loop = asyncio.get_event_loop()
loop.run_until_complete(slow_operation())
loop.close()
复制代码

Running result: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead, you can see that this usage has been canceled in Python 3.8.

The current usage is to async defstart with :

import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at {time.strftime('%X')}")

    await say_after(1, 'hello')
    await say_after(2, 'world')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())
复制代码

Output result:

started at 23:39:52
hello
world
finished at 23:39:55
复制代码

The language and syntax of the new asyncio module is very powerful, but a bit clunky. Generators are often a bit cryptic and difficult for inexperienced Python developers. What exactly does the income come from? This stuff is foreign to a lot of people; Python needs better syntax.

Sanic frame

Classic Django and Flask are a synchronous framework, not an asynchronous framework.

In the summer of 2016, Sanic was born to explore this gap. The idea is simple: can we take an app with a seemingly simple API from Flask and make it async/await?

不知何故,这个想法起飞并获得了认可。 这不是一个最初以重做 Python 应用程序处理 Web 请求的方式为目标的项目。 这在很大程度上是一个意外暴露的案例。 该项目迅速爆发并引起了轰动。 让 Flask 采用这种新模式有很大的吸引力。 但是,由于 Flask 本身无法做到这一点,所以很多人认为 Sanic 可能是 Flask 的异步版本。

开发人员很高兴有机会使用最新的 Python 为他们的应用程序带来全新的性能水平。

image.png

Sanic 的目的:提供一个简单的方法来启动和运行一个高性能的HTTP服务器,该服务器易于构建、扩展,并最终扩展。

Sanic的口号是。"快速建设。快速运行"(Build fast.Run fast)。这当然强调了项目的性能导向。它也说明了一个目标,即在Sanic中构建一个应用程序是为了让人感到直观。启动和运行一个应用程序不应该意味着要学习一套复杂的API,并且要不断地打开第二个浏览器窗口查看文档。当其他工具大量使用 "黑匣子 "式的功能,如全局变量、"魔法 "导入和猴子补丁时,Sanic通常更倾向于朝编写好的、干净的和习惯性的 Python(又称pythonic代码)方向发展。如果你知道 Python,你可以用 Sanic 构建一个网络 API。

比如我们来看一个简单的 Hello World例子。

Hello World Example

首先使用 pip3 install sanic 命令安装 sanic 模块。

Installing collected packages: aiofiles, websockets, httptools, sanic-routing, multidict, sanic
Successfully installed aiofiles-0.8.0 httptools-0.4.0 multidict-6.0.2 sanic-22.3.0 sanic-routing-22.3.0 websockets-10.2
复制代码

Sanic() 是最基础的组成部分,通常我们会在一个名为 hello.py 的文件中将其实例化,当然文件名称并不是必须的, 但是我们还是推荐使用 hello.py 做为文件名称来实例化 Sanic 对象。

from sanic import Sanic
from sanic.response import json

app = Sanic("My Hello, world app")

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

if __name__ == '__main__':
    app.run()  
复制代码

Sanic can now be easily run using sanic hello.app

官网链接:sanic.dev/zh/

Guess you like

Origin juejin.im/post/7086457744844292110