Skip to content

Commit b3ccee7

Browse files
committed
using alembic to perform database
1 parent 788f3ac commit b3ccee7

File tree

8 files changed

+144
-14
lines changed

8 files changed

+144
-14
lines changed

.gitignore

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,8 @@ taste.py
44
# Confidential
55

66
secret.json
7-
.env
7+
.env
8+
9+
# Alembic
10+
11+
alembic

alembic.ini

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

app/SQLQuery.pgsql

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
11

2-
/*
3-
INSERT INTO posts (title, content, published, owner_id) VALUES ('From SQL SENTENCE', 'FROM SQL SENTENCE IN A SCRIPT', false, 1) RETURNING *;
2+
/* Pull information */
3+
--INSERT INTO posts (title, content, published, owner_id) VALUES ('From SQL SENTENCE', 'FROM SQL SENTENCE IN A SCRIPT', false, 1) RETURNING *;
44

5-
INSERT INTO users (email, password) VALUES ('arcan_diabdo@hotmail.com', 'Micontraseña1234') RETURNING *;
6-
*/
5+
--INSERT INTO users (email, password) VALUES ('arcan_diabdo@hotmail.com', 'Micontraseña1234') RETURNING *;
76

8-
SELECT * FROM votes;
7+
/* to group the number of post from each person*/
8+
--SELECT users.id, users.email, COUNT(posts.id) AS user_post_count FROM posts LEFT JOIN users ON posts.owner_id = users.id GROUP BY users.id;
99

10-
/* DELETE TABLE */
11-
/*DROP TABLE posts;*/
10+
/* Filters*/
11+
-- SELECT posts.*, COUNT(votes.post_id) FROM posts LEFT JOIN votes ON posts.id = votes.post_id GROUP BY posts.id;
1212

13+
/* DELETE TABLE */
14+
--DROP TABLE votes;
15+
/* CASCADE*/
16+
--DROP TABLE votes CASCADE
1317
/* delete all rows from a table
1418
DELETE FROM posts;
1519
*/

app/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
app = FastAPI()
1818

19-
models.Base.metadata.create_all(bind=engine)
19+
#models.Base.metadata.create_all(bind=engine)
2020

2121
# ROUTERS
2222
app.include_router(post.router)

app/models.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ class User(Base):
2727
password = Column(String, nullable=False)
2828
created_at = Column(TIMESTAMP(timezone=True), nullable=False, server_default=text('now()'))
2929
premium = Column(Boolean, nullable=False)
30+
phone_number = Column(String)
3031

3132
class Vote(Base):
3233
__tablename__ = "votes"

app/routers/post.py

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from fastapi import status, HTTPException, Depends
33
from fastapi.routing import APIRouter
44
from sqlalchemy.orm import Session
5-
5+
from sqlalchemy import func
66
from app import oauth2
77
from .. import models, schemas
88
from ..database import get_db
@@ -16,15 +16,21 @@
1616

1717
# API
1818

19-
@router.get("/", response_model=List[schemas.Post])
19+
#@router.get("/", response_model=List[schemas.Post])
20+
@router.get("/", response_model=List[schemas.PostOut])
2021
def get_posts(db: Session = Depends(get_db), current_user: int = Depends(oauth2.get_current_user), limit: int = 10, skip: int= 0, search: Optional[str]= ""):
2122
# SQL
2223
"""cursor.execute('''SELECT * FROM posts''')
2324
posts = cursor.fetchall()"""
2425
# ORM
2526
print(f"Request by '{current_user.id}' - {current_user.email}")
2627
# to filter by user _ posts = db.query(models.Post).filter(models.Post.owner_id == current_user.id).all()
27-
posts = db.query(models.Post).filter(models.Post.title.contains(search)).limit(limit).offset(skip).all()
28+
#posts = db.query(models.Post).filter(models.Post.title.contains(search)).limit(limit).offset(skip).all()
29+
posts = db.query(
30+
models.Post, func.count(models.Vote.post_id).label('votes')).join(
31+
models.Vote, models.Vote.post_id == models.Post.id, isouter=True).group_by(
32+
models.Post.id).filter(
33+
models.Post.title.contains(search)).limit(limit).offset(skip).all()
2834
return posts
2935

3036

@@ -57,15 +63,19 @@ def get_latest_post():
5763
"""post = my_posts[len(my_posts)-1]
5864
return post"""
5965

60-
@router.get("/{id}", response_model=schemas.Post)
66+
@router.get("/{id}", response_model=schemas.PostOut)
6167
async def get_post(id: int, db: Session = Depends(get_db), current_user: int = Depends(oauth2.get_current_user)):
6268

6369
# SQL CODE
6470
'''cursor.execute("SELECT * FROM posts WHERE id = %s", (str(id),))
6571
post = cursor.fetchone()'''
6672

6773
# ORM
68-
post = db.query(models.Post).filter(models.Post.id==id).first()
74+
#post = db.query(models.Post).filter(models.Post.id==id).first()
75+
post = db.query(
76+
models.Post, func.count(models.Vote.post_id).label('votes')).join(
77+
models.Vote, models.Vote.post_id == models.Post.id, isouter=True).group_by(
78+
models.Post.id).filter(models.Post.id==id).first()
6979
#post = find_post(id)
7080
if post != None:
7181
return post

app/routers/vote.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@
1515
@router.post("/", status_code=status.HTTP_201_CREATED)
1616
def vote(vote: schemas.Vote, db: Session = Depends(database.get_db), current_user: int = Depends(oauth2.get_current_user)):
1717

18+
post = db.query(models.Post).filter(models.Post.id == vote.post_id).first()
19+
if not post:
20+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Post with id {vote.post_id} does not exist!")
21+
1822
vote_query = db.query(models.Vote).filter(models.Vote.post_id == vote.post_id, models.Vote.user_id == current_user.id)
1923
found_vote = vote_query.first()
2024
if vote.dir == 1:

app/schemas.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,13 @@ class Post(PostBase):
3737
class Config:
3838
orm_mode = True
3939

40+
class PostOut(BaseModel):
41+
Post: Post
42+
votes: int
43+
44+
class Config:
45+
orm_mode = True
46+
4047
class UserCreate(BaseModel):
4148
email: EmailStr
4249
password: str

0 commit comments

Comments
 (0)