📅  最后修改于: 2023-12-03 15:30:44.703000             🧑  作者: Mango
FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.7+ based on standard Python type hints. PostgreSQL is a powerful, open-source relational database management system. Combining FastAPI and PostgreSQL can give you a fast and reliable API with easy data storage and retrieval.
To get started with FastAPI and PostgreSQL, you can follow these steps:
$ pip install fastapi
$ pip install uvicorn[standard]
$ pip install databases[postgresql]
from fastapi import FastAPI
from databases import Database
app = FastAPI()
DATABASE_URL = "postgresql://user:password@host:port/dbname"
database = Database(DATABASE_URL)
@app.on_event("startup")
async def startup():
await database.connect()
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
create_table_query = """
CREATE TABLE items (
id SERIAL PRIMARY KEY,
name TEXT,
description TEXT,
price FLOAT,
tax FLOAT
);
"""
async with database.transaction():
await database.execute(create_table_query)
@app.post("/items/")
async def create_item(item: Item):
query = """
INSERT INTO items (name, description, price, tax)
VALUES (:name, :description, :price, :tax)
RETURNING id;
"""
values = item.dict()
return {"id": await database.execute(query=query, values=values)}
@app.get("/items/{item_id}")
async def read_item(item_id: int):
query = """
SELECT *
FROM items
WHERE id = :item_id;
"""
return await database.fetch_one(query=query, values={"item_id": item_id})
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
query = """
UPDATE items
SET name = :name,
description = :description,
price = :price,
tax = :tax
WHERE id = :item_id;
"""
values = item.dict()
values.update({"item_id": item_id})
return {"rows_updated": await database.execute(query=query, values=values)}
@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
query = """
DELETE FROM items
WHERE id = :item_id;
"""
return {"rows_deleted": await database.execute(query=query, values={"item_id": item_id})}
$ uvicorn main:app --reload
Combining FastAPI and PostgreSQL can give you a powerful, fast and reliable API with easy data storage and retrieval. It's a great choice for building APIs that need to handle large amounts of data and high concurrency.