zhanymkanov / fastapi-best-practices

FastAPI Best Practices and Conventions we used at our startup
9.4k stars 701 forks source link

How to start the project #23

Closed synapsedata closed 1 year ago

synapsedata commented 1 year ago

How should I start the project, docs says that main.py file will run the app but what will contain that main.py file and where will point?

Example how I did in a recent course uvicorn app:app --reload --host 0.0.0.0 --port 7070

app.py content: import fastapi as _fastapi import fastapi.security as _security import sqlalchemy.orm as _orm import schemas as _schemas import services as _services from typing import List from fastapi.middleware.cors import CORSMiddleware

app = _fastapi.FastAPI()

app.add_middleware( CORSMiddleware, allow_origins=[""], allow_credentials=True, allow_methods=[""], allow_headers=["*"] )

@app.post("/api/v1/users")
async def register_user(user: _schemas.UserRequest, db: _orm.Session = _fastapi.Depends(_services.get_db)): db_user = await _services.get_user_by_email(email=user.email, db=db) if db_user: raise _fastapi.HTTPException(status_code=400, detail="Email already exists")

create user and return token

db_user = await _services.create_user(user=user, db=db)
return await _services.create_token(user=db_user)

@app.post("/api/v1/login") async def login_user( form_data: _security.OAuth2PasswordRequestForm = _fastapi.Depends(), db: _orm.Session = _fastapi.Depends(_services.get_db)): db_user = await _services.login(email=form_data.username, password=form_data.password, db=db) if not db_user: raise _fastapi.HTTPException(status_code=401, detail="Wrong login credentials") return await _services.create_token(db_user)

In this case point to app.py which is llinked to services, so the question is how to structure the main.py in fastapi-best-practices, where should i point to?

Where this code (@app.post("/api/v1/users") and @app.post("/api/v1/login") ) should be, what namefile should have regarding to fastapi-best-practices?