diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6769e21 --- /dev/null +++ b/.gitignore @@ -0,0 +1,160 @@ +# 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/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..aee80a4 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,15 @@ +FROM python:3.10 + +ENV PYTHONUNBUFFERED 1 + +RUN mkdir app/ + +WORKDIR /app/ + +ADD . . + +RUN pip install --upgrade pip + +RUN pip install -r requirements.txt + +CMD ["python3", "main.py"] \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..88d6207 --- /dev/null +++ b/Makefile @@ -0,0 +1,9 @@ +run: + echo "Iniciando banco" + sudo docker-compose up -d fgaaviso_db + + sleep 7 + echo "Iniciando app" + sudo docker-compose up -d app + echo "aplicando migracoes" + sudo docker-compose exec app alembic upgrade head \ No newline at end of file diff --git a/README.md b/README.md index f56ec88..babb9c8 100644 --- a/README.md +++ b/README.md @@ -1 +1,35 @@ -# 2022.1_G1_fgAvisos_Backend \ No newline at end of file +# 2022.1_G1_fgavisos_Backend + +Pré-requisito para rodar o projeto: Docker e Docker Compose + +### Para rodar + +#### Opção 1 (só funciona no linux): + +``` +make +``` + +Após rodar o comando espere um pouco e a aplicação já estara no ar. + +#### Opção 2 (funciona para windows, linux e macOS): + +Rodando a primeira fez: + +``` +docker-compose build +``` + +``` +docker-compose up +``` + +``` +docker-compose exec app alembic upgrade head +``` + +Nas demais vezes: + +``` +docker-compose up +``` \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..1a9e229 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,105 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = 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-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 = postgresql://postgres:postgres@fgaaviso_db/fgavisos + + +[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 diff --git a/create_tables.py b/create_tables.py new file mode 100644 index 0000000..9f7e3d3 --- /dev/null +++ b/create_tables.py @@ -0,0 +1,17 @@ +from db.config import settings +from db.database import engine + +async def create_tables() -> None: + import src.models.__all_models + print('Criando tabelas') + + async with engine.begin() as connection: + await connection.run_sync(settings.Base.metadata.drop_all) + await connection.run_sync(settings.Base.metadata.create_all) + print('Tabelas criadas') + + +if __name__ == '__main__': + import asyncio + + asyncio.run(create_tables()) \ No newline at end of file diff --git a/db/__init__.py b/db/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/db/config.py b/db/config.py new file mode 100644 index 0000000..cc432a8 --- /dev/null +++ b/db/config.py @@ -0,0 +1,20 @@ +from pydantic import BaseSettings + +from sqlalchemy.orm import declarative_base + + +class Settings(BaseSettings): + + Base = declarative_base() + + user = 'postgres' + password = 'postgres' + host = 'fgaaviso_db' + + DB_URL: str = f'postgresql+asyncpg://{user}:{password}@{host}/fgavisos' + + + class Config: + case_sensitive = True + +settings: Settings() = Settings() \ No newline at end of file diff --git a/db/database.py b/db/database.py new file mode 100644 index 0000000..bf934df --- /dev/null +++ b/db/database.py @@ -0,0 +1,23 @@ +from sqlalchemy.orm import sessionmaker +from sqlalchemy.ext.asyncio import create_async_engine, AsyncEngine, AsyncSession + +from db.config import settings + + +engine: AsyncEngine = create_async_engine(settings.DB_URL) + +Session: AsyncSession = sessionmaker( + bind=engine, + autocommit=False, + autoflush=False, + expire_on_commit=False, + class_=AsyncSession +) + +async def get_session(): + session: AsyncSession = Session() + + try: + yield session + finally: + await session.close() \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..2a51419 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,30 @@ +version: '3' + +services: + fgaaviso_db: + image: mdillon/postgis:11 + container_name: fgavisos-database + environment: + POSTGRES_USER: "postgres" + POSTGRES_PASSWORD: "postgres" + POSTGRES_DB: "fgavisos" + ports: + - "5430:5432" + volumes: + - postgresVolume:/var/lib/postgresql/data + - postgresConfig:/etc/postgresql/11/main + + app: + build: . + container_name: fgavisos-api + ports: + - "8001:8001" + volumes: + - ".:/app" + depends_on: + - fgaaviso_db + + +volumes: + postgresVolume: + postgresConfig: \ No newline at end of file diff --git a/init_db/init.sql b/init_db/init.sql new file mode 100644 index 0000000..7d2459e --- /dev/null +++ b/init_db/init.sql @@ -0,0 +1,3 @@ +CREATE DATABASE fgavisos; +\c fgavisos +CREATE EXTESION fgavisos; \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..5de2b50 --- /dev/null +++ b/main.py @@ -0,0 +1,34 @@ +from fastapi import FastAPI, status, Depends, HTTPException + +from src.models.aluno import AlunoModel +from src.schemas.aluno import AlunoSchema + +from db.database import get_session + +from sqlalchemy.ext.asyncio import AsyncSession + +from sqlalchemy.future import select + +# Exemplos apenas para teste + +app = FastAPI() + +@app.get('/') +def teste(): + return {"teste": "teste"} + +@app.post('/aluno', status_code=status.HTTP_201_CREATED, response_model=AlunoSchema) +async def post_aluno(aluno: AlunoSchema, db: AsyncSession = Depends(get_session)): + aluno_novo = AlunoModel(**aluno.dict()) + + db.add(aluno_novo) + await db.commit() + print('deu bom') + + return aluno_novo + + +if __name__ == "__main__": + import uvicorn + + uvicorn.run('main:app', host='0.0.0.0', port=8001, reload=True) \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..98e4f9c --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..34d5e83 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,80 @@ +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +# 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 +from db.config import settings +import src.models.__all_models +target_metadata = settings.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() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..55df286 --- /dev/null +++ b/migrations/script.py.mako @@ -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() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/0135a2dcf927_init.py b/migrations/versions/0135a2dcf927_init.py new file mode 100644 index 0000000..690521c --- /dev/null +++ b/migrations/versions/0135a2dcf927_init.py @@ -0,0 +1,101 @@ +"""init + +Revision ID: 0135a2dcf927 +Revises: 41fcd8ae6116 +Create Date: 2022-08-24 00:02:53.223682 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '0135a2dcf927' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('aluno', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('nome', sa.String(length=150), nullable=False), + sa.Column('email', sa.String(length=150), nullable=False), + sa.Column('senha', sa.String(length=20), nullable=False), + sa.Column('numero_telefone', sa.String(length=20), nullable=True), + sa.Column('dt_nascimento', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('matricula', sa.BigInteger(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('email'), + sa.UniqueConstraint('matricula') + ) + op.create_table('professor', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('nome', sa.String(length=150), nullable=False), + sa.Column('email', sa.String(length=150), nullable=False), + sa.Column('senha', sa.String(length=20), nullable=False), + sa.Column('numero_telefone', sa.String(length=20), nullable=True), + sa.Column('dt_nascimento', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('matricula', sa.BigInteger(), nullable=False), + sa.Column('is_coordenador', sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('email'), + sa.UniqueConstraint('matricula') + ) + op.create_table('turma', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('professor', sa.Integer(), nullable=True), + sa.Column('ano', sa.Integer(), nullable=False), + sa.Column('semestre', sa.Integer(), nullable=False), + sa.Column('nome_disciplina', sa.String(length=75), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['professor'], ['professor.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('aluno_turma', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('id_aluno', sa.Integer(), nullable=True), + sa.Column('id_turma', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['id_aluno'], ['aluno.id'], ), + sa.ForeignKeyConstraint(['id_turma'], ['turma.id'], ), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('id_aluno'), + sa.UniqueConstraint('id_turma') + ) + op.create_table('aviso', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('titulo', sa.String(length=30), nullable=False), + sa.Column('corpo', sa.String(length=2000), nullable=False), + sa.Column('autor', sa.Integer(), nullable=False), + sa.Column('tag', sa.String(length=20), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('turma', sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(['autor'], ['professor.id'], ), + sa.ForeignKeyConstraint(['turma'], ['turma.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('comentario', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('id_aviso', sa.Integer(), nullable=True), + sa.Column('autor_aluno', sa.Integer(), nullable=True), + sa.Column('autor_professor', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['autor_aluno'], ['aluno.id'], ), + sa.ForeignKeyConstraint(['autor_professor'], ['professor.id'], ), + sa.ForeignKeyConstraint(['id_aviso'], ['aviso.id'], ), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('comentario') + op.drop_table('aviso') + op.drop_table('aluno_turma') + op.drop_table('turma') + op.drop_table('professor') + op.drop_table('aluno') + # ### end Alembic commands ### diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..edf4dac --- /dev/null +++ b/requirements.txt @@ -0,0 +1,17 @@ +alembic==1.8.1 +anyio==3.6.1 +asyncpg==0.26.0 +click==8.1.3 +fastapi==0.79.1 +greenlet==1.1.2 +h11==0.13.0 +idna==3.3 +Mako==1.2.1 +MarkupSafe==2.1.1 +psycopg2-binary==2.9.3 +pydantic==1.9.2 +sniffio==1.2.0 +SQLAlchemy==1.4.40 +starlette==0.19.1 +typing_extensions==4.3.0 +uvicorn==0.18.2 diff --git a/src/models/__all_models.py b/src/models/__all_models.py new file mode 100644 index 0000000..72e12ea --- /dev/null +++ b/src/models/__all_models.py @@ -0,0 +1,7 @@ +from src.models.usuario import UsuarioModel +from src.models.aluno import AlunoModel +from src.models.professor import ProfessorModel +from src.models.turma import TurmaModel +from src.models.aluno_turma import AlunoPossuiTurma +from src.models.aviso import AvisoModel +from src.models.comentario import ComentarioModel \ No newline at end of file diff --git a/src/models/__init__.py b/src/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/models/aluno.py b/src/models/aluno.py new file mode 100644 index 0000000..00f09c8 --- /dev/null +++ b/src/models/aluno.py @@ -0,0 +1,9 @@ +from src.models.usuario import UsuarioModel + +from sqlalchemy import Column, BigInteger + + +class AlunoModel(UsuarioModel): + __tablename__ = 'aluno' + + matricula = Column(BigInteger, nullable=False, unique=True) \ No newline at end of file diff --git a/src/models/aluno_turma.py b/src/models/aluno_turma.py new file mode 100644 index 0000000..a0cf8a8 --- /dev/null +++ b/src/models/aluno_turma.py @@ -0,0 +1,11 @@ +from sqlalchemy import Column, Integer, ForeignKey + +from db.config import settings + + +class AlunoPossuiTurma(settings.Base): + __tablename__ = 'aluno_turma' + + id = Column(Integer, primary_key=True, autoincrement=True) + id_aluno = Column(Integer, ForeignKey('aluno.id'), unique=True) + id_turma = Column(Integer, ForeignKey('turma.id'), unique=True) \ No newline at end of file diff --git a/src/models/aviso.py b/src/models/aviso.py new file mode 100644 index 0000000..590eb47 --- /dev/null +++ b/src/models/aviso.py @@ -0,0 +1,16 @@ +from sqlalchemy import Column, Integer, String, DateTime, ForeignKey + +from db.config import settings + +import datetime + +class AvisoModel(settings.Base): + __tablename__ = 'aviso' + + id = Column(Integer, primary_key=True, autoincrement=True) + titulo = Column(String(30), nullable=False) + corpo = Column(String(2000), nullable=False) + autor = Column(Integer, ForeignKey('professor.id'), nullable=False) + tag = Column(String(20)) + created_at = Column(DateTime, default=datetime.datetime.now()) + turma = Column(Integer, ForeignKey('turma.id'), nullable=False) \ No newline at end of file diff --git a/src/models/comentario.py b/src/models/comentario.py new file mode 100644 index 0000000..8e81ef6 --- /dev/null +++ b/src/models/comentario.py @@ -0,0 +1,14 @@ +from sqlalchemy import Column, Integer, String, DateTime, ForeignKey + +from db.config import settings + +import datetime + + +class ComentarioModel(settings.Base): + __tablename__ = 'comentario' + + id = Column(Integer, primary_key=True, autoincrement=True) + id_aviso = Column(Integer, ForeignKey('aviso.id')) + autor_aluno = Column(Integer, ForeignKey('aluno.id')) + autor_professor = Column(Integer, ForeignKey('professor.id')) diff --git a/src/models/professor.py b/src/models/professor.py new file mode 100644 index 0000000..67bc21a --- /dev/null +++ b/src/models/professor.py @@ -0,0 +1,10 @@ +from sqlalchemy import Column, BigInteger, Boolean + +from src.models.usuario import UsuarioModel + + +class ProfessorModel(UsuarioModel): + __tablename__ = 'professor' + + matricula = Column(BigInteger, nullable=False, unique=True) + is_coordenador = Column(Boolean, default=False) \ No newline at end of file diff --git a/src/models/turma.py b/src/models/turma.py new file mode 100644 index 0000000..d82bb8f --- /dev/null +++ b/src/models/turma.py @@ -0,0 +1,16 @@ +from sqlalchemy import Column, Integer, String, DateTime, ForeignKey + +from db.config import settings + +import datetime + + +class TurmaModel(settings.Base): + __tablename__ = 'turma' + + id = Column(Integer, primary_key=True, autoincrement=True) + professor = Column(Integer, ForeignKey('professor.id')) + ano = Column(Integer, nullable=False) + semestre = Column(Integer, nullable=False) + nome_disciplina = Column(String(75)) + created_at = Column(DateTime, default=datetime.datetime.now()) \ No newline at end of file diff --git a/src/models/usuario.py b/src/models/usuario.py new file mode 100644 index 0000000..b770cdb --- /dev/null +++ b/src/models/usuario.py @@ -0,0 +1,17 @@ +from sqlalchemy import Column, Integer, String, DateTime + +from db.config import settings + +import datetime + + +class UsuarioModel(settings.Base): + __abstract__ = True + + id = Column(Integer, primary_key=True, autoincrement=True) + nome = Column(String(150), nullable=False) + email = Column(String(150), unique=True, nullable=False) + senha = Column(String(20), nullable=False) + numero_telefone = Column(String(20)) + dt_nascimento = Column(DateTime) + created_at = Column(DateTime, default=datetime.datetime.now()) \ No newline at end of file diff --git a/src/schemas/__init__.py b/src/schemas/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/schemas/aluno.py b/src/schemas/aluno.py new file mode 100644 index 0000000..6bc30df --- /dev/null +++ b/src/schemas/aluno.py @@ -0,0 +1,19 @@ +from typing import Any, Optional + +from pydantic import BaseModel + +from datetime import datetime + + +class AlunoSchema(BaseModel): + id: Optional[int] + nome: str + email: str + senha: str + numero_telefone: Optional[str] + dt_nascimento: Optional[datetime] + created_at: Optional[datetime] + matricula: int + + class Config: + orm_mode=True \ No newline at end of file diff --git a/src/schemas/aluno_turma.py b/src/schemas/aluno_turma.py new file mode 100644 index 0000000..a4927df --- /dev/null +++ b/src/schemas/aluno_turma.py @@ -0,0 +1,12 @@ +from typing import Any, Optional + +from pydantic import BaseModel + + +class AlunoPossuiTurmaSchema(BaseModel): + id: Optional[int] + id_aluno: int + id_turma: int + + class Config: + orm_mode=True \ No newline at end of file diff --git a/src/schemas/aviso.py b/src/schemas/aviso.py new file mode 100644 index 0000000..2e45bd8 --- /dev/null +++ b/src/schemas/aviso.py @@ -0,0 +1,18 @@ +from typing import Any, Optional + +from pydantic import BaseModel + +from datetime import datetime + + +class AvisoSchema(BaseModel): + id: Optional[int] + titulo: str + corpo: str + autor: int + tag: Optional[str] + created_at: Optional[datetime] + turma: int + + class Config: + orm_mode=True \ No newline at end of file diff --git a/src/schemas/comentario.py b/src/schemas/comentario.py new file mode 100644 index 0000000..0b477d7 --- /dev/null +++ b/src/schemas/comentario.py @@ -0,0 +1,13 @@ +from typing import Any, Optional + +from pydantic import BaseModel + + +class ComentarioSchema(BaseModel): + id: Optional[int] + id_aviso: int + autor_aluno: Optional[int] + autor_professor: Optional[int] + + class Config: + orm_mode=True \ No newline at end of file diff --git a/src/schemas/professor.py b/src/schemas/professor.py new file mode 100644 index 0000000..a35b095 --- /dev/null +++ b/src/schemas/professor.py @@ -0,0 +1,20 @@ +from typing import Any, Optional + +from pydantic import BaseModel + +from datetime import datetime + + +class ProfessorSchema(BaseModel): + id: Optional[int] + nome: str + email: str + senha: str + numero_telefone: Optional[str] + dt_nascimento: Optional[datetime] + created_at: Optional[datetime] + matricula: int + is_coordenador: Optional[bool] + + class Config: + orm_mode=True \ No newline at end of file diff --git a/src/schemas/turma.py b/src/schemas/turma.py new file mode 100644 index 0000000..aa6eae8 --- /dev/null +++ b/src/schemas/turma.py @@ -0,0 +1,17 @@ +from typing import Any, Optional + +from pydantic import BaseModel + +from datetime import datetime + + +class TurmaSchema(BaseModel): + id: Optional[int] + professor: str + ano: str + semestre: int + nome_disciplina: Optional[str] + created_at: Optional[datetime] + + class Config: + orm_mode=True \ No newline at end of file