Browse Source

fastapi+minio:v3
这是添加了JWT鉴权的版本

clxHardstudy 1 year ago
parent
commit
2546763ef5
5 changed files with 61 additions and 37 deletions
  1. 1 4
      app/main.py
  2. 0 6
      config/config.py
  3. 30 1
      models/model.py
  4. 27 25
      routers/files.py
  5. 3 1
      test_unit.py

+ 1 - 4
app/main.py

@@ -1,11 +1,8 @@
 from fastapi import FastAPI
-from pydantic import BaseModel, ValidationError
-from typing import List, Optional
-from datetime import datetime
-from typing import Dict
 from routers import items,files
 import uvicorn
 
+
 app = FastAPI()
 
 app.include_router(files.router)

+ 0 - 6
config/config.py

@@ -1,9 +1,3 @@
-"""
-    encoding: UTF-8
-    @author:clx
-    @file:config.py.py
-    @time:2023/5/31 12:48
-"""
 import json
 from minio import Minio
 

+ 30 - 1
models/model.py

@@ -4,7 +4,7 @@
     @file:model.py
     @time:2023/5/30 6:29
 """
-from typing import Optional
+from typing import Optional, Union
 
 from pydantic import BaseModel
 
@@ -12,3 +12,32 @@ from pydantic import BaseModel
 class Item(BaseModel):
     id: int
     name: str
+
+class Token(BaseModel):
+    access_token: str
+    token_type: str
+
+
+class TokenData(BaseModel):
+    username: Union[str, None] = None
+
+
+class User(BaseModel):
+    username: str
+    email: Union[str, None] = None
+    full_name: Union[str, None] = None
+    disabled: Union[bool, None] = None
+
+
+class UserInDB(User):
+    hashed_password: str
+
+fake_users_db = {
+    "johndoe": {
+        "username": "johndoe",
+        "full_name": "John Doe",
+        "email": "johndoe@example.com",
+        "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
+        "disabled": False,
+    }
+}

+ 27 - 25
routers/files.py

@@ -1,30 +1,17 @@
-"""
-    encoding: UTF-8
-    @author:clx
-    @file:files.py.py
-    @time:2023/5/30 6:08
-"""
-import json
 import os
-import random
-import time
 import re
-import aiofiles
-from fastapi import APIRouter, File, UploadFile, Request, Response, status, HTTPException
-from fastapi.responses import FileResponse, StreamingResponse
-from typing import Annotated, List
-from minio import Minio
+import time
+from datetime import datetime, timedelta
 from io import BytesIO
+from fastapi import Depends, FastAPI, HTTPException, status, UploadFile, APIRouter, File
+from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
+from starlette.responses import StreamingResponse
 from config import config
+from models.model import *
+from utils.jwt import authenticate_user, ACCESS_TOKEN_EXPIRE_MINUTES, create_access_token, get_current_active_user
+
+
 
-"""
-    minio_client = Minio(
-    "127.0.0.1:9000",
-    access_key="minioadmin",
-    secret_key="minioadmin",
-    secure=False
-)
-"""
 
 # 创建minio对象
 minio_class = config.MinioOperate()
@@ -35,10 +22,25 @@ minio_class.create_bucket()
 
 router = APIRouter()
 
+@router.post("/token", response_model=Token)
+async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
+    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
+    if not user:
+        raise HTTPException(
+            status_code=status.HTTP_401_UNAUTHORIZED,
+            detail="Incorrect username or password",
+            headers={"WWW-Authenticate": "Bearer"},
+        )
+    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
+    access_token = create_access_token(
+        data={"sub": user.username}, expires_delta=access_token_expires
+    )
+    return {"access_token": access_token, "token_type": "bearer"}
+
 
 # minio ?上传文件时在重复时,需要修改文件名
 @router.post("/file")
-async def create_file(file: UploadFile = File(...)):
+async def create_file(file: UploadFile = File(...),current_user: User = Depends(get_current_active_user)):
     timestamp = str(time.time())
     uid = re.sub(r"\.", "", timestamp)
     front, ext = os.path.splitext(file.filename)
@@ -80,10 +82,10 @@ async def download_file(uid: str):
 
 # 删除
 @router.delete("/file/{uid}")
-async def delete_file(uid: str):
+async def delete_file(uid: str,current_user: User = Depends(get_current_active_user)):
     try:
         minio_client.get_object("file1", uid)
         minio_client.remove_object("file1", uid)
         return {"msg": "删除图片成功!", "status": 200}
     except:
-        return {"msg": "Not Found", "status": 404}
+        return {"msg": "Not Found", "status": 404}

+ 3 - 1
pytest.py → test_unit.py

@@ -1,17 +1,19 @@
 """
     encoding: UTF-8
     @author:clx
-    @file:pytest.py
+    @file:test_unit.py
     @time:2023/5/30 20:06
 """
 import uvicorn
 from fastapi import FastAPI
 from fastapi.testclient import TestClient
+import pytest
 
 app = FastAPI()
 
 client = TestClient(app)
 
+
 def test_create_file():
     response = client.get("/item/res")
     assert response.status_code == 200