fastapipython.md(檔案已創建)
| @@ -0,0 +1,65 @@ | |||
| 1 | + | FastAPI, a modern Python web framework, is often used with database modeling to create robust APIs. Here's how it's typically done: | |
| 2 | + | ||
| 3 | + | 1. Database Choice: | |
| 4 | + | FastAPI doesn't enforce a specific database. You can choose SQL (like PostgreSQL, MySQL, SQLite) or NoSQL databases. | |
| 5 | + | For SQL databases, SQLAlchemy is a common choice as an ORM (Object-Relational Mapper). | |
| 6 | + | SQLModel, created by the same author as FastAPI, is designed to work seamlessly with it. | |
| 7 | + | 2. Data Models: | |
| 8 | + | Pydantic: FastAPI uses Pydantic for data validation and serialization. You define data models using Pydantic, which are then used to validate incoming requests and structure responses. | |
| 9 | + | SQLModel: SQLModel extends Pydantic to define database tables directly as Python classes. This allows you to define both data structures and database schemas in one place. | |
| 10 | + | SQLAlchemy: If using SQLAlchemy, you define models that map to database tables. | |
| 11 | + | 3. Database Interaction: | |
| 12 | + | SQLAlchemy: With SQLAlchemy, you create an engine that connects to your database. Then you define sessions to interact with the database. | |
| 13 | + | SQLModel: SQLModel simplifies this process by providing its own engine and session management. | |
| 14 | + | You typically create a dependency that yields a database session for each request to ensure proper database interaction. | |
| 15 | + | 4. ORM vs. Raw SQL: | |
| 16 | + | ORMs like SQLAlchemy and SQLModel allow you to interact with databases using Python objects instead of writing raw SQL queries, making code more readable and maintainable. | |
| 17 | + | You can still use raw SQL if needed. | |
| 18 | + | 5. FastAPI Integration: | |
| 19 | + | FastAPI endpoints use Pydantic models to define request and response structures. | |
| 20 | + | You can inject database sessions as dependencies into your endpoints. | |
| 21 | + | FastAPI automatically generates API documentation based on your Pydantic models. | |
| 22 | + | 6. Example with SQLModel: | |
| 23 | + | ```Python | |
| 24 | + | ||
| 25 | + | from typing import Optional | |
| 26 | + | from fastapi import FastAPI, Depends | |
| 27 | + | from sqlmodel import Field, Session, SQLModel, create_engine, select | |
| 28 | + | ||
| 29 | + | class Hero(SQLModel, table=True): | |
| 30 | + | id: Optional[int] = Field(default=None, primary_key=True) | |
| 31 | + | name: str | |
| 32 | + | secret_name: str | |
| 33 | + | age: Optional[int] = Field(default=None, index=True) | |
| 34 | + | ||
| 35 | + | sqlite_file_name = "database.db" | |
| 36 | + | sqlite_url = f"sqlite:///{sqlite_file_name}" | |
| 37 | + | connect_args = {"check_same_thread": False} | |
| 38 | + | engine = create_engine(sqlite_url, connect_args=connect_args) | |
| 39 | + | ||
| 40 | + | def create_db_and_tables(): | |
| 41 | + | SQLModel.metadata.create_all(engine) | |
| 42 | + | ||
| 43 | + | def get_session(): | |
| 44 | + | with Session(engine) as session: | |
| 45 | + | yield session | |
| 46 | + | ||
| 47 | + | SessionDep = Depends(get_session) | |
| 48 | + | app = FastAPI() | |
| 49 | + | ||
| 50 | + | @app.on_event("startup") | |
| 51 | + | def on_startup(): | |
| 52 | + | create_db_and_tables() | |
| 53 | + | ||
| 54 | + | @app.get("/heroes/") | |
| 55 | + | def read_heroes(session: SessionDep): | |
| 56 | + | heroes = session.exec(select(Hero)).all() | |
| 57 | + | return heroes | |
| 58 | + | ``` | |
| 59 | + | ||
| 60 | + | 7. Key Considerations: | |
| 61 | + | Dependencies: Use FastAPI's dependency injection to manage database sessions effectively. | |
| 62 | + | Error Handling: FastAPI automatically handles validation errors based on Pydantic models. | |
| 63 | + | Documentation: FastAPI generates interactive API documentation. | |
| 64 | + | Testing: Write tests for your database interactions. | |
| 65 | + | FastAPI's integration with Pydantic and ORMs simplifies database modeling, making it easier to build efficient and maintainable APIs. | |
上一頁
下一頁