小白入门——基于sanic框架的蓝图对象Blueprint

Sanic框架

Sanic是Python3.7+下的Web服务器和异步Web框架,旨在提高性能。

Sanic允许使用Python3.5中添加的 async / await 语法,这使得您的代码有效的避免阻塞从而达到提升响应速度的目的。

从2016年5月发布第一版Sanic框架至今,已经7个年头了,这7年,经过不断地积累和更新,Sanic已经从一个步履蹒跚地小框架变成了一个健步如飞地稳重框架啦~

Sanic 的使用和 Flask 非常相似,有 Flask 基础的童鞋可以很快掌握这个框架。

安装Sanic

Python安装第三方模块都是利用pip工具进行安装:

python 复制代码
pip install sanic
# 如果不想使用uvloop和ujson 可以这样安装
SANIC_NO_UVLOOP=true SANIC_NO_UJSON=true pip install sanic

搭建一个简单的Sanic框架

python 复制代码
# file name: sanic_test.py
from sanic import Sanic
from sanic.response import json

app = Sanic()

@app.route('/')
async def test(request):
    msg = {'msg': 'Hello Sanic, I am zdm.'}
    return json(msg, ensure_ascii=False)

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8080)

将上述代码写入名为sanic_test.py的文件中,通过终端执行该文件,启动Sanic服务。

python 复制代码
python sanic_test.py

终端出现Starting worker,表示启动成功。

在浏览器中访问 http://127.0.0.1:8080,得到返回结果 {'msg': 'Hello Sanic, I am zdm.'}。

Blueprint蓝图对象

** 蓝图对象是Sanic应用程序组织代码的一种方式,可以将应用程序分成多个模块,每个模块都有自己的路由和视图函数。**

** 如下语句定义了一个基于Sanic框架的蓝图对象,用于实现文本纠错服务。**

python 复制代码
from sanic import Blueprint, response

textcorrectservice = Blueprint('textcorrectservice') # 创建一个名为'textcorrectservice'的蓝图对象

举一个蓝图对象的例子:

** 假设我们要实现一个简单的Web应用程序,用于查询当天的天气情况。我们可以使用Sanic框架创建一个蓝图对象,用于处理HTTP请求和响应,如下所示:**

python 复制代码
# file name: Blueprint_test.py
from sanic import Sanic, Blueprint
from sanic.response import json

weather_service = Blueprint('weather_service')

app = Sanic(__name__,)
app.blueprint(weather_service)

@weather_service.route('/weather')
async def get_weather(request):
    # 获取当天的天气情况
    weather = get_today_weather()
    # 生成HTTP响应
    return json({'weather': weather})

def get_today_weather():
	return "今天是个好天气~"
	
if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8080)

例子解析:
在上面的代码中,首先,我们创建了一个名为"weather_service"的蓝图对象,用于处理HTTP请求和响应。在蓝图对象中,我们定义了一个名为"get_weather"的路由和视图函数,用于处理"/weather"路径的HTTP请求。在视图函数中,我们调用了一个名为"get_today_weather"的函数,用于获取当天的天气情况,并使用Sanic框架中的response模块生成了一个JSON格式的HTTP响应。
然后,我们创建了一个名为app的应用程序实例,并将weather_service注册到应用程序中。
最后,通过app.run启动应用程序,并监听来自8080端口的额请求。

将上述代码写入名为Blueprint_test.py的文件中,通过终端执行该文件,启动Sanic服务。

python 复制代码
python Blueprint_test.py

终端出现Starting worker,表示启动成功。

在浏览器中访问 http://127.0.0.1:8080/weather,得到返回结果 {"weather": "今天是个好天气~"}。

相关推荐
〖是♂我〗20 分钟前
自定义数据集 使用scikit-learn中svm的包实现svm分类
开发语言·python
抱抱宝1 小时前
Pyecharts之特殊图表的独特展示
python·信息可视化·数据分析
deephub1 小时前
Python GIL(全局解释器锁)机制对多线程性能影响的深度分析
python·机器学习·gil
MatpyMaster2 小时前
基于PyQt5打造的实用工具——PDF文件加图片水印,可调大小位置,可批量处理!
python·pdf
go54631584652 小时前
python 从知网的期刊导航页面抓取与农业科技相关的数据
开发语言·python·科技
米码收割机3 小时前
【python】tkinter实现音乐播放器(源码+音频文件)【独一无二】
开发语言·python·pygame
星如雨グッ!(๑•̀ㅂ•́)و✧3 小时前
Java NIO全面详解
java·python·nio
笛柳戏初雪3 小时前
Python中的函数(下)
开发语言·python
码界筑梦坊4 小时前
基于Django的个人博客系统的设计与实现
后端·python·django·毕业设计