|
| 1 | +When generating routes, the `OrmarCRUDRouter` will automatically tie into your database |
| 2 | +using your [ormar](https://collerek.github.io/ormar/) models. To use it, simply pass your ormar database model as the schema. |
| 3 | + |
| 4 | +## Simple Example |
| 5 | + |
| 6 | +Below is an example assuming that you have already imported and created all the required |
| 7 | +models. |
| 8 | + |
| 9 | +```python |
| 10 | +router = OrmarCRUDRouter( |
| 11 | + schema=MyOrmarModel, |
| 12 | + create_schema=Optional[MyPydanticCreateModel], |
| 13 | + update_schema=Optional[MyPydanticUpdateModel] |
| 14 | +) |
| 15 | + |
| 16 | +app.include_router(router) |
| 17 | +``` |
| 18 | + |
| 19 | +!!! note The `create_schema` should not include the *primary id* field as this be |
| 20 | +generated by the database. |
| 21 | + |
| 22 | +## Full Example |
| 23 | + |
| 24 | +```python |
| 25 | +# example.py |
| 26 | +import databases |
| 27 | +import ormar |
| 28 | +import sqlalchemy |
| 29 | +import uvicorn |
| 30 | +from fastapi import FastAPI |
| 31 | + |
| 32 | +from fastapi_crudrouter import OrmarCRUDRouter |
| 33 | + |
| 34 | +DATABASE_URL = "sqlite:///./test.db" |
| 35 | +database = databases.Database(DATABASE_URL) |
| 36 | +metadata = sqlalchemy.MetaData() |
| 37 | + |
| 38 | +app = FastAPI() |
| 39 | + |
| 40 | + |
| 41 | +@app.on_event("startup") |
| 42 | +async def startup(): |
| 43 | + await database.connect() |
| 44 | + |
| 45 | + |
| 46 | +@app.on_event("shutdown") |
| 47 | +async def shutdown(): |
| 48 | + await database.disconnect() |
| 49 | + |
| 50 | + |
| 51 | +class BaseMeta(ormar.ModelMeta): |
| 52 | + metadata = metadata |
| 53 | + database = database |
| 54 | + |
| 55 | + |
| 56 | +def _setup_database(): |
| 57 | + # if you do not have the database run this once |
| 58 | + engine = sqlalchemy.create_engine(DATABASE_URL) |
| 59 | + metadata.drop_all(engine) |
| 60 | + metadata.create_all(engine) |
| 61 | + return engine, database |
| 62 | + |
| 63 | + |
| 64 | +class Potato(ormar.Model): |
| 65 | + class Meta(BaseMeta): |
| 66 | + pass |
| 67 | + |
| 68 | + id = ormar.Integer(primary_key=True) |
| 69 | + thickness = ormar.Float() |
| 70 | + mass = ormar.Float() |
| 71 | + color = ormar.String(max_length=255) |
| 72 | + type = ormar.String(max_length=255) |
| 73 | + |
| 74 | + |
| 75 | +app.include_router( |
| 76 | + OrmarCRUDRouter( |
| 77 | + schema=Potato, |
| 78 | + prefix="potato", |
| 79 | + ) |
| 80 | +) |
| 81 | + |
| 82 | +if __name__ == "__main__": |
| 83 | + uvicorn.run("example:app", host="127.0.0.1", port=5000, log_level="info") |
| 84 | +``` |
0 commit comments