Сделана БД, возможно будет редактироваться.

This commit is contained in:
urec56 2024-01-29 18:34:59 +03:00
commit 93b4f15a95
19 changed files with 755 additions and 0 deletions

8
.env_template Normal file
View file

@ -0,0 +1,8 @@
DB_USER=
DB_PASS=
DB_HOST=
DB_PORT=
DB_NAME=
SECRET_KEY=
ALGORITHM=

162
.gitignore vendored Normal file
View file

@ -0,0 +1,162 @@
# ---> Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/

116
alembic.ini Normal file
View file

@ -0,0 +1,116 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = app/migrations
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(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>=3.9 or backports.zoneinfo library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# 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.
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# 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
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
# hooks = ruff
# ruff.type = exec
# ruff.executable = %(here)s/.venv/bin/ruff
# ruff.options = --fix 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

18
app/config.py Normal file
View file

@ -0,0 +1,18 @@
from pydantic import BaseSettings
class Settings(BaseSettings):
DB_USER: str
DB_PASS: str
DB_HOST: str
DB_PORT: str
DB_NAME: str
SECRET_KEY: str
ALGORITHM: str
class Config:
env_file = ".env"
settings = Settings()

7
app/dao/base.py Normal file
View file

@ -0,0 +1,7 @@
from sqlalchemy import insert, select
from app.database import async_session_maker
class BaseDAO:
model = None

20
app/database.py Normal file
View file

@ -0,0 +1,20 @@
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import DeclarativeBase, sessionmaker
from app.config import settings
# URL по которому лежит БД
DATABASE_URL = f"""postgresql+asyncpg://{settings.DB_USER}:
{settings.DB_PASS}@{settings.DB_HOST}:
{settings.DB_PORT}/{settings.DB_NAME}"""
DATABASE_PARAMS = {}
engine = create_async_engine(DATABASE_URL, **DATABASE_PARAMS)
# Создание ассинхронной сессии для БД
async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
# Создание класса, от которого будут наследоваться все таблицы бд
class Base(DeclarativeBase):
pass

12
app/main.py Normal file
View file

@ -0,0 +1,12 @@
from fastapi import FastAPI
from app.users.chat.router import router as chat_router
app = FastAPI()
app.include_router(chat_router)
@app.get('/')
async def root():
pass

1
app/migrations/README Normal file
View file

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

87
app/migrations/env.py Normal file
View file

@ -0,0 +1,87 @@
import sys
from os.path import abspath, dirname
from logging.config import fileConfig
from sqlalchemy import engine_from_config, pool
from alembic import context
from app.database import DATABASE_URL, Base
from app.users.models import Users # noqa
from app.users.chat.models import Chats # noqa
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
sys.path.insert(0, dirname(dirname(abspath(__file__))))
config = context.config
config.set_main_option('sqlalchemy.url', f'{DATABASE_URL}?async_fallback=True')
# 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.metadata
# 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() -> None:
"""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")
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() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
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()

View file

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

View file

@ -0,0 +1,45 @@
"""Database Creation
Revision ID: 9845ad4fed24
Revises: e434e2885475
Create Date: 2024-01-29 18:32:13.361975
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '9845ad4fed24'
down_revision: Union[str, None] = 'e434e2885475'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('chats',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('chat', sa.JSON(), nullable=True),
sa.Column('allowed_users', sa.JSON(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('email', sa.String(), nullable=False),
sa.Column('username', sa.String(), nullable=False),
sa.Column('hashed_password', sa.String(), nullable=False),
sa.Column('role', sa.Integer(), nullable=False),
sa.Column('black_phoenix', sa.Integer(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('users')
op.drop_table('chats')
# ### end Alembic commands ###

View file

@ -0,0 +1,30 @@
"""Database Creation
Revision ID: e434e2885475
Revises:
Create Date: 2024-01-29 18:30:03.314179
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'e434e2885475'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###

10
app/temlates/chat.html Normal file
View file

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BlackPhoenix</title>
</head>
<body>
</body>
</html>

37
app/users/auth.py Normal file
View file

@ -0,0 +1,37 @@
from datetime import datetime, timedelta
from jose import jwt
from passlib.context import CryptContext
from pydantic import EmailStr
from app.config import settings
from app.users.dao import UsersDAO
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
# Функция создания JWT токена
def create_access_token(data: dict) -> str:
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(minutes=30)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(
to_encode, settings.SECRET_KEY, settings.ALGORITHM
)
return encoded_jwt
# Функция проверки наличия юзера
async def authenticate_user(email: EmailStr, password: str):
user = await UsersDAO.find_one_or_none(email=email)
if not user or not verify_password(password, user.hashed_password):
return None
return user

15
app/users/chat/models.py Normal file
View file

@ -0,0 +1,15 @@
from sqlalchemy import Column, Integer, JSON
from app.database import Base
class Chats(Base):
__tablename__ = "chats"
id = Column(Integer, primary_key=True)
chat = Column(JSON)
allowed_users = Column(JSON)
def __str__(self):
return f"Чат #{self.id} с {self.allowed_users}."

26
app/users/chat/router.py Normal file
View file

@ -0,0 +1,26 @@
from fastapi import APIRouter, WebSocket
from starlette.websockets import WebSocketDisconnect
from app.users.chat.websocket import manager
router = APIRouter(
prefix="/chat",
tags=["Чат"]
)
@router.get("")
async def root():
pass
@router.websocket("/ws/{user_id}")
async def websocket_endpoint(websocket: WebSocket, user_id: int):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
await manager.broadcast(f"User {user_id}: {data}")
except WebSocketDisconnect:
manager.disconnect(websocket)
await manager.broadcast(f"User {user_id}: себался")

View file

@ -0,0 +1,20 @@
from fastapi import WebSocket
class ConnectionManager(WebSocket):
def __init__(self):
self.active_connection: list[WebSocket] = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connection.append(websocket)
def disconnect(self, websocket: WebSocket):
self.active_connection.remove(websocket)
async def broadcast(self, message: str):
for websocket in self.active_connection:
await websocket.send_text(message)
manager = ConnectionManager()

18
app/users/models.py Normal file
View file

@ -0,0 +1,18 @@
from sqlalchemy import Column, Integer, String
from app.database import Base
class Users(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
email = Column(String, nullable=False)
username = Column(String, nullable=False)
hashed_password = Column(String, nullable=False)
role = Column(Integer, nullable=False)
black_phoenix = Column(Integer, nullable=False)
def __str__(self):
return f"Юзер {self.username}"

97
requirements.txt Normal file
View file

@ -0,0 +1,97 @@
aiohttp==3.9.1
aioredis==1.3.1
aiosignal==1.3.1
alembic==1.13.1
amqp==5.2.0
annotated-types==0.6.0
anyio==4.2.0
async-timeout==4.0.3
asyncpg==0.29.0
attrs==23.2.0
autoflake==2.2.1
bcrypt==4.1.2
billiard==4.2.0
black==23.12.1
celery==5.3.6
certifi==2023.11.17
click==8.1.7
click-didyoumean==0.3.0
click-plugins==1.1.1
click-repl==0.3.0
dnspython==2.4.2
ecdsa==0.18.0
email-validator==2.1.0.post1
fastapi==0.109.0
fastapi-cache2==0.2.1
fastapi-versioning==0.10.0
flake8==7.0.0
flower==2.0.1
frozenlist==1.4.1
greenlet==3.0.3
gunicorn==21.2.0
h11==0.14.0
hiredis==2.3.2
httpcore==1.0.2
httptools==0.6.1
httpx==0.26.0
humanize==4.9.0
idna==3.6
iniconfig==2.0.0
isort==5.13.2
itsdangerous==2.1.2
Jinja2==3.1.3
kombu==5.3.5
Mako==1.3.0
MarkupSafe==2.1.3
mccabe==0.7.0
multidict==6.0.4
mypy-extensions==1.0.0
nodeenv==1.8.0
orjson==3.9.12
packaging==23.2
passlib==1.7.4
pathspec==0.12.1
pendulum==3.0.0
pillow==10.2.0
platformdirs==4.1.0
pluggy==1.3.0
prometheus-client==0.19.0
prometheus-fastapi-instrumentator==6.1.0
prompt-toolkit==3.0.43
pyasn1==0.5.1
pycodestyle==2.11.1
pydantic==1.10.14
pydantic_core==2.14.6
pyflakes==3.2.0
pyright==1.1.347
pytest==7.4.4
pytest-asyncio==0.23.3
python-dateutil==2.8.2
python-dotenv==1.0.0
python-jose==3.3.0
python-json-logger==2.0.7
python-multipart==0.0.6
pytz==2023.3.post1
PyYAML==6.0.1
redis==4.6.0
rsa==4.9
sentry-sdk==1.39.2
six==1.16.0
sniffio==1.3.0
sqladmin==0.16.0
SQLAlchemy==2.0.25
starlette==0.35.1
time-machine==2.13.0
tornado==6.4
typing_extensions==4.9.0
tzdata==2023.4
ujson==5.9.0
urllib3==2.1.0
uvicorn==0.26.0
uvloop==0.19.0
vine==5.1.0
watchfiles==0.21.0
wcwidth==0.2.13
websockets==12.0
WTForms==3.1.2
yarl==1.9.4