-
First Check
Commit to Help
Example Codeimport uvicorn
import threading
from typing import Optional
from datetime import datetime
from passlib.context import CryptContext
from beanie import Document, init_beanie
from motor.motor_asyncio import AsyncIOMotorClient
from fastapi import FastAPI
lock = threading.Lock()
app = FastAPI()
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
class User(Document):
username: str
full_name: Optional[str] = None
email: Optional[str] = None
class Settings:
name = "users"
def __repr__(self) -> str:
return f"<User {self.username}>"
def __str__(self) -> str:
return self.username
def __hash__(self) -> int:
return hash(self.username)
def __eq__(self, other: object) -> bool:
if isinstance(other, User):
return self.username == other.username
return False
@property
def created(self) -> datetime:
return self.id.generation_time
@classmethod
async def by_username(cls, username: str) -> "User":
"""Get a user by username"""
return await cls.find_one(cls.username == username)
class UserPW(User):
password: str
def hash_password(password: str) -> str:
return pwd_context.hash(password.encode())
async def create_admin_user(
username: str = "test",
password: str = "test"
):
# lock not working, still create 4 users
with lock:
found_user = await User.by_username(username)
if found_user is not None:
print("admin user already exists, pass!")
else:
user = UserPW(
username=username,
password=password
)
hashed = hash_password(user.password)
user.password = hashed
await user.create()
return User(**user.dict())
async def init_db(app: FastAPI):
app.db = AsyncIOMotorClient("mongodb://test:test@127.0.0.1:27017/pml_dev?authSource=admin")
col = getattr(app.db, "pml_dev")
await init_beanie(col, document_models=[
User
])
@app.on_event("startup")
async def init():
# init database
await init_db(app)
# create admin user if not exists
await create_admin_user()
# create 4 duplicate users
# uvicorn main:app --host=0.0.0.0 --port 5000 --workers 4
# only create 1 user on single worker
# uvicorn main:app --host=0.0.0.0 --port 5000 Description
Operating SystemmacOS Operating System DetailsNo response FastAPI Version0.86.0 Python Version3.10 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
My recommendation is to not use In case you want to continue with your idea... You can use a redis lock, or file system lock. 👀 |
Beta Was this translation helpful? Give feedback.
-
yes, i will use |
Beta Was this translation helpful? Give feedback.
-
On
If you using docker, set the entrypoint to this bash script. |
Beta Was this translation helpful? Give feedback.
-
ok, i will use |
Beta Was this translation helpful? Give feedback.
My recommendation is to not use
startup
for this. Create a separate script for it, that runs beforeuvicorn
.In case you want to continue with your idea... You can use a redis lock, or file system lock. 👀