Skip to content

Commit c11e052

Browse files
initial commit
0 parents  commit c11e052

File tree

4 files changed

+210
-0
lines changed

4 files changed

+210
-0
lines changed

alembic.ini

+105
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
# A generic, single database configuration.
2+
3+
[alembic]
4+
# path to migration scripts
5+
script_location = alembic
6+
7+
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
8+
# Uncomment the line below if you want the files to be prepended with date and time
9+
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
10+
# for all available tokens
11+
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
12+
13+
# sys.path path, will be prepended to sys.path if present.
14+
# defaults to the current working directory.
15+
prepend_sys_path = .
16+
17+
# timezone to use when rendering the date within the migration file
18+
# as well as the filename.
19+
# If specified, requires the python-dateutil library that can be
20+
# installed by adding `alembic[tz]` to the pip requirements
21+
# string value is passed to dateutil.tz.gettz()
22+
# leave blank for localtime
23+
# timezone =
24+
25+
# max length of characters to apply to the
26+
# "slug" field
27+
# truncate_slug_length = 40
28+
29+
# set to 'true' to run the environment during
30+
# the 'revision' command, regardless of autogenerate
31+
# revision_environment = false
32+
33+
# set to 'true' to allow .pyc and .pyo files without
34+
# a source .py file to be detected as revisions in the
35+
# versions/ directory
36+
# sourceless = false
37+
38+
# version location specification; This defaults
39+
# to alembic/versions. When using multiple version
40+
# directories, initial revisions must be specified with --version-path.
41+
# The path separator used here should be the separator specified by "version_path_separator" below.
42+
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
43+
44+
# version path separator; As mentioned above, this is the character used to split
45+
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
46+
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
47+
# Valid values for version_path_separator are:
48+
#
49+
# version_path_separator = :
50+
# version_path_separator = ;
51+
# version_path_separator = space
52+
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
53+
54+
# the output encoding used when revision files
55+
# are written from script.py.mako
56+
# output_encoding = utf-8
57+
58+
sqlalchemy.url = driver://user:pass@localhost/dbname
59+
60+
61+
[post_write_hooks]
62+
# post_write_hooks defines scripts or Python functions that are run
63+
# on newly generated revision scripts. See the documentation for further
64+
# detail and examples
65+
66+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
67+
# hooks = black
68+
# black.type = console_scripts
69+
# black.entrypoint = black
70+
# black.options = -l 79 REVISION_SCRIPT_FILENAME
71+
72+
# Logging configuration
73+
[loggers]
74+
keys = root,sqlalchemy,alembic
75+
76+
[handlers]
77+
keys = console
78+
79+
[formatters]
80+
keys = generic
81+
82+
[logger_root]
83+
level = WARN
84+
handlers = console
85+
qualname =
86+
87+
[logger_sqlalchemy]
88+
level = WARN
89+
handlers =
90+
qualname = sqlalchemy.engine
91+
92+
[logger_alembic]
93+
level = INFO
94+
handlers =
95+
qualname = alembic
96+
97+
[handler_console]
98+
class = StreamHandler
99+
args = (sys.stderr,)
100+
level = NOTSET
101+
formatter = generic
102+
103+
[formatter_generic]
104+
format = %(levelname)-5.5s [%(name)s] %(message)s
105+
datefmt = %H:%M:%S

main.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import uvicorn
2+
from fastapi import FastAPI
3+
from fastapi_sqlalchemy import DBSessionMiddleware, db
4+
5+
from schema import Book as SchemaBook
6+
from schema import Author as SchemaAuthor
7+
8+
from schema import Book
9+
from schema import Author
10+
11+
from models import Book as ModelBook
12+
from models import Author as ModelAuthor
13+
14+
import os
15+
from dotenv import load_dotenv
16+
17+
load_dotenv('.env')
18+
19+
20+
app = FastAPI()
21+
22+
# to avoid csrftokenError
23+
app.add_middleware(DBSessionMiddleware, db_url=os.environ['DATABASE_URL'])
24+
25+
@app.get("/")
26+
async def root():
27+
return {"message": "hello world"}
28+
29+
30+
@app.post('/book/', response_model=SchemaBook)
31+
async def book(book: SchemaBook):
32+
db_book = ModelBook(title=book.title, rating=book.rating, author_id = book.author_id)
33+
db.session.add(db_book)
34+
db.session.commit()
35+
return db_book
36+
37+
@app.get('/book/')
38+
async def book():
39+
book = db.session.query(ModelBook).all()
40+
return book
41+
42+
43+
44+
@app.post('/author/', response_model=SchemaAuthor)
45+
async def author(author:SchemaAuthor):
46+
db_author = ModelAuthor(name=author.name, age=author.age)
47+
db.session.add(db_author)
48+
db.session.commit()
49+
return db_author
50+
51+
@app.get('/author/')
52+
async def author():
53+
author = db.session.query(ModelAuthor).all()
54+
return author
55+
56+
57+
# To run locally
58+
if __name__ == '__main__':
59+
uvicorn.run(app, host='0.0.0.0', port=8000)

models.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Float
2+
from sqlalchemy.ext.declarative import declarative_base
3+
from sqlalchemy.orm import relationship
4+
from sqlalchemy.sql import func
5+
6+
Base = declarative_base()
7+
8+
class Book(Base):
9+
__tablename__ = 'book'
10+
id = Column(Integer, primary_key=True, index=True)
11+
title = Column(String)
12+
rating = Column(Float)
13+
time_created = Column(DateTime(timezone=True), server_default=func.now())
14+
time_updated = Column(DateTime(timezone=True), onupdate=func.now())
15+
author_id = Column(Integer, ForeignKey('author.id'))
16+
17+
author = relationship('Author')
18+
19+
20+
class Author(Base):
21+
__tablename__ = 'author'
22+
id = Column(Integer, primary_key=True)
23+
name = Column(String)
24+
age = Column(Integer)
25+
time_created = Column(DateTime(timezone=True), server_default=func.now())
26+
time_updated = Column(DateTime(timezone=True), onupdate=func.now())
27+
28+

schema.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# build a schema using pydantic
2+
from pydantic import BaseModel
3+
4+
class Book(BaseModel):
5+
title: str
6+
rating: int
7+
author_id: int
8+
9+
class Config:
10+
orm_mode = True
11+
12+
class Author(BaseModel):
13+
name:str
14+
age:int
15+
16+
class Config:
17+
orm_mode = True
18+

0 commit comments

Comments
 (0)