89 lines
2.4 KiB
Python
89 lines
2.4 KiB
Python
# sample as https://github.com/mongodb-developer/mongodb-with-fastapi/blob/master/app.py
|
|
import os
|
|
from fastapi import FastAPI, Body, HTTPException, status
|
|
from fastapi.responses import JSONResponse
|
|
from fastapi.encoders import jsonable_encoder
|
|
from pydantic import BaseModel, Field, EmailStr
|
|
from bson import ObjectId
|
|
from typing import Optional, List
|
|
import motor.motor_asyncio
|
|
from pydantic.types import Json
|
|
from config.config import settings
|
|
|
|
|
|
async def get_mongo():
|
|
client = motor.motor_asyncio.AsyncIOMotorClient(settings.MONGODB_URL)
|
|
db = client.jump
|
|
return db
|
|
|
|
|
|
class PyObjectId(ObjectId):
|
|
@classmethod
|
|
def __get_validators__(cls):
|
|
yield cls.validate
|
|
|
|
@classmethod
|
|
def validate(cls, v):
|
|
if not ObjectId.is_valid(v):
|
|
raise ValueError("Invalid objectid")
|
|
return ObjectId(v)
|
|
|
|
@classmethod
|
|
def __modify_schema__(cls, field_schema):
|
|
field_schema.update(type="string")
|
|
|
|
|
|
class PlatformModel(BaseModel):
|
|
id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
|
|
moduleId: int = Field(...)
|
|
platformAlias: str = Field(...)
|
|
iconRes: str = Field(...)
|
|
gameNum: int = Field(...)
|
|
filter: list = []
|
|
countryFilter: bool
|
|
|
|
class Config:
|
|
allow_population_by_field_name = True
|
|
arbitrary_types_allowed = True
|
|
json_encoders = {ObjectId: str}
|
|
schema_extra = {
|
|
"example": {
|
|
"moduleId":
|
|
4,
|
|
"platformAlias":
|
|
'Steam',
|
|
"iconRes":
|
|
'http://switch-cdn.vgjump.com/869270335915032576',
|
|
"gameNum":
|
|
759,
|
|
"filter": [{
|
|
'termsId': 26,
|
|
'terms': '精选'
|
|
}, {
|
|
'termsId': 27,
|
|
'terms': '全部'
|
|
}],
|
|
"countryFilter":
|
|
None
|
|
}
|
|
}
|
|
|
|
|
|
class UpdateStudentModel(BaseModel):
|
|
name: Optional[str]
|
|
email: Optional[EmailStr]
|
|
course: Optional[str]
|
|
gpa: Optional[float]
|
|
|
|
class Config:
|
|
arbitrary_types_allowed = True
|
|
json_encoders = {ObjectId: str}
|
|
schema_extra = {
|
|
"example": {
|
|
"name": "Jane Doe",
|
|
"email": "jdoe@example.com",
|
|
"course": "Experiments, Science, and Fashion in Nanophotonics",
|
|
"gpa": "3.0",
|
|
}
|
|
}
|