Skip to content

Commit

Permalink
Updated
Browse files Browse the repository at this point in the history
  • Loading branch information
tisnik committed Oct 30, 2023
1 parent c9d19cd commit 13b9610
Showing 1 changed file with 117 additions and 0 deletions.
117 changes: 117 additions & 0 deletions docs/fastapi.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,9 +255,126 @@ async def delete_operation(id: int):

## Reálná databáze

```
postgres=# CREATE USER tester WITH PASSWORD '123qwe';
CREATE ROLE
postgres=# CREATE DATABASE test1 OWNER tester;
CREATE DATABASE
postgres=# GRANT ALL PRIVILEGES ON DATABASE test1 TO tester;
GRANT
```

---

## SQLAlchemy

* installation

```python
[project]
name = ""
version = ""
description = ""
authors = [
{name = "", email = ""},
]
dependencies = [
"fastapi>=0.104.0",
"uvicorn>=0.23.2",
"sqlalchemy>=2.0.22",
"psycopg2-binary>=2.9.9",
]
requires-python = ">=3.11"
readme = "README.md"
license = {text = "MIT"}

[tool.pdm.scripts]
start = "uvicorn --app-dir src/example_package main:app --reload"
```

[Zdrojový kód příkladu](https://github.com/tisnik/most-popular-python-libs/blob/master/fastapi/sources//pyproject2.toml)

---

### Implementace základních CRUD operací

```python
from fastapi import FastAPI

from sqlalchemy import create_engine
from sqlalchemy.engine import URL
from sqlalchemy.orm import sessionmaker


def connect_to_db():
url = URL.create(
drivername="postgresql",
username="tester",
password="123qwe",
host="localhost",
database="test1",
port=5432
)
print("url", url)

engine = create_engine(url)
print("engine", engine)

Session = sessionmaker(bind=engine)
session = Session()
print("session", session)

return engine, session


engine, session = connect_to_db()


from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import declarative_base

Base = declarative_base()


class Record(Base):
__tablename__ = "records"

id = Column(Integer, primary_key=True)
text = Column(String)


# inicializace
Base.metadata.create_all(engine)

app = FastAPI()


@app.post("/create")
async def create_operation(text: str):
record = Record(text=text)
session.add(record)
session.commit()
return {"created": record.id}

@app.get("/")
async def read_operation():
record_query = session.query(Record)
return {"list": record_query.all()}

@app.put("/update/{id}")
async def update_operation(id: int, text: str = ""):
record_query = session.query(Record).filter(Record.id==id)
record = record_query.first()
record.text = text
session.add(record)
session.commit()

@app.delete("/delete/{id}")
async def delete_operation(id: int):
record = session.query(Record).filter(Record.id==id).first()
session.delete(record)
session.commit()
return {"todo deleted": record.id}
```

[Zdrojový kód příkladu](https://github.com/tisnik/most-popular-python-libs/blob/master/fastapi/sources//main5.py)

0 comments on commit 13b9610

Please sign in to comment.