当前位置:   article > 正文

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

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号