Python?搭建?FastAPI?項(xiàng)目的詳細(xì)過程
一般網(wǎng)上的文章都是以腳本的方式寫Demor的,沒找到自己想要的那種項(xiàng)目結(jié)構(gòu)型的示例(類似Java SpringBoot 創(chuàng)建 Model,通過 pom 進(jìn)行關(guān)聯(lián)配置的那種)
看了一些源碼,再結(jié)合自己的想法,建了一個簡單的示例, 用 Python 做接口服務(wù)的項(xiàng)目搭建,僅供參考
代碼結(jié)構(gòu)說明
VipQA │ .env # 環(huán)境變量配置文件 │ app_init.py # 我用它來放了項(xiàng)目初始化代碼 │ main.py # 主程序,用來啟動項(xiàng)目 │ requirements.txt # 項(xiàng)目依賴包 pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple 進(jìn)行安裝 │ settings.py # 用來將 .env 里的變更值取出來。 Python 設(shè)置環(huán)境變量方法(https://www.cnblogs.com/vipsoft/p/17677020.html) │ __init__.py # 目前沒放代碼 │ ├─db # 里面放了初始化數(shù)據(jù)庫的腳本 │ └─ build_nodes.py │ ├─routers # 路由目錄,相當(dāng)于 Java 里的 Controller │ │ node_router.py # neo4j 節(jié)點(diǎn)接口,用來處理節(jié)點(diǎn)相關(guān)的接口方法 │ └─ __init__.py # 路由配置,把目錄下的各模塊路由注冊到 API 里面 │ ├─service # 業(yè)務(wù)邏輯處理,參考JAVA,供 Controller 調(diào)用 │ node_service.py # neo4j 節(jié)點(diǎn)服務(wù),處理節(jié)點(diǎn)邏輯 │ __init__.py # 目前空 │ ├─static # 靜態(tài)資源目錄 │ 404.html # URL地址不存在時,顯示這個頁面 │ index.html # 默認(rèn)首頁 │ └─utils # 工具類 │ neo4j_provider.py # neo4j 連接工具 └─ __init__.py # 目前空
主程序代碼
requirements.txtpip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
#pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple # 知識圖譜依賴包 neo4j==5.10.0 # async web framework # web 服務(wù)器 uvicorn==0.23.2 # 代碼框架 fastapi==0.101.1 # 環(huán)境配置 .env 使用依賴包 python-dotenv==0.20.0 # 命令行、控制臺,返回內(nèi)容,字體變顏色 colorama==0.4.4
.env 環(huán)境變量配置文件
# app APP_HOST=127.0.0.1 APP_PORT=8000 # neo4j NEO4J_URI=neo4j://172.16.3.64:7687 NEO4J_USER=neo4j NEO4J_PASSWORD=password NEO4J_VERSION=5 NEO4J_DATABASE=neo4j NEO4J_PORT=8080
settings.py
變量設(shè)置一般有兩種,一種取文件里的,還有是取系統(tǒng)的環(huán)境變量,詳見:Python 設(shè)置環(huán)境變量方法
from dotenv import dotenv_values from typing import List dotenv_config = dotenv_values('.env') class Settings: BACKEND_CORS_ORIGINS: List = ['*'] # APP APP_HOST = dotenv_config.get("APP_HOST", "127.0.0.1") APP_PORT = int(dotenv_config.get("APP_PORT", 8000)) # Neo4j NEO4J_URI = dotenv_config.get("NEO4J_URI", "neo4j://172.16.3.64:7687") NEO4J_USER = dotenv_config.get("NEO4J_USER", "neo4j") NEO4J_PASSWORD = dotenv_config.get("NEO4J_PASSWORD", "password") NEO4J_VERSION = dotenv_config.get("NEO4J_VERSION", "5") NEO4J_DATABASE = dotenv_config.get("NEO4J_DATABASE", "neo4j") NEO4J_PORT = int(dotenv_config.get("NEO4J_PORT", 8080)) settings = Settings()
app_init.py
項(xiàng)目啟動
import time import logging import os from settings import settings from starlette.middleware.cors import CORSMiddleware from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, FileResponse from fastapi.staticfiles import StaticFiles from routers import api_router # 創(chuàng)建 FastAPI 實(shí)類,供 main.py 調(diào)用 def create_application() -> FastAPI: # 等待其他組件啟動完成 time.sleep(3) application = FastAPI( title="FastAPI結(jié)構(gòu)示例", # 文檔標(biāo)題 description="使用 FastAPI 實(shí)現(xiàn) Node4j 基礎(chǔ)功能. ??", # 文檔簡介 version="0.0.1", # 文檔版本號 # docs_url=None, redoc_url=None, # 配置離線文檔,None 后,http://127.0.0.1:8000/docs 就不能再訪問了 ) # api_router => routers/__init__.py 里面 的 api_router = APIRouter() # 訪問接口時,所有的接口前面都要加上 api 前綴,相當(dāng)于 Java 里的 server.servlet.context-path: /api 配置 application.include_router(api_router, prefix='/api') # 后面帶 API 的就表示接口,路由到 routers 目錄下找對應(yīng)的接口,相當(dāng)于 Java 的 Controller, register_middleware(application) # 支付跨域 register_static(application) # 添加HTML靜態(tài)頁面配置 register_event(application) # 添加項(xiàng)目事件 return application def register_static(app): # 如果需要使用靜態(tài)文件, 可以使用 StaticFiles,將它掛載到應(yīng)用程序中。 html_path = os.path.dirname(os.path.abspath(__file__)) app.mount('/static', StaticFiles(directory=os.path.join(html_path, 'static'))) @app.get('/') async def read_index(): # 跳轉(zhuǎn)到 static 下面的 index.html 文件 return FileResponse(os.path.join(html_path, 'static', 'index.html')) @app.exception_handler(404) async def not_found(request: Request, exc): accept = request.headers.get('accept') if not accept: # 返回JSON 格式 return JSONResponse(content={'error': "Not found"}, status_code=exc.status_code) if exc.status_code == 404 and 'text/html' in accept: # 404 跳轉(zhuǎn)到 static 下面的 404.html 頁面 return FileResponse(os.path.join(html_path, 'static', '404.html')) else: return JSONResponse(content={'error': "Not found"}, status_code=exc.status_code) # 支持跨域 def register_middleware(application): if settings.BACKEND_CORS_ORIGINS: application.add_middleware( CORSMiddleware, allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) def register_event(app): @app.on_event("startup") async def startup_event(): logging.info("App Startup") @app.on_event("shutdown") async def shutdown_event(): logging.info("App Shutdown")
接口路由
routers/init.py
from fastapi import APIRouter from . import node_router api_router = APIRouter() # tags 顯示在 Swagger 上的標(biāo)題 # 這邊的 prefix 相當(dāng)于 java 里的 Controller 上的 @RequestMapping("/node") api_router.include_router(node_router.router, tags=['Node'], prefix='/node')
node_router.py
from fastapi import APIRouter, status from fastapi.responses import JSONResponse router = APIRouter() # 定義一個根路由 @router.get("/add") def add_node(): # TODO 往 neo4j 里創(chuàng)建新的節(jié)點(diǎn) data = { 'code': 0, 'message': '', 'data': 'add success' } return JSONResponse(content=data, status_code=status.HTTP_200_OK)
附JAVA,接口前綴配置
所有接口前面的前綴
# 開發(fā)環(huán)境配置 server: # 服務(wù)器的HTTP端口,默認(rèn)為8080 port: 8088 servlet: # 應(yīng)用的訪問路徑 context-path: /api
業(yè)務(wù)接口上的前綴(所有類方法前)
@RequestMapping("/node") public class NodeController{ @PostMapping("/add") public void add(){ } }
源碼地址:https://gitee.com/VipSoft/VipQA
到此這篇關(guān)于Python 搭建 FastAPI 項(xiàng)目的文章就介紹到這了,更多相關(guān)Python FastAPI 項(xiàng)目內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python Json數(shù)據(jù)文件操作原理解析
這篇文章主要介紹了Python Json數(shù)據(jù)文件操作原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-05-05Python實(shí)現(xiàn)串口通信(pyserial)過程解析
這篇文章主要介紹了Python實(shí)現(xiàn)串口通信(pyserial)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-09-09PHP魔術(shù)方法__ISSET、__UNSET使用實(shí)例
這篇文章主要介紹了PHP魔術(shù)方法__ISSET、__UNSET使用實(shí)例,本文直接給出代碼示例,需要的朋友可以參考下2014-11-11手把手教你實(shí)現(xiàn)Python重試超時裝飾器
這篇文章主要為大家介紹了實(shí)現(xiàn)Python重試超時裝飾器教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2023-05-05pandas dataframe統(tǒng)計(jì)填充空值方式
這篇文章主要介紹了pandas dataframe統(tǒng)計(jì)填充空值方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02Django集成Celery實(shí)現(xiàn)高效的異步任務(wù)處理的全過程
Django?作為一個強(qiáng)大的?Python?Web?框架,可以通過集成?Celery?這一異步任務(wù)隊(duì)列來優(yōu)化這些任務(wù)的處理,本文將深入探討如何在?Django?項(xiàng)目中集成?Celery,包括?Celery?的基本配置、定義任務(wù)、以及監(jiān)控任務(wù)執(zhí)行,需要的朋友可以參考下2023-11-11Python性能分析工具pyinstrument提高代碼效率
今天分享一個超級實(shí)用的 Python 性能分析工具 pyinstrument ,可以快速找到代碼運(yùn)行最慢的部分,幫助提高代碼的性能。支持 Python 3.7+ 且能夠分析異步代碼,僅需一條命令即可顯示具體代碼的耗時。經(jīng)常寫 Python 的小伙伴一定要用一下2021-09-09