Sanic 简介
说到 Python Web 框架, 你可能会想到 Flask、Django、Tornado、FastAPI等等。
这里向大家介绍另一个高效的异步Python Web 框架 —— Sanic。
Sanic 的使用和 Flask 非常相似,有 Flask 基础的童鞋可以很快掌握这个框架。
Sanic 最大的特色是支持 异步 方式处理并发请求,在开发中可以使用 async、await 关键字实现非阻塞响应请求。
Sanic 特性
直接支持生产环境部署
高度可扩展
内置快速网络服务器
具有异步支持
使用 Redoc、Swagger 的 OpenAPI 文档
CORS 保护等
安装Sanic
Python安装第三方模块都是利用pip工具进行安装,这里也不例外,首先进入上一步我们新建的 python3.6 虚拟环境,然后安装:
# 安装Sanic,请先使用 source activate python36 进入虚拟环境
pip install sanic
# 如果不想使用uvloop和ujson 可以这样安装
SANIC_NO_UVLOOP=true SANIC_NO_UJSON=true pip install sanic通过上面的命令,你就可以在 python3.6 虚拟环境中安装Sanic以及其依赖的第三方库了,若想查看Sanic是否已经正确安装,可以进入终端下对应的虚拟环境,启动Python解释器,导入Sanic库:
python
>>>
>>> import sanic如果没有出现错误,就说明你已经正确地安装了Sanic,请继续阅读下一节,了解下如何利用Sanic来构建一个Web项目吧。
第一个程序
我们将正式使用Sanic来构建一个web项目,让我们踏出第一步,利用Sanic来编写一个返回Hello World!字符串的服务程序。
新建一个文件夹sanicweb:
$ mkdir sanicweb
$ cd sanicweb/
$ pwd
/Users/junxi/pyenv/sanicweb创建一个sanic例子,保存为 main.py :
from sanic import Sanic
from sanic.response import text
app = Sanic()
@app.route("/")
async def index(request):
return text('Hello World!')
if __name__ == "__main__":
app.run(host="0.0.0.0", port=9000)运行main.py,然后访问地址http://127.0.0.1:9000/
$ curl -X GET http://127.0.0.1:9000/
Hello World!这样我们就完成了第一个sanic例子。
文件上传
首先,创建一个Sanic应用,并添加一个用于文件上传的路由。
以下是一个简单的文件上传服务器的代码示例:
upload.py
from sanic import Sanic
from sanic.response import json, file
from sanic.request import Request
from sanic.handlers import ErrorHandler
from sanic.exceptions import ServerError, ServerError, NotFound, Unauthorized
app = Sanic("FileUploadApp")
@app.route("/upload", methods=["POST"])
async def file_upload(request: Request):
file = request.files.get("file")
if not file:
return json({"error": "No file provided"}, status=400)
file_path = f"./uploads/{}"
with open(file_path, "wb") as f:
f.write(file.body)
return json({"message": f"File {} uploaded successfully", "path": file_path})
# 错误处理
error_handler = ErrorHandler()
error_handler.add(ServerError, "Internal Server Error")
error_handler.add(NotFound, "Not Found")
error_handler.add(Unauthorized, "Unauthorized")
app.add_exception_handler(ServerError, error_handler.handle_server_error)
app.add_exception_handler(NotFound, error_handler.handle_not_found)
app.add_exception_handler(Unauthorized, error_handler.handle_unauthorized)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True)在这个示例中,我们定义了一个名为 /upload 的POST路由,用于处理文件上传。
我们使用 request.files.get("file") 来获取上传的文件,并将其保存到服务器的 ./uploads/ 目录下。确保在运行服务器之前创建这个目录,否则可能会遇到文件保存错误。
要上传文件,你可以使用 curl 命令行工具或者任何支持文件上传的HTTP客户端。以下是使用 curl 上传文件的示例命令:
curl -X POST -F "file=@/path/to/your/file.txt" http://localhost:8000/upload请确保替换 /path/to/your/file.txt 为你想要上传的文件的实际路径。
我们创建一个用来上传的Form表单保存为 uploadfile.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<h1>Upload a file</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" required>
<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html>这个HTML文件定义了一个表单,它使用 POST 方法将文件发送到 /upload,这是你的Sanic服务器监听的地址和端口。enctype="multipart/form-data" 是必须的,因为它告诉浏览器以一种可以传输文件数据的方式编码表单。
如果你调试到服务器里,你会发现,sanic 只支持两种类型的 Content-Type:
application/x-www-form-urlencoded
multipart/form-data
将这个HTML文件放在你的服务器可以访问的目录下,然后在浏览器中打开它。用户可以通过点击 "Upload File" 按钮来上传文件。
















