当前位置:   article > 正文

使用python库uvicorn替代Nginx发布Vue3项目_python uvicorn

python uvicorn

目录

一、Vue3项目打包

二、将打包文件放到python项目

三、配置uvicorn服务

四、启动服务


【SpringBoot版传送门:使用SpringBoot替代Nginx发布Vue3项目_苍穹之跃的博客-CSDN博客

一、Vue3项目打包

(博主vue版本:3.2.44)

由于是要放在FastAPI中,接口服务和Web服务用的是同一个端口,所以我们给前端一个统一的URL前缀来区分前端页面和后端接口。比如:/admin;配置方式如下:在src/router文件夹下找到路由文件,注意要用history模式,不要用哈希。 

至于打包,就跟平时打包到nginx一样的去打包就行了。(不要添加base参数,画蛇添足!) 

二、将打包文件放到python项目

在python项目中新建文件夹static,然后将打包好的vue包复制进去。

三、配置uvicorn服务

新建api_service.py文件作为入口类

①静态文件映射

②配置VueRouter路由的反向代理

 

③强制让JS文件的MIME类型为application/javascript

  

完整代码如下↓↓↓

  1. import uvicorn
  2. from fastapi import FastAPI, Request
  3. from fastapi.staticfiles import StaticFiles
  4. from starlette.middleware.base import BaseHTTPMiddleware
  5. from starlette.responses import HTMLResponse
  6. app = FastAPI()
  7. app.mount("/", StaticFiles(directory="static"), name="/")
  8. # 静态文件代理
  9. class RedirectToIndexMiddleware(BaseHTTPMiddleware):
  10. async def dispatch(self, request: Request, call_next):
  11. # 排除静态文件
  12. if not request.url.path.endswith((".js", ".css", ".png", ".ico")):
  13. # 只拦截指定前缀
  14. if request.url.path.startswith("/admin/") or request.url.path == "/admin":
  15. return HTMLResponse(content=request.app.index_html, status_code=200)
  16. response = await call_next(request)
  17. return response
  18. # 读取index.html
  19. with open("static/index.html", encoding='utf-8') as f:
  20. app.index_html = f.read()
  21. # 添加中间件
  22. app.add_middleware(RedirectToIndexMiddleware)
  23. # 自定义JS文件的MIME类型为application/javascript
  24. @app.middleware("http")
  25. async def override_static_file_mimetype(request, call_next):
  26. response = await call_next(request)
  27. if request.url.path.endswith((".js")):
  28. response.headers["content-type"] = "application/javascript"
  29. return response
  30. # 添加中间件
  31. app.add_middleware(RedirectToIndexMiddleware)
  32. if __name__ == "__main__":
  33. uvicorn.run(app, host="0.0.0.0", port=8000)

四、启动服务

 浏览器访问:http://localhost:8000/admin

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/50022
推荐阅读
相关标签
  

闽ICP备14008679号