Python?搭建?FastAPI?項目的詳細過程
一般網(wǎng)上的文章都是以腳本的方式寫Demor的,沒找到自己想要的那種項目結(jié)構型的示例(類似Java SpringBoot 創(chuàng)建 Model,通過 pom 進行關聯(lián)配置的那種)
看了一些源碼,再結(jié)合自己的想法,建了一個簡單的示例, 用 Python 做接口服務的項目搭建,僅供參考
代碼結(jié)構說明

VipQA │ .env # 環(huán)境變量配置文件 │ app_init.py # 我用它來放了項目初始化代碼 │ main.py # 主程序,用來啟動項目 │ requirements.txt # 項目依賴包 pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple 進行安裝 │ settings.py # 用來將 .env 里的變更值取出來。 Python 設置環(huán)境變量方法(https://www.cnblogs.com/vipsoft/p/17677020.html) │ __init__.py # 目前沒放代碼 │ ├─db # 里面放了初始化數(shù)據(jù)庫的腳本 │ └─ build_nodes.py │ ├─routers # 路由目錄,相當于 Java 里的 Controller │ │ node_router.py # neo4j 節(jié)點接口,用來處理節(jié)點相關的接口方法 │ └─ __init__.py # 路由配置,把目錄下的各模塊路由注冊到 API 里面 │ ├─service # 業(yè)務邏輯處理,參考JAVA,供 Controller 調(diào)用 │ node_service.py # neo4j 節(jié)點服務,處理節(jié)點邏輯 │ __init__.py # 目前空 │ ├─static # 靜態(tài)資源目錄 │ 404.html # URL地址不存在時,顯示這個頁面 │ index.html # 默認首頁 │ └─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 服務器 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
變量設置一般有兩種,一種取文件里的,還有是取系統(tǒng)的環(huán)境變量,詳見:Python 設置環(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
項目啟動
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 實類,供 main.py 調(diào)用
def create_application() -> FastAPI:
# 等待其他組件啟動完成
time.sleep(3)
application = FastAPI(
title="FastAPI結(jié)構示例", # 文檔標題
description="使用 FastAPI 實現(xiàn) Node4j 基礎功能. ??", # 文檔簡介
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 前綴,相當于 Java 里的 server.servlet.context-path: /api 配置
application.include_router(api_router, prefix='/api') # 后面帶 API 的就表示接口,路由到 routers 目錄下找對應的接口,相當于 Java 的 Controller,
register_middleware(application) # 支付跨域
register_static(application) # 添加HTML靜態(tài)頁面配置
register_event(application) # 添加項目事件
return application
def register_static(app):
# 如果需要使用靜態(tài)文件, 可以使用 StaticFiles,將它掛載到應用程序中。
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 上的標題
# 這邊的 prefix 相當于 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é)點
data = {
'code': 0,
'message': '',
'data': 'add success'
}
return JSONResponse(content=data, status_code=status.HTTP_200_OK)
附JAVA,接口前綴配置
所有接口前面的前綴
# 開發(fā)環(huán)境配置
server:
# 服務器的HTTP端口,默認為8080
port: 8088
servlet:
# 應用的訪問路徑
context-path: /api業(yè)務接口上的前綴(所有類方法前)
@RequestMapping("/node")
public class NodeController{
@PostMapping("/add")
public void add(){
}
}源碼地址:https://gitee.com/VipSoft/VipQA
到此這篇關于Python 搭建 FastAPI 項目的文章就介紹到這了,更多相關Python FastAPI 項目內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
TensorFlow在MAC環(huán)境下的安裝及環(huán)境搭建
小編在論壇中看到很多朋友在尋找TensorFlow的環(huán)境搭建圖文步驟以及安裝的具體流程,在此小編給大家整理了一篇非常詳細的圖文流程,希望能夠幫助到你。2017-11-11
python中array數(shù)組添加一行或一列數(shù)據(jù)的具體實現(xiàn)
這篇文章主要給大家介紹了關于python中array數(shù)組添加一行或一列數(shù)據(jù)的具體實現(xiàn),最近經(jīng)常使用到數(shù)組方法,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2023-09-09
Python實現(xiàn)一個Git日志統(tǒng)計分析的小工具
這篇文章主要給大家介紹了關于利用Python如何實現(xiàn)一個Git日志統(tǒng)計分析小工具的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。2017-12-12
使用國內(nèi)鏡像源優(yōu)化pip install下載的方法步驟
在Python開發(fā)中,pip 是一個不可或缺的工具,用于安裝和管理Python包,然而,由于默認的PyPI服務器位于國外,國內(nèi)用戶在安裝依賴時可能會遇到下載速度慢、連接不穩(wěn)定等問題,所以本文將詳細介紹如何使用國內(nèi)鏡像源來加速pip install -r requirements.txt的過程2025-03-03
淺談Python類的__getitem__和__setitem__特殊方法
下面小編就為大家?guī)硪黄獪\談Python類的__getitem__和__setitem__特殊方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12

