15 Commits

Author SHA1 Message Date
6c6f96cc94 Trying to change models 2023-07-24 07:07:36 +03:00
45d0b8e52d Alembic installed and activated. Poems table added 2023-07-23 22:52:31 +03:00
1055416640 Still no result 2023-07-20 00:09:30 +03:00
52d9ad3399 Prepare to use another auth code 2023-07-19 23:24:42 +03:00
30140f058f Добавлена response_model=User в get_current_user 2023-07-19 00:14:56 +03:00
d5ba710885 добавили responce_model=User к get_current_user 2023-07-19 00:11:57 +03:00
6127dd8ba4 добавлен параметр response_model к get_user 2023-07-19 00:10:59 +03:00
9e4bb1b99f К схемам из schema.py добавлены доп. поля (соотв. models) 2023-07-19 00:05:42 +03:00
d66b9004e0 fastapi.Responce has been imported 2023-07-18 23:56:07 +03:00
626170964f pass new parameters to sessionmaker 2023-07-18 23:47:01 +03:00
1dd37a72b4 parameters of sessionmaker changed 2023-07-18 23:43:23 +03:00
b39d9ada27 Imported modules corrected 2023-07-18 23:39:04 +03:00
91842dcc51 Merge branch 'main' of https://git.dm1sh.ru/dm1sh/porridger 2023-07-17 23:36:46 +03:00
09ba6a3478 Разделил модели базы данных и модели pydantic. 2023-07-17 23:34:04 +03:00
808edad6b4 Необходимо решить проблему get_user 2023-07-17 03:41:20 +03:00
14 changed files with 477 additions and 81 deletions

102
alembic.ini Normal file
View File

@ -0,0 +1,102 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = migrations
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to migrations/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# sqlalchemy.url = driver://user:pass@localhost/dbname
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

2
back/base.py Normal file
View File

@ -0,0 +1,2 @@
from .db import Base
from .models import UserDatabase, Announcement, Trashbox

View File

@ -1,6 +1,13 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from typing import AsyncGenerator
from sqlalchemy import create_engine, select
# from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.ext.declarative import declarative_base
from fastapi import Depends
# from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
@ -8,6 +15,7 @@ engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autoflush=True, bind=engine)
SessionLocal = sessionmaker(bind=engine, autoflush=True, autocommit=False)
Base = declarative_base()
database = SessionLocal()
Base = declarative_base()

View File

@ -19,34 +19,47 @@ import shutil
import os
from .utils import *
from .models import Announcement, Trashbox, UserDatabase, Base
from .db import engine, SessionLocal
from .db import Base, engine, SessionLocal, database
from .models import Announcement, Trashbox, UserDatabase
from . import schema
Base.metadata.create_all(bind=engine)
db = SessionLocal()
app = FastAPI()
templates = Jinja2Templates(directory="./front/dist")
app.mount("/static", StaticFiles(directory = "./front/dist"))
if not os.path.exists("./uploads"):
os.mkdir("C:/Users/38812/porridger/uploads")
app.mount("/uploads", StaticFiles(directory = "./uploads"))
# Функция, создающая сессию БД при каждом запросе к нашему API.
# Срабатывает до запуска остальных функций.
# Всегда закрывает сессию при окончании работы с ней
@app.middleware("http")
async def db_session_middleware(request: Request, call_next):
response = Response("Internal server error", status_code=500)
try:
request.state.db = SessionLocal()
response = await call_next(request)
finally:
request.state.db.close()
return response
@app.get("/api/announcements")#адрес объявлений
def annoncements_list(user_id: int = None, metro: str = None, category: str = None, booked_by: int = -1):
def annoncements_list(user_id: int = None, metro: str = None, category: str = None, booked_by: int = 0):
# Считываем данные из Body и отображаем их на странице.
# В последствии будем вставлять данные в html-форму
a = db.query(Announcement)
b = db.query(Announcement)
c = db.query(Announcement)
d = db.query(Announcement)
e = db.query(Announcement)
a = database.query(Announcement)
b = database.query(Announcement)
c = database.query(Announcement)
d = database.query(Announcement)
e = database.query(Announcement)
if user_id != None:
b = a.filter(Announcement.user_id == user_id)
@ -74,7 +87,7 @@ def single_annoncement(user_id:int):
# Считываем данные из Body и отображаем их на странице.
# В последствии будем вставлять данные в html-форму
try:
annoncement = db.get(Announcement, user_id)
annoncement = database.get(Announcement, user_id)
return {"id": annoncement.id, "user_id": annoncement.user_id, "name": annoncement.name,
"category": annoncement.category, "best_by": annoncement.best_by, "address": annoncement.address,
"description": annoncement.description, "metro": annoncement.metro, "latitude": annoncement.latitude,
@ -115,8 +128,8 @@ def put_in_db(name: Annotated[str, Form()], category: Annotated[str, Form()], be
@app.delete("/api/announcement") #адрес объявления
def delete_from_db(data = Body()):#функция удаления объекта из БД
try:
db.delete(user_id=data.user_id)#удаление из БД
db.commit() # сохраняем изменения
database.delete(user_id=data.user_id)#удаление из БД
database.commit() # сохраняем изменения
return {"Answer" : True}
except:
return {"Answer" : False}
@ -129,21 +142,21 @@ def change_book_status(data: schema.Book):
# Получаем id пользователя, который бронирует объявление
temp_user_id = 1
# Находим объявление по данному id
announcement_to_change = db.query(Announcement).filter(id == data.id).first()
announcement_to_change = database.query(Announcement).filter(id == data.id).first()
# Изменяем поле booked_status на полученный id
announcement_to_change.booked_status = temp_user_id
return {"Success": True}
except:
return {"Success": False}
# reginstration
@app.post("/api/signup")
def create_user(data = Body()):
if db.query(UserDatabase).filter(UserDatabase.email == data["email"]).first() == None:
if database.query(UserDatabase).filter(UserDatabase.email == data["email"]).first() == None:
new_user = UserDatabase(id=data["id"], email=data["email"], password=data["password"], name=data["name"], surname=data["surname"])
db.add(new_user)
db.commit()
db.refresh(new_user) # обновляем состояние объекта
database.add(new_user)
database.commit()
database.refresh(new_user) # обновляем состояние объекта
return {"Success": True}
return {"Success": False, "Message": "Пользователь с таким email уже зарегестрирован."}
@ -153,7 +166,7 @@ async def login_for_access_token(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
# разобраться с первым параметром
user = authenticate_user(db.query(UserDatabase).all(), form_data.username, form_data.password)
user = authenticate_user(database, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
@ -167,8 +180,8 @@ async def login_for_access_token(
return access_token
@app.get("/api/users/me/", response_model=User)
async def read_users_me(
@app.get("/api/users/me/", response_model=schema.User)
async def read_users_me( #!!!!!!!!!!!
current_user: Annotated[User, Depends(get_current_active_user)]
):
return current_user

View File

@ -1,12 +1,18 @@
from sqlalchemy import Column, Integer, String
from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
from fastapi import Depends
from .db import Base
# from db import Base
class User(SQLAlchemyBaseUserTableUUID, Base):
pass
class UserDatabase(Base):#класс пользователя
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)#айди пользователя
id = Column(Integer, primary_key=True, index=True, unique=True)#айди пользователя
phone = Column(Integer, nullable=True)#номер телефона пользователя
email = Column(String)#электронная почта пользователя
password = Column(String) # пароль
@ -43,3 +49,26 @@ class Trashbox(Base):#класс мусорных баков
longtitude = Column(Integer)
category = Column(String)#категория продукта из объявления
class Poems(Base):#класс поэзии
__tablename__ = "poems"
id = Column(Integer, primary_key=True, index=True) #айди
poem_text = Column(String) # текст стихотворения
# from typing import AsyncGenerator
# from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
# from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
# # This function can be called during the initialization of the FastAPI app.
# async def create_db_and_tables():
# async with engine.begin() as conn:
# await conn.run_sync(Base.metadata.create_all)
# async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
# async with async_session_maker() as session:
# yield session
# async def get_user_db(session: AsyncSession = Depends(get_async_session)):
# yield SQLAlchemyUserDatabase(session, User)

View File

@ -1,5 +1,29 @@
from pydantic import BaseModel
from typing import Annotated, Union
class Book(BaseModel):
id: int
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
email: Union[str, None] = None
class User(BaseModel):
id: int
phone: Union[int, None] = None
email: str
name: Union[str, None] = None
surname: str
class Config:
orm_mode = True
class UserInDB(User):
password: str
hashed_password: str

2
back/service.py Normal file
View File

@ -0,0 +1,2 @@
from sqlalchemy.orm import Session

View File

@ -1,52 +1,24 @@
from datetime import datetime, timedelta
from typing import Annotated, Union
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi import Depends, FastAPI, HTTPException, status, Response, Request
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel
# to get a string like this run:
# openssl rand -hex 32
from sqlalchemy.orm import Session
from sqlalchemy import select
from .db import Session, database
from .models import UserDatabase
from .schema import Token, TokenData, UserInDB, User
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# fake_users_db = {
# "johndoe": {
# "email": "johndoe",
# "full_name": "John Doe",
# "email": "johndoe@example.com",
# "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
# "disabled": False,
# }
# }
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
email: Union[str, None] = None
class User(BaseModel):
# email: str
email: Union[str, None] = None
# password: str
# password: Union[str, None] = None
full_name: Union[str, None] = None
disabled: Union[bool, None] = None
class UserInDB(User):
hashed_password: str
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@ -60,17 +32,15 @@ def get_password_hash(password):
# проблема здесь
def get_user(db, email: str):
user = None
for person_with_correct_email in db.query(UserDatabase):
if person_with_correct_email.email == email:
user = person_with_correct_email
return user #UserInDB(user_email)
def get_user(db: Session, email: str):
user_with_required_email = db.query(UserDatabase).filter(UserDatabase.email == email).first()
print(user_with_required_email)
if user_with_required_email:
return user_with_required_email
return None
def authenticate_user(db, email: str, password: str):
def authenticate_user(db: Session, email: str, password: str):
user = get_user(db, email)
if not user:
return False
@ -90,7 +60,7 @@ def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None
return encoded_jwt
async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
async def get_current_user(db: Session, token: Annotated[str, Depends(oauth2_scheme)]):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
@ -104,8 +74,8 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
token_data = TokenData(email=email)
except JWTError:
raise credentials_exception
user = get_user(fake_users_db, email=token_data.email)
if user is None:
user = get_user(db, email=token_data.email)
if user == None:
raise credentials_exception
return user
@ -115,4 +85,8 @@ async def get_current_active_user(
):
if current_user.disabled:
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
return current_user
def get_db(request: Request):
return request.state.db

1
migrations/README Normal file
View File

@ -0,0 +1 @@
Generic single-database configuration.

85
migrations/env.py Normal file
View File

@ -0,0 +1,85 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from back import db, base
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = base.Base.metadata
# target_metadata = None
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
# url = config.get_main_option("sqlalchemy.url")
url = config.get_main_option(db.SQLALCHEMY_DATABASE_URL)
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
configuration = config.get_section(config.config_ini_section)
configuration['sqlalchemy.url'] = db.SQLALCHEMY_DATABASE_URL
connectable = engine_from_config(
configuration,
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

24
migrations/script.py.mako Normal file
View File

@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}

View File

@ -0,0 +1,28 @@
"""first
Revision ID: 0006eca30e2c
Revises:
Create Date: 2023-07-23 22:32:43.496939
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0006eca30e2c'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###

View File

@ -0,0 +1,34 @@
"""Poems table added
Revision ID: 18001c2231e3
Revises: 33c5716276b5
Create Date: 2023-07-23 22:50:16.055961
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '18001c2231e3'
down_revision = '33c5716276b5'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('poems',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('poem_text', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_poems_id'), 'poems', ['id'], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_poems_id'), table_name='poems')
op.drop_table('poems')
# ### end Alembic commands ###

View File

@ -0,0 +1,70 @@
"""Try to make alembic see models
Revision ID: 33c5716276b5
Revises: 0006eca30e2c
Create Date: 2023-07-23 22:42:07.532395
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '33c5716276b5'
down_revision = '0006eca30e2c'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('announcements',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('name', sa.String(), nullable=True),
sa.Column('category', sa.String(), nullable=True),
sa.Column('best_by', sa.Integer(), nullable=True),
sa.Column('address', sa.String(), nullable=True),
sa.Column('longtitude', sa.Integer(), nullable=True),
sa.Column('latitude', sa.Integer(), nullable=True),
sa.Column('description', sa.String(), nullable=True),
sa.Column('src', sa.String(), nullable=True),
sa.Column('metro', sa.String(), nullable=True),
sa.Column('trashId', sa.Integer(), nullable=True),
sa.Column('booked_by', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_announcements_id'), 'announcements', ['id'], unique=False)
op.create_table('trashboxes',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=True),
sa.Column('address', sa.String(), nullable=True),
sa.Column('latitude', sa.Integer(), nullable=True),
sa.Column('longtitude', sa.Integer(), nullable=True),
sa.Column('category', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_trashboxes_id'), 'trashboxes', ['id'], unique=False)
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('phone', sa.Integer(), nullable=True),
sa.Column('email', sa.String(), nullable=True),
sa.Column('password', sa.String(), nullable=True),
sa.Column('hashed_password', sa.String(), nullable=True),
sa.Column('name', sa.String(), nullable=True),
sa.Column('surname', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=True)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_users_id'), table_name='users')
op.drop_table('users')
op.drop_index(op.f('ix_trashboxes_id'), table_name='trashboxes')
op.drop_table('trashboxes')
op.drop_index(op.f('ix_announcements_id'), table_name='announcements')
op.drop_table('announcements')
# ### end Alembic commands ###