mirror of
				https://github.com/fastapi-users/fastapi-users.git
				synced 2025-11-04 14:45:50 +08:00 
			
		
		
		
	* docs(examples): full examples use lifespan instead of on_startup for database initialization * Update beanie.md Replaced the annotations on the notes that I missed
		
			
				
	
	
		
			63 lines
		
	
	
		
			1.4 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
			
		
		
	
	
			63 lines
		
	
	
		
			1.4 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
from contextlib import asynccontextmanager
 | 
						|
 | 
						|
from beanie import init_beanie
 | 
						|
from fastapi import Depends, FastAPI
 | 
						|
 | 
						|
from app.db import User, db
 | 
						|
from app.schemas import UserCreate, UserRead, UserUpdate
 | 
						|
from app.users import (
 | 
						|
    SECRET,
 | 
						|
    auth_backend,
 | 
						|
    current_active_user,
 | 
						|
    fastapi_users,
 | 
						|
    google_oauth_client,
 | 
						|
)
 | 
						|
 | 
						|
 | 
						|
@asynccontextmanager
 | 
						|
async def lifespan(app: FastAPI):
 | 
						|
    await init_beanie(
 | 
						|
        database=db,
 | 
						|
        document_models=[
 | 
						|
            User,
 | 
						|
        ],
 | 
						|
    )
 | 
						|
    yield
 | 
						|
 | 
						|
 | 
						|
app = FastAPI(lifespan=lifespan)
 | 
						|
 | 
						|
app.include_router(
 | 
						|
    fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]
 | 
						|
)
 | 
						|
app.include_router(
 | 
						|
    fastapi_users.get_register_router(UserRead, UserCreate),
 | 
						|
    prefix="/auth",
 | 
						|
    tags=["auth"],
 | 
						|
)
 | 
						|
app.include_router(
 | 
						|
    fastapi_users.get_reset_password_router(),
 | 
						|
    prefix="/auth",
 | 
						|
    tags=["auth"],
 | 
						|
)
 | 
						|
app.include_router(
 | 
						|
    fastapi_users.get_verify_router(UserRead),
 | 
						|
    prefix="/auth",
 | 
						|
    tags=["auth"],
 | 
						|
)
 | 
						|
app.include_router(
 | 
						|
    fastapi_users.get_users_router(UserRead, UserUpdate),
 | 
						|
    prefix="/users",
 | 
						|
    tags=["users"],
 | 
						|
)
 | 
						|
app.include_router(
 | 
						|
    fastapi_users.get_oauth_router(google_oauth_client, auth_backend, SECRET),
 | 
						|
    prefix="/auth/google",
 | 
						|
    tags=["auth"],
 | 
						|
)
 | 
						|
 | 
						|
 | 
						|
@app.get("/authenticated-route")
 | 
						|
async def authenticated_route(user: User = Depends(current_active_user)):
 | 
						|
    return {"message": f"Hello {user.email}!"}
 |