Sanic框架实现字体文件截取。
功能:输入要截取的字体,将字体文件切割生成新的文件。
用三层思想搭建一个Sanic项目,利用框架的蓝图将项目分为model层,controller层。
1.启动服务主文件main.py。
# coding:utf-8
from sanic import Sanic
from controller import webapi
app = Sanic("SanicWebApi")
#接口蓝图
app.blueprint(webapi)
#配置运行参数
app.run(host='127.0.0.1', port=8080, access_log=False)
2.Controller层,新建一个controller包并新建入口文件
__init__.py
from sanic import Blueprint
from .webapi import api
#API接口路径
webapi = Blueprint.group(api,url_prefix="/api")
webApi.py
import uuid
from sanic import Blueprint, response
from sanic import json, text
from models import InterceptFont
from utility import ResponseResult
api = Blueprint("webapi")
# 请求入口 --controller
@api.route("/getFont")
async def interceptFont(request):
text = request.args["inputText"][0]
font_name = request.args["fontName"][0]
font_tpyt = request.args["fontTypt"][0]
return_font_name = request.args["returnFontName"][0]
if return_font_name == "":
return_font_name = str(uuid.uuid4())
if font_name == "" or font_tpyt == "":
return json(ResponseResult.Error([],"字体名称或字体类型不可为空!"))
fontpath = InterceptFont(text,font_name,font_tpyt,return_font_name)
return await response.file_stream(
fontpath,
chunk_size = 1024,
filename = return_font_name+font_tpyt,
headers={'X-Serverd-By': 'YuanRenXue Python'}
)
3.Models层,新建一个models包
__init__.py
from .InterceptFontPackage import InterceptFont
interceptFontPackage.py
from fontTools import subset
from utility import readconfig
def InterceptFont(text,fontName,fontType,retName):
# 字体拆分
options = subset.Options()
con = readconfig.ReadConfig()
item = con.getConfigValue("config","font_file_path")
path = str(item).rstrip()+fontName
font = subset.load_font(path, options)
subsetter = subset.Subsetter(options)
subsetter.populate(text=text)
subsetter.subset(font)
# woff
options.flavor = 'woff'
font_path = 'fonts/'+retName+fontType
subset.save_font(font,font_path , options)
return font_path
4.返回状态封装
ResponseResult.py
import json
class ResponseResult:
def __init__(self):
self.status = 200
self.msg = "成功!"
self.response = []
self.success = False
def Success(self, response=[], msg="成功!"):
data = {"status": self.status, "msg": msg, "success": True, "response": response}
return data
def Error(self, response=[], msg="失败!"):
self.status = -1
data = {"status": self.status, "msg": msg, "success": False, "response": response}
return data
PS:简简单单的一个小功能,我也是刚用Sanic框架。不足之处,谅解谅解。。
这里学的超详细的API说明: