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

相关推荐
Csvn11 小时前
🌟 LangChain 30 天保姆级教程 · Day 13|OutputParser 进阶!让 AI 输出自动转为结构化对象,并支持自动重试!
python·langchain
cch891811 小时前
Python主流框架全解析
开发语言·python
sg_knight12 小时前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财12 小时前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
张張40812 小时前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_4235339912 小时前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python
Ricky111zzz12 小时前
leetcode学python记录1
python·算法·leetcode·职场和发展
小白学大数据12 小时前
Selenium+Python 爬虫:动态加载头条问答爬取
爬虫·python·selenium
Hui Baby13 小时前
springboot读取配置文件
后端·python·flask
阿Y加油吧13 小时前
回溯法经典难题:N 皇后问题 深度解析 + 二分查找入门(搜索插入位置)
开发语言·python