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

相关推荐
大模型铲屎官1 分钟前
【深度学习-Day 23】框架实战:模型训练与评估核心环节详解 (MNIST实战)
人工智能·pytorch·python·深度学习·大模型·llm·mnist
阿幸软件杂货间25 分钟前
PPT转图片拼贴工具 v1.0
python·powerpoint
AIGC_北苏38 分钟前
DrissionPage爬虫包实战分享
爬虫·python·drissionpage
YBCarry_段松啓1 小时前
uv:下一代 Python 包管理器
人工智能·python
yorushika_2 小时前
python打卡训练营打卡记录day45
开发语言·python·深度学习·tensorboard
封奚泽优2 小时前
使用Python进行函数作画
开发语言·python
fc&&fl2 小时前
大模型面试题总结
人工智能·python
databook2 小时前
稀疏表示与字典学习:让数据“瘦身”的魔法
python·机器学习·scikit-learn
Sheeep2 小时前
学习Pytest + Hypothesis——能帮你发现你自己都没想到的 bug
python·测试
站大爷IP3 小时前
用Python打造办公效率神器:从数据到文档的全流程自动化实践
python