小白入门——基于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": "今天是个好天气~"}。

相关推荐
Faker66363aaa3 分钟前
中国传统园林建筑检测与识别---RetinaNet_PVT-M_FPN_1x_COCO原创
python
清水白石0081 小时前
NumPy 向量化实战指南:从原理到实践的性能革命
python·numpy
Coding茶水间1 小时前
基于深度学习的猪识别系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
图像处理·人工智能·python·深度学习·yolo·目标检测
X54先生(人文科技)2 小时前
启蒙灯塔起源团预言—碳硅智能时代到来
人工智能·python·机器学习·语言模型
qq_24218863322 小时前
快速搭建跨环境检测服务的步骤
linux·开发语言·windows·python·macos
JaydenAI2 小时前
[拆解LangChain执行引擎]三种持久化模式的差异
python·langchain
老赵全栈实战2 小时前
《从零搭建RAG系统第4天:问题向量化+Milvus检索匹配+结果优化》
python·ai编程
Katecat996633 小时前
【葡萄病害检测】基于SABL-RetinaNet的葡萄叶片黑腐病、霜霉病、白粉病和锈病自动识别系统
python
FL16238631293 小时前
windows从源码安装python版本paddleocr3.4.0
开发语言·windows·python
七夜zippoe3 小时前
模型解释性实战:从黑盒到白盒的SHAP与LIME完全指南
人工智能·python·机器学习·shap·lime