报错:UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0x89 in position 0: invalid start byte 解决办法
from fastapi import FastAPI,Response
import uvicorn
app=FastAPI()
@app.get("/{path}")
def index(path):
print(path)
with open(f"WebServer_html/{path}","r",encoding="UTF-8") as f:
content = f.read()
return Response(content=content)
uvicorn.run(app,host="192.168.82.163",port=9999)
运行后出错:
更改成gbk格式也不行
from fastapi import FastAPI,Response
import uvicorn
app=FastAPI()
@app.get("/{path}")
def index(path):
print(path)
with open(f"WebServer_html/{path}","r",encoding="GBK") as f:
content = f.read()
return Response(content=content)
uvicorn.run(app,host="192.168.82.163",port=9999)
我试了网上的各种方法:包括如下
- 在代码前加上两行,实操不行
#-*- coding : utf-8-*-
# coding:utf-8
from fastapi import FastAPI,Response
import uvicorn
app=FastAPI()
@app.get("/{path}")
def index(path):
print(path)
with open(f"WebServer_html/{path}","r",encoding="UTF-8") as f:
content = f.read()
return Response(content=content)
uvicorn.run(app,host="192.168.82.163",port=9999)
- 用编码格式 “unicode_escape”
运行确实不出错了,但是运行后中文变成乱码,不行
from fastapi import FastAPI,Response
import uvicorn
app=FastAPI()
@app.get("/{path}")
def index(path):
print(path)
with open(f"WebServer_html/{path}","r",encoding="unicode_escape") as f:
content = f.read()
return Response(content=content)
uvicorn.run(app,host="192.168.82.163",port=9999)
解决办法如下:
# with open(f"WebServer_html/{path}","r",encoding="UTF-8") as f:
with open(f"WebServer_html/{path}","r",encoding="UTF-8",errors='ignore') as f:
在encoding参数后面加上,errors参数并设置为’ignore’。亲测有效