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

相关推荐
敲敲敲-敲代码19 分钟前
【PyCharm- Python- ArcGIS】:安装一个和 ArcGIS 不冲突的独立 Python让PyCharm 使用 (解决全过程记录)
python·arcgis·pycharm
猿榜编程37 分钟前
python基础-requests结合AI实现自动化数据抓取
开发语言·python·自动化
一键三联啊42 分钟前
【FastJSON】的parse与parseObject
linux·前端·python
shimly1234562 小时前
(done) 吴恩达版提示词工程 8. 聊天机器人 (聊天格式设计,上下文内容,点餐机器人)
人工智能·python·机器人
站大爷IP2 小时前
基于PySide6的聚合翻译软件设计与实现
python
灏瀚星空2 小时前
从基础到实战的量化交易全流程学习:1.2 金融市场基础
笔记·python·信息可视化·系统架构·开源
用户27784491049933 小时前
Python打造Excel记账模板,摸鱼时间也能轻松理财
人工智能·python
闲人编程3 小时前
OpenCV图像矩与形状匹配完全指南
python·opencv·图像识别
一个天蝎座 白勺 程序猿3 小时前
Python爬虫(8)Python数据存储实战:JSON文件读写与复杂结构化数据处理指南
爬虫·python·json
q_q王4 小时前
dify对接飞书云文档,并且将图片传入飞书文档
python·大模型·飞书·dify·智能体·图片展示