fastapi-返回静态文件 和 设置响应状态码

fast-api 返回文件和 设置响应状态码

import hashlib
import json
import logging.config
import os
import uvicorn
from fastapi import FastAPI, Query, Request, HTTPException
from typing import Dict, Any
from common.mod_north1_north2 import mod_north_xml
from fastapi.responses import FileResponse


@app.get("/static/{filename}", tags=["此处是接口说明"])
async def static_file(request: Request, filename: str):
    """
    :param request:
    :param filename:文件名
    :return:静态文件.xml
    """
    # 获取请求头信息
    file_path = fr'{os.getcwd().split("guduoduo_cloud_index_platform")[0]}guduoduo_cloud_index_platform\static\{filename}'
    req_header_IfNoneMatch = request.headers.get("If-None-Match", "")

    if not os.path.exists(file_path):
        data = {"message": "Data not exists!!!"}
        status_code = 404
        raise HTTPException(status_code=status_code, detail=data.get("message"))
    else:
        file_content = open(file_path, "rb").read()
        Etag = f"""W/'{hashlib.md5(file_content).hexdigest()}'"""
        headers = {
            'Etag': Etag,
        }
        # 数据一致,没有修改
        if req_header_IfNoneMatch == Etag:
            data = {"message": "Data consistent"}
            status_code = 304
            raise HTTPException(status_code=status_code, detail=data.get("message"))
        else:
            return FileResponse(file_path, headers=headers)

你可能感兴趣的:(后端-fastapi,fastapi)