├── .editorconfig ├── .gitignore ├── .pre-commit-config.yaml ├── Dockerfile ├── LICENSE ├── README.md ├── alembic.ini ├── analytics ├── Dockerfile ├── __init__.py ├── alembic.ini ├── database │ ├── __init__.py │ ├── configs.py │ ├── migrations │ │ ├── README │ │ ├── __init__.py │ │ ├── env.py │ │ ├── script.py.mako │ │ └── versions │ │ │ ├── 2024-06-06_eeddc49b11f8.py │ │ │ └── __init__.py │ └── models.py ├── main.py ├── requirements.txt └── service │ ├── __init__.py │ ├── grpc.py │ ├── logger.py │ ├── post_views.proto │ ├── post_views_pb2.py │ ├── post_views_pb2.pyi │ └── post_views_pb2_grpc.py ├── api_test.http ├── docker-compose-dev.yml ├── docker-compose-test.yml ├── makefile ├── pyproject.toml ├── requirements.txt ├── tests ├── __init__.py ├── configs.py ├── conftest.py ├── engagements │ ├── __init__.py │ ├── test_routes.py │ └── test_services.py ├── factories.py ├── posts │ ├── __init__.py │ ├── test_routes.py │ └── test_services.py └── users │ ├── __init__.py │ ├── test_routes.py │ └── test_services.py └── twitter_api ├── __init__.py ├── core ├── __init__.py ├── config.py ├── exceptions.py ├── lifespan.py ├── logging.py ├── middleware.py └── pagination.py ├── database ├── __init__.py ├── base_models.py ├── configs.py ├── depends.py └── migrations │ ├── README │ ├── __init__.py │ ├── env.py │ ├── script.py.mako │ └── versions │ ├── 2024-06-05_7e6080593f5d.py │ └── __init__.py ├── engagements ├── __init__.py ├── grpc │ ├── __init__.py │ ├── post_views.proto │ ├── post_views_pb2.py │ ├── post_views_pb2.pyi │ └── post_views_pb2_grpc.py ├── models.py ├── routes.py ├── services.py └── tasks.py ├── main.py ├── posts ├── __init__.py ├── depends.py ├── models.py ├── routes.py └── services.py ├── routes.py └── users ├── __init__.py ├── auth.py ├── depends.py ├── models.py ├── routes.py └── services.py /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | charset = utf-8 7 | end_of_line = lf 8 | indent_style = space 9 | indent_size = 2 10 | trim_trailing_whitespace = true 11 | insert_final_newline = true 12 | 13 | [*.py] 14 | indent_size = 4 15 | 16 | [Makefile] 17 | indent_style = tab -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | # Pycharm config 132 | .idea/ 133 | 134 | /dump.rdb 135 | http-client.env.json 136 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | default_language_version: 2 | python: python3.11 3 | 4 | repos: 5 | - repo: https://github.com/astral-sh/ruff-pre-commit 6 | rev: v0.4.3 7 | hooks: 8 | - id: ruff 9 | args: [--fix] 10 | - id: ruff-format 11 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | 2 | FROM python:3.11-slim-bullseye 3 | LABEL maintainer="bindruid" 4 | 5 | ENV PYTHONUNBUFFERED 1 6 | ENV PYTHONDONTWRITEBYTECODE 1 7 | 8 | COPY ./requirements.txt /code/ 9 | COPY ./alembic.ini /code/ 10 | RUN apt-get update && apt-get install -y curl 11 | RUN pip install -r /code/requirements.txt 12 | RUN mkdir /code/logs/ 13 | WORKDIR /code/ 14 | EXPOSE 8000 15 | HEALTHCHECK CMD curl --fail http://localhost:8000/api/v1/healthcheck/ || exit 1 16 | ENTRYPOINT ["fastapi", "run", "./twitter_api/main.py", "--reload", "--host", "0.0.0.0", "--port", "8000"] 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright © 2024 abharya.dev@gmail.com 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Twitter Minimal API 2 | 3 | 4 | 5 | 6 | ## Prerequisites 7 | 8 | - `Python 3.11` 9 | - `Postgresql 15` 10 | 11 | 12 | ## Development 13 | 14 | ### `.env` example 15 | 16 | ```shell 17 | DEBUG=True 18 | SECRET_KEY=super_secret_key 19 | DB_URL=postgres://postgres:password@localhost/database_name 20 | PAGINATION_PER_PAGE=20 21 | JWT_SECRET=secret_key 22 | JWT_ALG=HS256 23 | JWT_EXP=86400 24 | ``` 25 | 26 | ### Database setup 27 | 28 | Run database server 29 | 30 | ```shell 31 | docker compose -f ./docker-compose-dev.yml up 32 | ``` 33 | 34 | Create your first migration 35 | 36 | ```shell 37 | alembic revision --autogenerate 38 | ``` 39 | 40 | Upgrading the database when new migrations are created 41 | 42 | ```shell 43 | alembic upgrade head 44 | ``` 45 | 46 | ### Run fastapi app 47 | 48 | ```shell 49 | make dev 50 | ``` 51 | 52 | Check API documentation at `localhost:8000/docs` or `localhost:8000/redoc` 53 | 54 | ### Run database migrations 55 | 56 | ```shell 57 | make migrate 58 | ``` 59 | 60 | ### Run tests 61 | 62 | ```shell 63 | make test 64 | ``` 65 | -------------------------------------------------------------------------------- /alembic.ini: -------------------------------------------------------------------------------- 1 | # A generic, single database configuration. 2 | 3 | [alembic] 4 | # path to migration scripts 5 | script_location = twitter_api:database/migrations 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_%%(rev)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>=3.9 or backports.zoneinfo library. 20 | # Any required deps can installed by adding `migrations[tz]` to the pip requirements 21 | # string value is passed to ZoneInfo() 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 migrations/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:migrations/versions 43 | 44 | # version path separator; As mentioned above, this is the character used to split 45 | # version_locations. The default within new migrations.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 | # set to 'true' to search source files recursively 55 | # in each "version_locations" directory 56 | # new in Alembic version 1.10 57 | # recursive_version_locations = false 58 | 59 | # the output encoding used when revision files 60 | # are written from script.py.mako 61 | # output_encoding = utf-8 62 | 63 | # sqlalchemy.url = 64 | 65 | 66 | [post_write_hooks] 67 | # post_write_hooks defines scripts or Python functions that are run 68 | # on newly generated revision scripts. See the documentation for further 69 | # detail and examples 70 | 71 | # format using "black" - use the console_scripts runner, against the "black" entrypoint 72 | # hooks = black 73 | # black.type = console_scripts 74 | # black.entrypoint = black 75 | # black.options = -l 79 REVISION_SCRIPT_FILENAME 76 | 77 | # lint with attempts to fix using "ruff" - use the exec runner, execute a binary 78 | # hooks = ruff 79 | # ruff.type = exec 80 | # ruff.executable = %(here)s/.venv/bin/ruff 81 | # ruff.options = --fix REVISION_SCRIPT_FILENAME 82 | 83 | # Logging configuration 84 | [loggers] 85 | keys = root,sqlalchemy,alembic 86 | 87 | [handlers] 88 | keys = console 89 | 90 | [formatters] 91 | keys = generic 92 | 93 | [logger_root] 94 | level = WARN 95 | handlers = console 96 | qualname = 97 | 98 | [logger_sqlalchemy] 99 | level = WARN 100 | handlers = 101 | qualname = sqlalchemy.engine 102 | 103 | [logger_alembic] 104 | level = INFO 105 | handlers = 106 | qualname = alembic 107 | 108 | [handler_console] 109 | class = StreamHandler 110 | args = (sys.stderr,) 111 | level = NOTSET 112 | formatter = generic 113 | 114 | [formatter_generic] 115 | format = %(levelname)-5.5s [%(name)s] %(message)s 116 | datefmt = %H:%M:%S 117 | -------------------------------------------------------------------------------- /analytics/Dockerfile: -------------------------------------------------------------------------------- 1 | 2 | FROM python:3.11-slim-bullseye 3 | LABEL maintainer="bindruid" 4 | 5 | ENV PYTHONUNBUFFERED 1 6 | ENV PYTHONDONTWRITEBYTECODE 1 7 | 8 | COPY ./analytics/requirements.txt /code/ 9 | RUN pip install -r /code/requirements.txt 10 | 11 | WORKDIR /code/ 12 | EXPOSE 50051 13 | ENTRYPOINT ["python", "main.py"] 14 | 15 | -------------------------------------------------------------------------------- /analytics/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/analytics/__init__.py -------------------------------------------------------------------------------- /analytics/alembic.ini: -------------------------------------------------------------------------------- 1 | # A generic, single database configuration. 2 | 3 | [alembic] 4 | # path to migration scripts 5 | script_location = database/migrations 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_%%(rev)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>=3.9 or backports.zoneinfo library. 20 | # Any required deps can installed by adding `migrations[tz]` to the pip requirements 21 | # string value is passed to ZoneInfo() 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 migrations/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:migrations/versions 43 | 44 | # version path separator; As mentioned above, this is the character used to split 45 | # version_locations. The default within new migrations.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 | # set to 'true' to search source files recursively 55 | # in each "version_locations" directory 56 | # new in Alembic version 1.10 57 | # recursive_version_locations = false 58 | 59 | # the output encoding used when revision files 60 | # are written from script.py.mako 61 | # output_encoding = utf-8 62 | 63 | # sqlalchemy.url = 64 | 65 | 66 | [post_write_hooks] 67 | # post_write_hooks defines scripts or Python functions that are run 68 | # on newly generated revision scripts. See the documentation for further 69 | # detail and examples 70 | 71 | # format using "black" - use the console_scripts runner, against the "black" entrypoint 72 | # hooks = black 73 | # black.type = console_scripts 74 | # black.entrypoint = black 75 | # black.options = -l 79 REVISION_SCRIPT_FILENAME 76 | 77 | # lint with attempts to fix using "ruff" - use the exec runner, execute a binary 78 | # hooks = ruff 79 | # ruff.type = exec 80 | # ruff.executable = %(here)s/.venv/bin/ruff 81 | # ruff.options = --fix REVISION_SCRIPT_FILENAME 82 | 83 | # Logging configuration 84 | [loggers] 85 | keys = root,sqlalchemy,alembic 86 | 87 | [handlers] 88 | keys = console 89 | 90 | [formatters] 91 | keys = generic 92 | 93 | [logger_root] 94 | level = WARN 95 | handlers = console 96 | qualname = 97 | 98 | [logger_sqlalchemy] 99 | level = WARN 100 | handlers = 101 | qualname = sqlalchemy.engine 102 | 103 | [logger_alembic] 104 | level = INFO 105 | handlers = 106 | qualname = alembic 107 | 108 | [handler_console] 109 | class = StreamHandler 110 | args = (sys.stderr,) 111 | level = NOTSET 112 | formatter = generic 113 | 114 | [formatter_generic] 115 | format = %(levelname)-5.5s [%(name)s] %(message)s 116 | datefmt = %H:%M:%S 117 | -------------------------------------------------------------------------------- /analytics/database/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/analytics/database/__init__.py -------------------------------------------------------------------------------- /analytics/database/configs.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from sqlalchemy import MetaData, create_engine 4 | from sqlalchemy.ext.declarative import declarative_base 5 | 6 | db_url = str(os.getenv('DB_URL')) 7 | engine = create_engine(db_url) 8 | 9 | POSTGRES_INDEXES_NAMING_CONVENTION = { 10 | 'ix': '%(column_0_label)s_idx', 11 | 'uq': '%(table_name)s_%(column_0_name)s_key', 12 | 'ck': '%(table_name)s_%(constraint_name)s_check', 13 | 'fk': '%(table_name)s_%(column_0_name)s_fkey', 14 | 'pk': '%(table_name)s_pkey', 15 | } 16 | 17 | metadata = MetaData(naming_convention=POSTGRES_INDEXES_NAMING_CONVENTION) 18 | 19 | Base = declarative_base(metadata=metadata) 20 | Base.metadata.create_all(engine) 21 | -------------------------------------------------------------------------------- /analytics/database/migrations/README: -------------------------------------------------------------------------------- 1 | Generic single-database configuration. -------------------------------------------------------------------------------- /analytics/database/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/analytics/database/migrations/__init__.py -------------------------------------------------------------------------------- /analytics/database/migrations/env.py: -------------------------------------------------------------------------------- 1 | from logging.config import fileConfig 2 | from sqlalchemy import engine_from_config 3 | from sqlalchemy import pool 4 | 5 | from alembic import context 6 | from database.models import PostView 7 | from database.configs import Base, db_url 8 | # this is the Alembic Config object, which provides 9 | # access to the values within the .ini file in use. 10 | config = context.config 11 | 12 | # Interpret the config file for Python logging. 13 | # This line sets up loggers basically. 14 | if config.config_file_name is not None: 15 | fileConfig(config.config_file_name) 16 | 17 | config.set_main_option('sqlalchemy.url', db_url) 18 | 19 | # add your model's MetaData object here 20 | # for 'autogenerate' support 21 | # from myapp import mymodel 22 | # target_metadata = mymodel.Base.metadata 23 | target_metadata = Base.metadata 24 | 25 | # other values from the config, defined by the needs of env.py, 26 | # can be acquired: 27 | # my_important_option = config.get_main_option("my_important_option") 28 | # ... etc. 29 | 30 | 31 | def run_migrations_offline() -> None: 32 | """Run migrations in 'offline' mode. 33 | 34 | This configures the context with just a URL 35 | and not an Engine, though an Engine is acceptable 36 | here as well. By skipping the Engine creation 37 | we don't even need a DBAPI to be available. 38 | 39 | Calls to context.execute() here emit the given string to the 40 | script output. 41 | 42 | """ 43 | url = config.get_main_option("sqlalchemy.url") 44 | context.configure( 45 | url=url, 46 | target_metadata=target_metadata, 47 | literal_binds=True, 48 | dialect_opts={"paramstyle": "named"}, 49 | ) 50 | 51 | with context.begin_transaction(): 52 | context.run_migrations() 53 | 54 | 55 | def run_migrations_online() -> None: 56 | """Run migrations in 'online' mode. 57 | 58 | In this scenario we need to create an Engine 59 | and associate a connection with the context. 60 | 61 | """ 62 | connectable = engine_from_config( 63 | config.get_section(config.config_ini_section, {}), 64 | prefix="sqlalchemy.", 65 | poolclass=pool.NullPool, 66 | ) 67 | 68 | with connectable.connect() as connection: 69 | context.configure( 70 | connection=connection, target_metadata=target_metadata 71 | ) 72 | 73 | with context.begin_transaction(): 74 | context.run_migrations() 75 | 76 | 77 | if context.is_offline_mode(): 78 | run_migrations_offline() 79 | else: 80 | run_migrations_online() 81 | -------------------------------------------------------------------------------- /analytics/database/migrations/script.py.mako: -------------------------------------------------------------------------------- 1 | """${message} 2 | 3 | Revision ID: ${up_revision} 4 | Revises: ${down_revision | comma,n} 5 | Create Date: ${create_date} 6 | 7 | """ 8 | from typing import Sequence, Union 9 | 10 | from alembic import op 11 | import sqlalchemy as sa 12 | ${imports if imports else ""} 13 | 14 | # revision identifiers, used by Alembic. 15 | revision: str = ${repr(up_revision)} 16 | down_revision: Union[str, None] = ${repr(down_revision)} 17 | branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} 18 | depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} 19 | 20 | 21 | def upgrade() -> None: 22 | ${upgrades if upgrades else "pass"} 23 | 24 | 25 | def downgrade() -> None: 26 | ${downgrades if downgrades else "pass"} 27 | -------------------------------------------------------------------------------- /analytics/database/migrations/versions/2024-06-06_eeddc49b11f8.py: -------------------------------------------------------------------------------- 1 | """empty message 2 | 3 | Revision ID: eeddc49b11f8 4 | Revises: 5 | Create Date: 2024-06-06 10:58:16.985669 6 | 7 | """ 8 | from typing import Sequence, Union 9 | 10 | from alembic import op 11 | import sqlalchemy as sa 12 | 13 | 14 | # revision identifiers, used by Alembic. 15 | revision: str = 'eeddc49b11f8' 16 | down_revision: Union[str, None] = None 17 | branch_labels: Union[str, Sequence[str], None] = None 18 | depends_on: Union[str, Sequence[str], None] = None 19 | 20 | 21 | def upgrade() -> None: 22 | # ### commands auto generated by Alembic - please adjust! ### 23 | op.create_table('views', 24 | sa.Column('id', sa.Integer(), nullable=False), 25 | sa.Column('post_id', sa.Integer(), nullable=False), 26 | sa.Column('count', sa.Integer(), nullable=True), 27 | sa.Column('created_at', sa.DateTime(), nullable=True), 28 | sa.Column('updated_at', sa.DateTime(), nullable=True), 29 | sa.PrimaryKeyConstraint('id', name=op.f('views_pkey')), 30 | sa.UniqueConstraint('post_id', name='unique_view_for_post_relations') 31 | ) 32 | op.create_index(op.f('views_post_id_idx'), 'views', ['post_id'], unique=True) 33 | # ### end Alembic commands ### 34 | 35 | 36 | def downgrade() -> None: 37 | # ### commands auto generated by Alembic - please adjust! ### 38 | op.drop_index(op.f('views_post_id_idx'), table_name='views') 39 | op.drop_table('views') 40 | # ### end Alembic commands ### 41 | -------------------------------------------------------------------------------- /analytics/database/migrations/versions/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/analytics/database/migrations/versions/__init__.py -------------------------------------------------------------------------------- /analytics/database/models.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | from sqlalchemy import Column, DateTime, Integer, UniqueConstraint 4 | 5 | from .configs import Base 6 | 7 | 8 | class PostView(Base): 9 | __tablename__ = 'views' 10 | __table_args__ = (UniqueConstraint('post_id', name='unique_view_for_post_relations'),) 11 | 12 | id = Column(Integer, primary_key=True) 13 | created_at = Column(DateTime, default=datetime.utcnow) 14 | updated_at = Column(DateTime, default=datetime.utcnow) 15 | post_id = Column(Integer, unique=True, index=True, nullable=False) 16 | count = Column(Integer, default=0) 17 | -------------------------------------------------------------------------------- /analytics/main.py: -------------------------------------------------------------------------------- 1 | import os 2 | from concurrent import futures 3 | 4 | import grpc 5 | from service import ViewAnalyticsService, post_views_pb2_grpc 6 | from service.logger import logger 7 | 8 | 9 | def runserver(): 10 | server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) 11 | post_views_pb2_grpc.add_PostViewAnalyticsServicer_to_server(ViewAnalyticsService(), server) 12 | server_port = os.getenv('ANALYTICS_PORT', default=50051) 13 | server.add_insecure_port(f'[::]:{server_port}') 14 | logger.info(f'GRPC server running on 0.0.0.0:{server_port}') 15 | server.start() 16 | server.wait_for_termination() 17 | 18 | 19 | if __name__ == '__main__': 20 | runserver() 21 | -------------------------------------------------------------------------------- /analytics/requirements.txt: -------------------------------------------------------------------------------- 1 | psycopg2-binary 2 | sqlalchemy 3 | alembic 4 | grpcio-tools 5 | rich 6 | -------------------------------------------------------------------------------- /analytics/service/__init__.py: -------------------------------------------------------------------------------- 1 | from . import post_views_pb2_grpc 2 | from .grpc import ViewAnalyticsService 3 | -------------------------------------------------------------------------------- /analytics/service/grpc.py: -------------------------------------------------------------------------------- 1 | import grpc 2 | from sqlalchemy.orm import Session, sessionmaker 3 | 4 | from database.configs import engine 5 | from database.models import PostView 6 | 7 | from . import post_views_pb2, post_views_pb2_grpc 8 | from .logger import logger 9 | 10 | 11 | def get_db_session() -> Session: 12 | session_class = sessionmaker(bind=engine) 13 | session = session_class() 14 | return session 15 | 16 | 17 | class ViewAnalyticsService(post_views_pb2_grpc.PostViewAnalyticsServicer): 18 | def GetViewCount(self, request, context): 19 | post_id = request.post_id 20 | logger.info(f'Counting views for post #{post_id}') 21 | db_session = get_db_session() 22 | post_view = db_session.query(PostView).filter(PostView.post_id == post_id).one_or_none() 23 | if post_view is None: 24 | context.abort(grpc.StatusCode.NOT_FOUND, f'Post #{post_id} not found') 25 | return post_views_pb2.PostViewResponse(post_id=post_id, post_view_count=post_view.count) 26 | 27 | def CreateViewCount(self, request, context): 28 | post_id = request.post_id 29 | logger.info(f'Creating view entry for post #{post_id}') 30 | db_session = get_db_session() 31 | post_view = db_session.query(PostView).filter(PostView.post_id == post_id).one_or_none() 32 | if post_view is not None: 33 | context.abort(grpc.StatusCode.ALREADY_EXISTS, f'View record for post #{post_id} already exists') 34 | new_post_view = PostView(post_id=post_id, count=0) 35 | db_session.add(new_post_view) 36 | db_session.commit() 37 | return post_views_pb2.PostViewResponse(post_id=post_id, post_view_count=0) 38 | 39 | def UpdateViewCount(self, request, context): 40 | post_id = request.post_id 41 | logger.info(f'Increasing view count entry for post #{post_id}') 42 | db_session = get_db_session() 43 | post_view = db_session.query(PostView).filter(PostView.post_id == post_id).one_or_none() 44 | if post_view is None: 45 | context.abort(grpc.StatusCode.NOT_FOUND, f'Post #{post_id} not found') 46 | post_view.count = post_view.count + 1 47 | db_session.commit() 48 | return post_views_pb2.PostViewResponse(post_id=post_id, post_view_count=post_view.count) 49 | 50 | def DeleteViewCount(self, request, context): 51 | post_id = request.post_id 52 | logger.info(f'Deleting view entry for post #{post_id}') 53 | db_session = get_db_session() 54 | post_view = db_session.query(PostView).filter(PostView.post_id == post_id).one_or_none() 55 | if post_view is None: 56 | context.abort(grpc.StatusCode.NOT_FOUND, f'Post #{post_id} not found') 57 | db_session.delete(post_view) 58 | db_session.commit() 59 | return post_views_pb2.PostViewResponse(post_id=post_id, post_view_count=0) 60 | -------------------------------------------------------------------------------- /analytics/service/logger.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from rich.logging import RichHandler 4 | 5 | logger = logging.getLogger(__name__) 6 | 7 | handler = RichHandler() 8 | 9 | logger.setLevel(logging.DEBUG) 10 | handler.setLevel(logging.DEBUG) 11 | 12 | handler.setFormatter(logging.Formatter('%(message)s')) 13 | 14 | logger.addHandler(handler) 15 | -------------------------------------------------------------------------------- /analytics/service/post_views.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | message PostViewRequest { 4 | int32 post_id = 1; 5 | } 6 | 7 | message PostViewResponse { 8 | int32 post_id = 1; 9 | int32 post_view_count = 2; 10 | } 11 | 12 | service PostViewAnalytics { 13 | rpc GetViewCount (PostViewRequest) returns (PostViewResponse); 14 | rpc CreateViewCount (PostViewRequest) returns (PostViewResponse); 15 | rpc UpdateViewCount (PostViewRequest) returns (PostViewResponse); 16 | rpc DeleteViewCount (PostViewRequest) returns (PostViewResponse); 17 | } 18 | -------------------------------------------------------------------------------- /analytics/service/post_views_pb2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by the protocol buffer compiler. DO NOT EDIT! 3 | # source: post_views.proto 4 | # Protobuf Python Version: 5.26.1 5 | """Generated protocol buffer code.""" 6 | from google.protobuf import descriptor as _descriptor 7 | from google.protobuf import descriptor_pool as _descriptor_pool 8 | from google.protobuf import symbol_database as _symbol_database 9 | from google.protobuf.internal import builder as _builder 10 | 11 | # @@protoc_insertion_point(imports) 12 | 13 | _sym_db = _symbol_database.Default() 14 | 15 | 16 | 17 | 18 | DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x10post_views.proto\"\"\n\x0fPostViewRequest\x12\x0f\n\x07post_id\x18\x01 \x01(\x05\"<\n\x10PostViewResponse\x12\x0f\n\x07post_id\x18\x01 \x01(\x05\x12\x17\n\x0fpost_view_count\x18\x02 \x01(\x05\x32\xf0\x01\n\x11PostViewAnalytics\x12\x33\n\x0cGetViewCount\x12\x10.PostViewRequest\x1a\x11.PostViewResponse\x12\x36\n\x0f\x43reateViewCount\x12\x10.PostViewRequest\x1a\x11.PostViewResponse\x12\x36\n\x0fUpdateViewCount\x12\x10.PostViewRequest\x1a\x11.PostViewResponse\x12\x36\n\x0f\x44\x65leteViewCount\x12\x10.PostViewRequest\x1a\x11.PostViewResponseb\x06proto3') 19 | 20 | _globals = globals() 21 | _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) 22 | _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'post_views_pb2', _globals) 23 | if not _descriptor._USE_C_DESCRIPTORS: 24 | DESCRIPTOR._loaded_options = None 25 | _globals['_POSTVIEWREQUEST']._serialized_start=20 26 | _globals['_POSTVIEWREQUEST']._serialized_end=54 27 | _globals['_POSTVIEWRESPONSE']._serialized_start=56 28 | _globals['_POSTVIEWRESPONSE']._serialized_end=116 29 | _globals['_POSTVIEWANALYTICS']._serialized_start=119 30 | _globals['_POSTVIEWANALYTICS']._serialized_end=359 31 | # @@protoc_insertion_point(module_scope) 32 | -------------------------------------------------------------------------------- /analytics/service/post_views_pb2.pyi: -------------------------------------------------------------------------------- 1 | from google.protobuf import descriptor as _descriptor 2 | from google.protobuf import message as _message 3 | from typing import ClassVar as _ClassVar, Optional as _Optional 4 | 5 | DESCRIPTOR: _descriptor.FileDescriptor 6 | 7 | class PostViewRequest(_message.Message): 8 | __slots__ = ("post_id",) 9 | POST_ID_FIELD_NUMBER: _ClassVar[int] 10 | post_id: int 11 | def __init__(self, post_id: _Optional[int] = ...) -> None: ... 12 | 13 | class PostViewResponse(_message.Message): 14 | __slots__ = ("post_id", "post_view_count") 15 | POST_ID_FIELD_NUMBER: _ClassVar[int] 16 | POST_VIEW_COUNT_FIELD_NUMBER: _ClassVar[int] 17 | post_id: int 18 | post_view_count: int 19 | def __init__(self, post_id: _Optional[int] = ..., post_view_count: _Optional[int] = ...) -> None: ... 20 | -------------------------------------------------------------------------------- /analytics/service/post_views_pb2_grpc.py: -------------------------------------------------------------------------------- 1 | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! 2 | """Client and server classes corresponding to protobuf-defined services.""" 3 | import warnings 4 | 5 | import grpc 6 | from . import post_views_pb2 as post__views__pb2 7 | 8 | GRPC_GENERATED_VERSION = '1.64.1' 9 | GRPC_VERSION = grpc.__version__ 10 | EXPECTED_ERROR_RELEASE = '1.65.0' 11 | SCHEDULED_RELEASE_DATE = 'June 25, 2024' 12 | _version_not_supported = False 13 | 14 | try: 15 | from grpc._utilities import first_version_is_lower 16 | _version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION) 17 | except ImportError: 18 | _version_not_supported = True 19 | 20 | if _version_not_supported: 21 | warnings.warn( 22 | f'The grpc package installed is at version {GRPC_VERSION},' 23 | + f' but the generated code in post_views_pb2_grpc.py depends on' 24 | + f' grpcio>={GRPC_GENERATED_VERSION}.' 25 | + f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}' 26 | + f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.' 27 | + f' This warning will become an error in {EXPECTED_ERROR_RELEASE},' 28 | + f' scheduled for release on {SCHEDULED_RELEASE_DATE}.', 29 | RuntimeWarning 30 | ) 31 | 32 | 33 | class PostViewAnalyticsStub(object): 34 | """Missing associated documentation comment in .proto file.""" 35 | 36 | def __init__(self, channel): 37 | """Constructor. 38 | 39 | Args: 40 | channel: A grpc.Channel. 41 | """ 42 | self.GetViewCount = channel.unary_unary( 43 | '/PostViewAnalytics/GetViewCount', 44 | request_serializer=post__views__pb2.PostViewRequest.SerializeToString, 45 | response_deserializer=post__views__pb2.PostViewResponse.FromString, 46 | _registered_method=True) 47 | self.CreateViewCount = channel.unary_unary( 48 | '/PostViewAnalytics/CreateViewCount', 49 | request_serializer=post__views__pb2.PostViewRequest.SerializeToString, 50 | response_deserializer=post__views__pb2.PostViewResponse.FromString, 51 | _registered_method=True) 52 | self.UpdateViewCount = channel.unary_unary( 53 | '/PostViewAnalytics/UpdateViewCount', 54 | request_serializer=post__views__pb2.PostViewRequest.SerializeToString, 55 | response_deserializer=post__views__pb2.PostViewResponse.FromString, 56 | _registered_method=True) 57 | self.DeleteViewCount = channel.unary_unary( 58 | '/PostViewAnalytics/DeleteViewCount', 59 | request_serializer=post__views__pb2.PostViewRequest.SerializeToString, 60 | response_deserializer=post__views__pb2.PostViewResponse.FromString, 61 | _registered_method=True) 62 | 63 | 64 | class PostViewAnalyticsServicer(object): 65 | """Missing associated documentation comment in .proto file.""" 66 | 67 | def GetViewCount(self, request, context): 68 | """Missing associated documentation comment in .proto file.""" 69 | context.set_code(grpc.StatusCode.UNIMPLEMENTED) 70 | context.set_details('Method not implemented!') 71 | raise NotImplementedError('Method not implemented!') 72 | 73 | def CreateViewCount(self, request, context): 74 | """Missing associated documentation comment in .proto file.""" 75 | context.set_code(grpc.StatusCode.UNIMPLEMENTED) 76 | context.set_details('Method not implemented!') 77 | raise NotImplementedError('Method not implemented!') 78 | 79 | def UpdateViewCount(self, request, context): 80 | """Missing associated documentation comment in .proto file.""" 81 | context.set_code(grpc.StatusCode.UNIMPLEMENTED) 82 | context.set_details('Method not implemented!') 83 | raise NotImplementedError('Method not implemented!') 84 | 85 | def DeleteViewCount(self, request, context): 86 | """Missing associated documentation comment in .proto file.""" 87 | context.set_code(grpc.StatusCode.UNIMPLEMENTED) 88 | context.set_details('Method not implemented!') 89 | raise NotImplementedError('Method not implemented!') 90 | 91 | 92 | def add_PostViewAnalyticsServicer_to_server(servicer, server): 93 | rpc_method_handlers = { 94 | 'GetViewCount': grpc.unary_unary_rpc_method_handler( 95 | servicer.GetViewCount, 96 | request_deserializer=post__views__pb2.PostViewRequest.FromString, 97 | response_serializer=post__views__pb2.PostViewResponse.SerializeToString, 98 | ), 99 | 'CreateViewCount': grpc.unary_unary_rpc_method_handler( 100 | servicer.CreateViewCount, 101 | request_deserializer=post__views__pb2.PostViewRequest.FromString, 102 | response_serializer=post__views__pb2.PostViewResponse.SerializeToString, 103 | ), 104 | 'UpdateViewCount': grpc.unary_unary_rpc_method_handler( 105 | servicer.UpdateViewCount, 106 | request_deserializer=post__views__pb2.PostViewRequest.FromString, 107 | response_serializer=post__views__pb2.PostViewResponse.SerializeToString, 108 | ), 109 | 'DeleteViewCount': grpc.unary_unary_rpc_method_handler( 110 | servicer.DeleteViewCount, 111 | request_deserializer=post__views__pb2.PostViewRequest.FromString, 112 | response_serializer=post__views__pb2.PostViewResponse.SerializeToString, 113 | ), 114 | } 115 | generic_handler = grpc.method_handlers_generic_handler( 116 | 'PostViewAnalytics', rpc_method_handlers) 117 | server.add_generic_rpc_handlers((generic_handler,)) 118 | server.add_registered_method_handlers('PostViewAnalytics', rpc_method_handlers) 119 | 120 | 121 | # This class is part of an EXPERIMENTAL API. 122 | class PostViewAnalytics(object): 123 | """Missing associated documentation comment in .proto file.""" 124 | 125 | @staticmethod 126 | def GetViewCount(request, 127 | target, 128 | options=(), 129 | channel_credentials=None, 130 | call_credentials=None, 131 | insecure=False, 132 | compression=None, 133 | wait_for_ready=None, 134 | timeout=None, 135 | metadata=None): 136 | return grpc.experimental.unary_unary( 137 | request, 138 | target, 139 | '/PostViewAnalytics/GetViewCount', 140 | post__views__pb2.PostViewRequest.SerializeToString, 141 | post__views__pb2.PostViewResponse.FromString, 142 | options, 143 | channel_credentials, 144 | insecure, 145 | call_credentials, 146 | compression, 147 | wait_for_ready, 148 | timeout, 149 | metadata, 150 | _registered_method=True) 151 | 152 | @staticmethod 153 | def CreateViewCount(request, 154 | target, 155 | options=(), 156 | channel_credentials=None, 157 | call_credentials=None, 158 | insecure=False, 159 | compression=None, 160 | wait_for_ready=None, 161 | timeout=None, 162 | metadata=None): 163 | return grpc.experimental.unary_unary( 164 | request, 165 | target, 166 | '/PostViewAnalytics/CreateViewCount', 167 | post__views__pb2.PostViewRequest.SerializeToString, 168 | post__views__pb2.PostViewResponse.FromString, 169 | options, 170 | channel_credentials, 171 | insecure, 172 | call_credentials, 173 | compression, 174 | wait_for_ready, 175 | timeout, 176 | metadata, 177 | _registered_method=True) 178 | 179 | @staticmethod 180 | def UpdateViewCount(request, 181 | target, 182 | options=(), 183 | channel_credentials=None, 184 | call_credentials=None, 185 | insecure=False, 186 | compression=None, 187 | wait_for_ready=None, 188 | timeout=None, 189 | metadata=None): 190 | return grpc.experimental.unary_unary( 191 | request, 192 | target, 193 | '/PostViewAnalytics/UpdateViewCount', 194 | post__views__pb2.PostViewRequest.SerializeToString, 195 | post__views__pb2.PostViewResponse.FromString, 196 | options, 197 | channel_credentials, 198 | insecure, 199 | call_credentials, 200 | compression, 201 | wait_for_ready, 202 | timeout, 203 | metadata, 204 | _registered_method=True) 205 | 206 | @staticmethod 207 | def DeleteViewCount(request, 208 | target, 209 | options=(), 210 | channel_credentials=None, 211 | call_credentials=None, 212 | insecure=False, 213 | compression=None, 214 | wait_for_ready=None, 215 | timeout=None, 216 | metadata=None): 217 | return grpc.experimental.unary_unary( 218 | request, 219 | target, 220 | '/PostViewAnalytics/DeleteViewCount', 221 | post__views__pb2.PostViewRequest.SerializeToString, 222 | post__views__pb2.PostViewResponse.FromString, 223 | options, 224 | channel_credentials, 225 | insecure, 226 | call_credentials, 227 | compression, 228 | wait_for_ready, 229 | timeout, 230 | metadata, 231 | _registered_method=True) 232 | -------------------------------------------------------------------------------- /api_test.http: -------------------------------------------------------------------------------- 1 | ### 2 | POST {{base_url}}/auth/ 3 | Content-Type: application/json 4 | 5 | {"email": "a.abharya@gmail.com", 6 | "username": "druid", 7 | "password": "123456" 8 | } 9 | ### 10 | 11 | POST {{base_url}}/auth/login/ 12 | Content-Type: application/json 13 | 14 | {"username": "druid", 15 | "password": "123456" 16 | } 17 | ### 18 | 19 | GET {{base_url}}/users/profile/1/ 20 | Accept: application/json 21 | Authorization: Bearer {{token_1}} 22 | 23 | ### 24 | DELETE {{base_url}}/users/profile/1/ 25 | Accept: application/json 26 | Authorization: Bearer {{token_2}} 27 | ### 28 | 29 | ### 30 | GET {{base_url}}/users/1/followers/ 31 | Accept: application/json 32 | Authorization: Bearer {{token_1}} 33 | ### 34 | 35 | ### 36 | GET {{base_url}}/users/1/followings/ 37 | Accept: application/json 38 | Authorization: Bearer {{token_1}} 39 | ### 40 | 41 | ### 42 | POST {{base_url}}/users/1/followings/ 43 | Accept: application/json 44 | Authorization: Bearer {{token_1}} 45 | 46 | {"user_id": 2 47 | } 48 | ### 49 | 50 | ### 51 | DELETE {{base_url}}/users/2/followers/1/ 52 | Accept: application/json 53 | Authorization: Bearer {{token_2}} 54 | ### 55 | 56 | 57 | DELETE {{base_url}}/users/1/followings/2/ 58 | Accept: application/json 59 | Authorization: Bearer {{token_1}} 60 | ### 61 | 62 | POST {{base_url}}/posts/ 63 | Content-Type: application/json 64 | Authorization: Bearer {{token_1}} 65 | 66 | {"content": "this my 1 tweet" 67 | } 68 | 69 | ### 70 | 71 | GET {{base_url}}/posts/druid/ 72 | Accept: application/json 73 | Authorization: Bearer {{token_1}} 74 | 75 | ### 76 | GET {{base_url}}/posts/druid/2/ 77 | Accept: application/json 78 | Authorization: Bearer {{token_1}} 79 | 80 | ### 81 | GET {{base_url}}/posts/druid/2/mentions/ 82 | Content-Type: application/json 83 | Authorization: Bearer {{token_1}} 84 | 85 | ### 86 | 87 | ### 88 | POST {{base_url}}/posts/druid/2/mentions/ 89 | Content-Type: application/json 90 | Authorization: Bearer {{token_1}} 91 | 92 | {"content": "this is my second mention" 93 | } 94 | ### 95 | 96 | ### 97 | GET {{base_url}}/posts/druid/1/quotes/ 98 | Content-Type: application/json 99 | Authorization:8 Bearer {{token_1}} 100 | ### 101 | 102 | ### 103 | POST {{base_url}}/posts/druid/1/quotes/ 104 | Content-Type: application/json 105 | Authorization: Bearer {{token_1}} 106 | 107 | {"content": "this is my third quote" 108 | } 109 | ### 110 | 111 | 112 | PATCH {{base_url}}/posts/1/ 113 | Content-Type: application/json 114 | Authorization: Bearer {{token_1}} 115 | 116 | {"content": "this is first message" 117 | } 118 | 119 | ### 120 | DELETE {{base_url}}/posts/2/ 121 | Accept: application/json 122 | Authorization: Bearer {{token_1}} 123 | ### 124 | 125 | ### 126 | GET {{base_url}}/engagements/statistics/2/ 127 | Accept: application/json 128 | Authorization: Bearer {{token_1}} 129 | ### 130 | 131 | ### 132 | POST {{base_url}}/engagements/likes/2/ 133 | Accept: application/json 134 | Authorization: Bearer {{token_1}} 135 | ### 136 | 137 | ### 138 | DELETE {{base_url}}/engagements/likes/2/ 139 | Accept: application/json 140 | Authorization: Bearer {{token_1}} 141 | ### 142 | 143 | 144 | ### 145 | GET {{base_url}}/engagements/views/2/ 146 | Accept: application/json 147 | Authorization: Bearer {{token_1}} 148 | ### 149 | 150 | ### 151 | GET {{base_url}}/engagements/likes/1/ 152 | Accept: application/json 153 | Authorization: Bearer {{token_1}} 154 | ### 155 | 156 | ### 157 | GET {{base_url}}/engagements/bookmarks/1/ 158 | Accept: application/json 159 | Authorization: Bearer {{token_1}} 160 | ### 161 | 162 | ### 163 | POST {{base_url}}/engagements/bookmarks/1/ 164 | Accept: application/json 165 | Authorization: Bearer {{token_1}} 166 | ### 167 | -------------------------------------------------------------------------------- /docker-compose-dev.yml: -------------------------------------------------------------------------------- 1 | version: '3.9' 2 | 3 | volumes: 4 | TWITTER_DATA: 5 | ANALYTICS_DATA: 6 | 7 | networks: 8 | TWITTER_BACKEND: 9 | 10 | services: 11 | twitter_db: 12 | image: "postgres:15-alpine" 13 | restart: "no" 14 | ports: 15 | - "5314:5432" 16 | environment: 17 | POSTGRES_USER: twitter_api 18 | POSTGRES_PASSWORD: 123456 19 | PGPASSWORD: 123456 20 | POSTGRES_DB: twitter_api 21 | PGDATA: /db_data 22 | volumes: 23 | - TWITTER_DATA:/db_data 24 | networks: 25 | - TWITTER_BACKEND 26 | 27 | 28 | analytics_db: 29 | image: "postgres:15-alpine" 30 | restart: "no" 31 | environment: 32 | POSTGRES_USER: analytics_api 33 | POSTGRES_PASSWORD: 123456 34 | PGPASSWORD: 123456 35 | POSTGRES_DB: analytics_api 36 | PGDATA: /db_data 37 | volumes: 38 | - ANALYTICS_DATA:/db_data 39 | networks: 40 | - TWITTER_BACKEND 41 | 42 | analytics: 43 | build: 44 | context: . 45 | dockerfile: ./analytics/Dockerfile 46 | restart: "no" 47 | volumes: 48 | - ./analytics:/code 49 | environment: 50 | DB_URL: "postgresql://analytics_api:123456@analytics_db:5432/analytics_api" 51 | ANALYTICS_PORT: 50051 52 | depends_on: 53 | - analytics_db 54 | networks: 55 | - TWITTER_BACKEND 56 | 57 | twitter_api: 58 | build: 59 | context: . 60 | dockerfile: ./Dockerfile 61 | restart: "no" 62 | volumes: 63 | - ./twitter_api:/code/twitter_api/ 64 | - ./logs:/code/logs 65 | environment: 66 | ENVIRONMENT: LOCAL 67 | DB_URL: postgresql://twitter_api:123456@twitter_db:5432/twitter_api 68 | ANALYTICS_HOST: analytics 69 | ANALYTICS_PORT: 50051 70 | SECRET_KEY: super_secret_key 71 | JWT_SECRET: super_jwt_secret_key 72 | SENTRY_ENABLED: 0 73 | SENTRY_DSN: localhost" 74 | 75 | depends_on: 76 | - twitter_db 77 | - analytics 78 | networks: 79 | - TWITTER_BACKEND 80 | ports: 81 | - "8000:8000" 82 | 83 | -------------------------------------------------------------------------------- /docker-compose-test.yml: -------------------------------------------------------------------------------- 1 | version: '3.9' 2 | 3 | networks: 4 | TWITTER_BACKEND_TEST: 5 | 6 | services: 7 | analytics_test_db: 8 | image: "postgres:15-alpine" 9 | restart: "no" 10 | environment: 11 | POSTGRES_USER: analytics_test_api 12 | POSTGRES_PASSWORD: 123456 13 | PGPASSWORD: 123456 14 | POSTGRES_DB: analytics_test_api 15 | PGDATA: /db_data 16 | tmpfs: 17 | - /db_data 18 | networks: 19 | - TWITTER_BACKEND_TEST 20 | 21 | analytics_test: 22 | build: 23 | context: . 24 | dockerfile: ./analytics/Dockerfile 25 | restart: "no" 26 | volumes: 27 | - ./analytics:/code 28 | environment: 29 | DB_URL: postgresql://analytics_test_api:123456@analytics_test_db:5432/analytics_test_api 30 | ANALYTICS_PORT: 50051 31 | depends_on: 32 | - analytics_test_db 33 | networks: 34 | - TWITTER_BACKEND_TEST 35 | 36 | twitter_db_test: 37 | image: "postgres:15-alpine" 38 | restart: "no" 39 | environment: 40 | POSTGRES_USER: test_twitter_api 41 | POSTGRES_PASSWORD: 123456 42 | PGPASSWORD: 123456 43 | POSTGRES_DB: test_twitter_api 44 | PGDATA: /db_data 45 | tmpfs: 46 | - /db_data 47 | networks: 48 | - TWITTER_BACKEND_TEST 49 | 50 | twitter_api_test: 51 | build: 52 | context: . 53 | dockerfile: ./Dockerfile 54 | restart: "no" 55 | volumes: 56 | - ./twitter_api:/code/twitter_api/ 57 | - ./tests:/code/tests/ 58 | - ./logs:/code/logs 59 | environment: 60 | ENVIRONMENT: TEST 61 | DB_URL: postgresql://test_twitter_api:123456@twitter_db_test:5432/test_twitter_api 62 | SECRET_KEY: super_secret_key 63 | JWT_SECRET: super_jwt_secret_key 64 | ANALYTICS_HOST: analytics_test 65 | ANALYTICS_PORT: 50051 66 | SENTRY_ENABLED: 0 67 | SENTRY_DSN: localhost" 68 | 69 | depends_on: 70 | - twitter_db_test 71 | - analytics_test 72 | networks: 73 | - TWITTER_BACKEND_TEST 74 | entrypoint: pytest -v --disable-warnings 75 | -------------------------------------------------------------------------------- /makefile: -------------------------------------------------------------------------------- 1 | DEFAULT_GOAL := dev 2 | 3 | .PHONY: dev test 4 | 5 | dev: 6 | docker compose -f docker-compose-dev.yml down 7 | docker compose -f docker-compose-dev.yml up 8 | 9 | test: 10 | docker compose -f docker-compose-test.yml down 11 | docker compose -f docker-compose-test.yml run --rm twitter_api_test || true 12 | docker compose -f docker-compose-test.yml down 13 | 14 | migrate: 15 | docker compose -f docker-compose-dev.yml exec twitter_api sh -c "alembic upgrade head" 16 | docker compose -f docker-compose-dev.yml exec analytics sh -c "alembic upgrade head" 17 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "twitter_fast_api" 3 | version = "0.1.0" 4 | description = "" 5 | authors = ["abharya.dev@gmail.com"] 6 | license = "MIT" 7 | 8 | [tool.ruff] 9 | exclude = [ 10 | '.eggs', 11 | '.git', 12 | '.ipynb_checkpoints', 13 | '.mypy_cache', 14 | '.nox', 15 | '.pants.d', 16 | '.pyenv', 17 | '.pytest_cache', 18 | '.pytype', 19 | '.ruff_cache', 20 | '.tox', 21 | '.venv', 22 | '.vscode', 23 | '__pypackages__', 24 | '_build', 25 | 'build', 26 | 'dist', 27 | 'node_modules', 28 | 'migrations', 29 | 'settings', 30 | 'site-packages', 31 | 'venv', 32 | 'post_views_pb2_grpc.py', 33 | 'post_views_pb2.py' 34 | ] 35 | src = ['twitter_api'] 36 | include = ['*.py'] 37 | line-length = 120 38 | output-format = 'grouped' 39 | target-version = 'py311' 40 | 41 | [tool.ruff.lint] 42 | # S = Bandit Security 43 | # SIM = Simplify 44 | # E = Pycodestyle Error 45 | # F = Pyflask 46 | # C4 = Comprehensions 47 | # BLE = Blind Exception 48 | # I = Isort 49 | # B = Flake8 Bugbear 50 | select = ['S', 'SIM', 'C4', 'E', 'F', 'BLE', 'I', 'B', 'N', 'ERA'] 51 | ignore = ['E501', 'N802', 'N806', 'N815'] 52 | fixable = ['I'] 53 | 54 | [tool.ruff.lint.per-file-ignores] 55 | '__init__.py' = ['F401'] 56 | '*test*.py' = ['S'] 57 | '*factories*.py' = ['S'] 58 | 59 | [tool.ruff.format] 60 | quote-style = 'single' 61 | docstring-code-format = true 62 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi 2 | pydantic 3 | pydantic-settings 4 | aiohttp 5 | sentry-asgi 6 | bcrypt 7 | python-jose 8 | typer 9 | rich 10 | psycopg2-binary 11 | sqlalchemy 12 | sqlalchemy-filters 13 | sqlalchemy-utils 14 | alembic 15 | grpcio-tools 16 | pytest 17 | faker 18 | pytz 19 | factory-boy 20 | 21 | 22 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/tests/__init__.py -------------------------------------------------------------------------------- /tests/configs.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm import scoped_session, sessionmaker 2 | from twitter_api.database import engine 3 | 4 | Session = scoped_session(sessionmaker(autocommit=False, autoflush=True, bind=engine)) 5 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | from unittest.mock import patch 2 | 3 | import pytest 4 | from fastapi.testclient import TestClient 5 | from twitter_api.database import Base, engine 6 | from twitter_api.database.depends import get_db_session 7 | from twitter_api.main import api 8 | from twitter_api.users.auth import generate_token 9 | 10 | from .configs import Session 11 | from .factories import BookmarkFactory, FollowershipFactory, LikeFactory, MentionFactory, PostFactory, UserFactory 12 | 13 | 14 | @pytest.fixture() 15 | def db(): 16 | Base.metadata.create_all(bind=engine) 17 | yield 18 | Base.metadata.drop_all(bind=engine) 19 | 20 | 21 | @pytest.fixture() 22 | def session(db): 23 | session = Session() 24 | yield session 25 | session.rollback() 26 | session.close() 27 | 28 | 29 | @pytest.fixture() 30 | def test_api(session): 31 | api.dependency_overrides[get_db_session] = lambda: session 32 | return api 33 | 34 | 35 | @pytest.fixture() 36 | def client(test_api): 37 | base_url = 'http://localhost:8000/api/v1' 38 | yield TestClient(app=test_api, base_url=base_url) 39 | 40 | 41 | @pytest.fixture() 42 | def test_user(): 43 | return UserFactory(username='bindruid', email='abharya.dev@gmail.com') 44 | 45 | 46 | @pytest.fixture() 47 | def auth_header(test_user): 48 | return {'Authorization': f'Bearer {generate_token(user=test_user)}'} 49 | 50 | 51 | @pytest.fixture() 52 | def user_as_follower(test_user): 53 | other_user = UserFactory() 54 | return FollowershipFactory(follower=test_user, following=other_user) 55 | 56 | 57 | @pytest.fixture() 58 | def user_as_following(test_user): 59 | other_user = UserFactory() 60 | return FollowershipFactory(follower=other_user, following=test_user) 61 | 62 | 63 | @pytest.fixture() 64 | def test_post(test_user): 65 | return PostFactory(author=test_user) 66 | 67 | 68 | @pytest.fixture() 69 | def post_with_quote(test_user): 70 | quoted_post = PostFactory(author=test_user) 71 | return PostFactory(author=test_user, quoted_post=quoted_post) 72 | 73 | 74 | @pytest.fixture() 75 | def post_with_mention(test_user): 76 | post = PostFactory(author=test_user) 77 | mention = PostFactory(author=test_user) 78 | return MentionFactory(mention=mention, original_post=post) 79 | 80 | 81 | @pytest.fixture() 82 | def liked_post(test_user): 83 | post = PostFactory(author=test_user) 84 | LikeFactory(user=test_user, post=post) 85 | return post 86 | 87 | 88 | @pytest.fixture() 89 | def bookmarked_post(test_user): 90 | post = PostFactory(author=test_user) 91 | BookmarkFactory(user=test_user, post=post) 92 | return post 93 | 94 | 95 | @pytest.fixture() 96 | def mocked_view_analytics_service(): 97 | with patch('twitter_api.engagements.services.count_total_views_for_post') as views_analytics_service: 98 | views_analytics_service.return_value = 1 99 | yield 100 | -------------------------------------------------------------------------------- /tests/engagements/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/tests/engagements/__init__.py -------------------------------------------------------------------------------- /tests/engagements/test_routes.py: -------------------------------------------------------------------------------- 1 | from fastapi import status 2 | 3 | from tests.factories import BookmarkFactory, LikeFactory, PostFactory, UserFactory 4 | 5 | 6 | def test_anyone_can_view_statistics_for_a_post(client, test_post, mocked_view_analytics_service): 7 | url = f'/engagements/statistics/{test_post.id}/' 8 | response = client.get(url) 9 | assert response.status_code == status.HTTP_200_OK 10 | 11 | 12 | def test_no_one_can_view_statistics_for_a_non_existing_post(client, mocked_view_analytics_service): 13 | url = '/engagements/statistics/1000/' 14 | response = client.get(url) 15 | assert response.status_code == status.HTTP_404_NOT_FOUND 16 | 17 | 18 | def test_anyone_can_view_count_of_views_for_a_post(client, test_post, mocked_view_analytics_service): 19 | url = f'/engagements/views/{test_post.id}/' 20 | response = client.get(url) 21 | assert response.status_code == status.HTTP_200_OK 22 | 23 | 24 | def test_no_one_can_view_count_of_views_for_a_non_existing_post(client, mocked_view_analytics_service): 25 | url = '/engagements/views/1000/' 26 | response = client.get(url) 27 | assert response.status_code == status.HTTP_404_NOT_FOUND 28 | 29 | 30 | def test_anyone_can_view_like_counts_for_a_post(client, liked_post): 31 | url = f'/engagements/likes/{liked_post.id}/' 32 | response = client.get(url) 33 | assert response.status_code == status.HTTP_200_OK 34 | 35 | 36 | def test_no_one_can_view_like_counts_for_a_non_existing_post(client): 37 | url = '/engagements/likes/1000/' 38 | response = client.get(url) 39 | assert response.status_code == status.HTTP_404_NOT_FOUND 40 | 41 | 42 | def test_authenticated_user_can_like_a_post(client, test_user, auth_header, test_post): 43 | url = f'/engagements/likes/{test_post.id}/' 44 | response = client.post(url, headers=auth_header) 45 | assert response.status_code == status.HTTP_201_CREATED 46 | 47 | 48 | def test_authenticated_user_can_not_like_a_post_which_already_has_liked(client, test_user, auth_header, liked_post): 49 | url = f'/engagements/likes/{liked_post.id}/' 50 | response = client.post(url, headers=auth_header) 51 | assert response.status_code == status.HTTP_400_BAD_REQUEST 52 | 53 | 54 | def test_unauthenticated_user_can_not_like_a_post(client, test_post): 55 | url = f'/engagements/likes/{test_post.id}/' 56 | response = client.post(url) 57 | assert response.status_code == status.HTTP_401_UNAUTHORIZED 58 | 59 | 60 | def test_authenticated_user_can_dislike_a_post_they_liked(client, test_user, auth_header, liked_post): 61 | url = f'/engagements/likes/{liked_post.id}/' 62 | response = client.delete(url, headers=auth_header) 63 | assert response.status_code == status.HTTP_204_NO_CONTENT 64 | 65 | 66 | def test_authenticated_user_can_not_dislike_a_post_they_did_not_like(client, test_user, auth_header, test_post): 67 | url = f'/engagements/likes/{test_post.id}/' 68 | response = client.delete(url, headers=auth_header) 69 | assert response.status_code == status.HTTP_404_NOT_FOUND 70 | 71 | 72 | def test_authenticated_user_can_not_dislike_a_post_on_behalf_of_other_user(client, test_user, auth_header): 73 | other_user = UserFactory() 74 | other_user_post = PostFactory(author=other_user) 75 | LikeFactory(user=other_user, post=other_user_post) 76 | url = f'/engagements/likes/{other_user_post.id}/' 77 | response = client.delete(url, headers=auth_header) 78 | assert response.status_code == status.HTTP_404_NOT_FOUND 79 | 80 | 81 | def test_authenticated_user_can_not_dislike_a_non_existing_post(client, test_user, auth_header): 82 | url = '/engagements/likes/1000/' 83 | response = client.delete(url, headers=auth_header) 84 | assert response.status_code == status.HTTP_404_NOT_FOUND 85 | 86 | 87 | def test_unauthenticated_user_can_not_dislike_a_post(client, liked_post): 88 | url = f'/engagements/likes/{liked_post.id}/' 89 | response = client.delete(url) 90 | assert response.status_code == status.HTTP_401_UNAUTHORIZED 91 | 92 | 93 | def test_anyone_can_view_bookmark_counts_for_a_post(client, bookmarked_post): 94 | url = f'/engagements/bookmarks/{bookmarked_post.id}/' 95 | response = client.get(url) 96 | assert response.status_code == status.HTTP_200_OK 97 | 98 | 99 | def test_no_one_can_view_bookmark_counts_for_a_non_existing_post(client): 100 | url = '/engagements/bookmarks/1000/' 101 | response = client.get(url) 102 | assert response.status_code == status.HTTP_404_NOT_FOUND 103 | 104 | 105 | def test_authenticated_user_can_bookmark_a_post(client, test_user, auth_header, test_post): 106 | url = f'/engagements/bookmarks/{test_post.id}/' 107 | response = client.post(url, headers=auth_header) 108 | assert response.status_code == status.HTTP_201_CREATED 109 | 110 | 111 | def test_authenticated_user_can_not_bookmark_a_post_which_already_has_bookmarked( 112 | client, test_user, auth_header, bookmarked_post 113 | ): 114 | url = f'/engagements/bookmarks/{bookmarked_post.id}/' 115 | response = client.post(url, headers=auth_header) 116 | assert response.status_code == status.HTTP_400_BAD_REQUEST 117 | 118 | 119 | def test_unauthenticated_user_can_not_bookmark_a_post(client, test_post): 120 | url = f'/engagements/bookmarks/{test_post.id}/' 121 | response = client.post(url) 122 | assert response.status_code == status.HTTP_401_UNAUTHORIZED 123 | 124 | 125 | def test_authenticated_user_can_un_bookmark_a_post_they_bookmarked(client, test_user, auth_header, bookmarked_post): 126 | url = f'/engagements/bookmarks/{bookmarked_post.id}/' 127 | response = client.delete(url, headers=auth_header) 128 | assert response.status_code == status.HTTP_204_NO_CONTENT 129 | 130 | 131 | def test_authenticated_user_can_not_un_bookmark_a_post_they_did_not_bookmark(client, test_user, auth_header, test_post): 132 | url = f'/engagements/bookmarks/{test_post.id}/' 133 | response = client.delete(url, headers=auth_header) 134 | assert response.status_code == status.HTTP_404_NOT_FOUND 135 | 136 | 137 | def test_authenticated_user_can_not_un_bookmark_a_post_on_behalf_of_other_user(client, test_user, auth_header): 138 | other_user = UserFactory() 139 | other_user_post = PostFactory(author=other_user) 140 | BookmarkFactory(user=other_user, post=other_user_post) 141 | url = f'/engagements/bookmarks/{other_user_post.id}/' 142 | response = client.delete(url, headers=auth_header) 143 | assert response.status_code == status.HTTP_404_NOT_FOUND 144 | 145 | 146 | def test_authenticated_user_can_not_un_bookmark_a_non_existing_post(client, test_user, auth_header): 147 | url = '/engagements/bookmarks/1000/' 148 | response = client.delete(url, headers=auth_header) 149 | assert response.status_code == status.HTTP_404_NOT_FOUND 150 | 151 | 152 | def test_unauthenticated_user_can_not_un_bookmark_a_post(client, bookmarked_post): 153 | url = f'/engagements/bookmarks/{bookmarked_post.id}/' 154 | response = client.delete(url) 155 | assert response.status_code == status.HTTP_401_UNAUTHORIZED 156 | -------------------------------------------------------------------------------- /tests/engagements/test_services.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/tests/engagements/test_services.py -------------------------------------------------------------------------------- /tests/factories.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | from factory import LazyFunction, SubFactory 4 | from factory.alchemy import SQLAlchemyModelFactory 5 | from factory.fuzzy import FuzzyDateTime 6 | from faker import Faker 7 | from faker.providers import misc 8 | from pytz import UTC 9 | from twitter_api.engagements.models import Bookmark, Like 10 | from twitter_api.posts.models import Mention, Post 11 | from twitter_api.users.auth import hash_password 12 | from twitter_api.users.models import Followership, User 13 | 14 | from .configs import Session 15 | 16 | fake = Faker() 17 | fake.add_provider(misc) 18 | 19 | 20 | class BaseFactory(SQLAlchemyModelFactory): 21 | class Meta: 22 | abstract = True 23 | sqlalchemy_session = Session 24 | sqlalchemy_session_persistence = 'flush' 25 | 26 | 27 | class TimeStampBaseFactory(BaseFactory): 28 | created_at = FuzzyDateTime(datetime(2024, 1, 1, tzinfo=UTC)) 29 | updated_at = FuzzyDateTime(datetime(2024, 1, 1, tzinfo=UTC)) 30 | 31 | 32 | class UserFactory(TimeStampBaseFactory, BaseFactory): 33 | username = fake.user_name() 34 | email = fake.email() 35 | password = LazyFunction(lambda: hash_password('test123')) 36 | 37 | class Meta: 38 | model = User 39 | 40 | 41 | class FollowershipFactory(TimeStampBaseFactory, BaseFactory): 42 | following = SubFactory(UserFactory) 43 | follower = SubFactory(UserFactory) 44 | 45 | class Meta: 46 | model = Followership 47 | 48 | 49 | class PostFactory(TimeStampBaseFactory, BaseFactory): 50 | author = SubFactory(UserFactory) 51 | content = 'sample tweet' 52 | 53 | class Meta: 54 | model = Post 55 | 56 | 57 | class MentionFactory(TimeStampBaseFactory, BaseFactory): 58 | mention = SubFactory(PostFactory) 59 | original_post = SubFactory(PostFactory) 60 | 61 | class Meta: 62 | model = Mention 63 | 64 | 65 | class LikeFactory(TimeStampBaseFactory, BaseFactory): 66 | user = SubFactory(UserFactory) 67 | post = SubFactory(PostFactory) 68 | 69 | class Meta: 70 | model = Like 71 | 72 | 73 | class BookmarkFactory(TimeStampBaseFactory, BaseFactory): 74 | user = SubFactory(UserFactory) 75 | post = SubFactory(PostFactory) 76 | 77 | class Meta: 78 | model = Bookmark 79 | -------------------------------------------------------------------------------- /tests/posts/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/tests/posts/__init__.py -------------------------------------------------------------------------------- /tests/posts/test_routes.py: -------------------------------------------------------------------------------- 1 | from fastapi import status 2 | 3 | from tests.factories import PostFactory, UserFactory 4 | 5 | 6 | def test_authenticated_user_can_make_a_post(client, auth_header): 7 | payload = {'content': 'test'} 8 | url = '/posts/' 9 | response = client.post(url, json=payload, headers=auth_header) 10 | assert response.status_code == status.HTTP_201_CREATED 11 | 12 | 13 | def test_unauthenticated_user_can_not_make_a_post(client): 14 | payload = {'content': 'test'} 15 | url = '/posts/' 16 | response = client.post(url, json=payload) 17 | assert response.status_code == status.HTTP_401_UNAUTHORIZED 18 | 19 | 20 | def test_authenticated_user_can_update_a_post(client, test_post, auth_header): 21 | payload = {'content': 'test'} 22 | url = f'/posts/{test_post.id}' 23 | response = client.patch(url, json=payload, headers=auth_header) 24 | assert response.status_code == status.HTTP_206_PARTIAL_CONTENT 25 | 26 | 27 | def test_authenticated_user_can_not_update_a_post_he_has_not_written(client, test_post, auth_header): 28 | other_user = UserFactory() 29 | other_user_post = PostFactory(author=other_user) 30 | payload = {'content': 'test'} 31 | url = f'/posts/{other_user_post.id}' 32 | response = client.patch(url, json=payload, headers=auth_header) 33 | assert response.status_code == status.HTTP_403_FORBIDDEN 34 | 35 | 36 | def test_authenticated_user_can_delete_his_post(client, test_post, auth_header): 37 | url = f'/posts/{test_post.id}' 38 | response = client.delete(url, headers=auth_header) 39 | assert response.status_code == status.HTTP_204_NO_CONTENT 40 | 41 | 42 | def test_authenticated_user_can_not_delete_a_post_he_has_not_written(client, test_post, auth_header): 43 | other_user = UserFactory() 44 | other_user_post = PostFactory(author=other_user) 45 | url = f'/posts/{other_user_post.id}' 46 | response = client.delete(url, headers=auth_header) 47 | assert response.status_code == status.HTTP_403_FORBIDDEN 48 | 49 | 50 | def test_anyone_can_view_list_of_post_of_an_existing_user(client, test_user): 51 | PostFactory.create_batch(size=5, author=test_user) 52 | url = f'/posts/{test_user.username}/' 53 | response = client.get(url) 54 | assert response.status_code == status.HTTP_200_OK 55 | 56 | 57 | def test_no_one_can_view_list_of_post_of_a_non_existing_user(client): 58 | url = '/posts/none/' 59 | response = client.get(url) 60 | assert response.status_code == status.HTTP_404_NOT_FOUND 61 | 62 | 63 | def test_anyone_can_view_detail_of_post_with_its_quoted_post(client, test_user, post_with_quote): 64 | url = f'/posts/{test_user.username}/{post_with_quote.id}' 65 | response = client.get(url) 66 | assert response.status_code == status.HTTP_200_OK 67 | assert response.json()['quoted_post'] 68 | 69 | 70 | def test_anyone_can_view_all_mentions_of_a_post(client, test_user, post_with_mention): 71 | url = f'/posts/{test_user.username}/{post_with_mention.original_post.id}/mentions' 72 | response = client.get(url) 73 | assert response.status_code == status.HTTP_200_OK 74 | 75 | 76 | def test_unauthenticated_user_can_not_mention_on_a_post(client, test_user, test_post): 77 | payload = {'content': 'test'} 78 | url = f'/posts/{test_user.username}/{test_post.id}/mentions' 79 | response = client.post(url, json=payload) 80 | assert response.status_code == status.HTTP_401_UNAUTHORIZED 81 | 82 | 83 | def test_authenticated_user_can_mention_on_a_post(client, test_user, auth_header, test_post): 84 | payload = {'content': 'test'} 85 | url = f'/posts/{test_user.username}/{test_post.id}/mentions' 86 | response = client.post(url, json=payload, headers=auth_header) 87 | assert response.status_code == status.HTTP_201_CREATED 88 | -------------------------------------------------------------------------------- /tests/posts/test_services.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/tests/posts/test_services.py -------------------------------------------------------------------------------- /tests/users/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/tests/users/__init__.py -------------------------------------------------------------------------------- /tests/users/test_routes.py: -------------------------------------------------------------------------------- 1 | from fastapi import status 2 | 3 | from tests.factories import UserFactory 4 | 5 | 6 | def test_anyone_can_register_with_valid_register_info(client): 7 | url = '/auth/' 8 | payload = {'email': 'druid@gmail.com', 'username': 'druid', 'password': '123456'} 9 | response = client.post(url, json=payload) 10 | assert response.status_code == status.HTTP_201_CREATED 11 | 12 | 13 | def test_no_one_can_register_with_duplicate_username(client): 14 | url = '/auth/' 15 | payload = {'email': 'user@gmail.com', 'username': 'druid', 'password': '123456'} 16 | UserFactory(username=payload['username']) 17 | response = client.post(url, json=payload) 18 | assert response.status_code == status.HTTP_400_BAD_REQUEST 19 | 20 | 21 | def test_no_one_can_register_with_duplicate_email(client): 22 | url = '/auth/' 23 | payload = {'email': 'user@gmail.com', 'username': 'druid', 'password': '123456'} 24 | UserFactory(email=payload['email']) 25 | response = client.post(url, json=payload) 26 | assert response.status_code == status.HTTP_400_BAD_REQUEST 27 | 28 | 29 | def test_anyone_can_get_token_when_login_successfully(client): 30 | sample_user = UserFactory() 31 | url = '/auth/login/' 32 | payload = {'username': sample_user.username, 'password': 'test123'} 33 | response = client.post(url, json=payload) 34 | assert response.status_code == status.HTTP_200_OK 35 | assert 'token' in response.json() 36 | 37 | 38 | def test_no_one_can_get_token_with_invalid_credentials(client): 39 | sample_user = UserFactory() 40 | url = '/auth/login/' 41 | payload = {'username': sample_user.username, 'password': 'invalid_pass'} 42 | response = client.post(url, json=payload) 43 | assert response.status_code == status.HTTP_401_UNAUTHORIZED 44 | assert 'token' not in response.json() 45 | 46 | 47 | def test_anyone_can_view_existing_user_profile(client, test_user): 48 | url = f'/users/profile/{test_user.id}/' 49 | response = client.get(url) 50 | assert response.status_code == status.HTTP_200_OK 51 | 52 | 53 | def test_no_one_can_view_non_existing_user_profile(client): 54 | url = '/users/profile/100000/' 55 | response = client.get(url) 56 | assert response.status_code == status.HTTP_404_NOT_FOUND 57 | 58 | 59 | def test_authenticated_user_can_delete_their_profile(client, test_user, auth_header): 60 | url = f'/users/profile/{test_user.id}/' 61 | response = client.delete(url, headers=auth_header) 62 | assert response.status_code == status.HTTP_204_NO_CONTENT 63 | 64 | 65 | def test_authenticated_user_can_not_delete_other_user_profile(client, test_user, auth_header): 66 | other_user = UserFactory() 67 | url = f'/users/profile/{other_user.id}/' 68 | response = client.delete(url, headers=auth_header) 69 | assert response.status_code == status.HTTP_403_FORBIDDEN 70 | 71 | 72 | def test_non_authenticated_user_can_not_delete_other_user_profile(client): 73 | other_user = UserFactory() 74 | url = f'/users/profile/{other_user.id}/' 75 | response = client.delete(url) 76 | assert response.status_code == status.HTTP_401_UNAUTHORIZED 77 | 78 | 79 | def test_anyone_can_view_user_followers(client, user_as_follower): 80 | url = f'/users/{user_as_follower.following.id}/followers/' 81 | response = client.get(url) 82 | assert response.status_code == status.HTTP_200_OK 83 | 84 | 85 | def test_no_one_can_view_non_existing_user_followers(client): 86 | url = '/users/10000/followers/' 87 | response = client.get(url) 88 | assert response.status_code == status.HTTP_404_NOT_FOUND 89 | 90 | 91 | def test_anyone_can_view_user_followings(client, user_as_following): 92 | url = f'/users/{user_as_following.follower.id}/followings/' 93 | response = client.get(url) 94 | assert response.status_code == status.HTTP_200_OK 95 | 96 | 97 | def test_no_one_can_view_non_existing_user_followings(client): 98 | url = '/users/10000/followings/' 99 | response = client.get(url) 100 | assert response.status_code == status.HTTP_404_NOT_FOUND 101 | 102 | 103 | def test_authenticated_user_can_remove_another_user_from_their_followers(client, user_as_following, auth_header): 104 | user = user_as_following.following 105 | url = f'/users/{user.id}/followers/{user_as_following.follower.id}/' 106 | response = client.delete(url, headers=auth_header) 107 | assert response.status_code == status.HTTP_204_NO_CONTENT 108 | 109 | 110 | def test_authenticated_user_can_only_remove_their_followers(client, user_as_follower, auth_header): 111 | user = user_as_follower.follower 112 | url = f'/users/{user_as_follower.following.id}/followers/{user.id}/' 113 | response = client.delete(url, headers=auth_header) 114 | assert response.status_code == status.HTTP_403_FORBIDDEN 115 | 116 | 117 | def test_authenticated_user_can_not_remove_non_existing_followership(client, test_user, auth_header): 118 | other_user = UserFactory() 119 | url = f'/users/{test_user.id}/followers/{other_user.id}/' 120 | response = client.delete(url, headers=auth_header) 121 | assert response.status_code == status.HTTP_404_NOT_FOUND 122 | 123 | 124 | def test_authenticated_user_can_follow_another_user(client, test_user, auth_header): 125 | other_user = UserFactory() 126 | payload = {'user_id': other_user.id} 127 | url = f'/users/{test_user.id}/followings/' 128 | response = client.post(url, headers=auth_header, json=payload) 129 | assert response.status_code == status.HTTP_201_CREATED 130 | 131 | 132 | def test_authenticated_user_can_not_follow_another_user_on_behalf_of_other_user(client, test_user, auth_header): 133 | other_user = UserFactory() 134 | payload = {'user_id': test_user.id} 135 | url = f'/users/{other_user.id}/followings/' 136 | response = client.post(url, headers=auth_header, json=payload) 137 | assert response.status_code == status.HTTP_403_FORBIDDEN 138 | 139 | 140 | def test_authenticated_user_can_not_follow_themselves(client, test_user, auth_header): 141 | payload = {'user_id': test_user.id} 142 | url = f'/users/{test_user.id}/followings/' 143 | response = client.post(url, headers=auth_header, json=payload) 144 | assert response.status_code == status.HTTP_400_BAD_REQUEST 145 | 146 | 147 | def test_authenticated_user_can_unfollow_another_user(client, user_as_follower, auth_header): 148 | user = user_as_follower.follower 149 | url = f'/users/{user.id}/followings/{user_as_follower.following.id}/' 150 | response = client.delete(url, headers=auth_header) 151 | assert response.status_code == status.HTTP_204_NO_CONTENT 152 | 153 | 154 | def test_authenticated_user_can_not_unfollow_another_user_on_behalf_of_other_user( 155 | client, user_as_following, auth_header 156 | ): 157 | user = user_as_following.following 158 | url = f'/users/{user_as_following.follower.id}/followings/{user.id}/' 159 | response = client.delete(url, headers=auth_header) 160 | assert response.status_code == status.HTTP_403_FORBIDDEN 161 | -------------------------------------------------------------------------------- /tests/users/test_services.py: -------------------------------------------------------------------------------- 1 | from twitter_api.users import services 2 | from twitter_api.users.models import Followership, User 3 | 4 | from tests.factories import UserFactory 5 | 6 | 7 | def test_get_user_by_email_for_existing_user(session, test_user): 8 | user = services.get_user_by_email(db_session=session, email=test_user.email) 9 | assert user 10 | 11 | 12 | def test_get_user_by_email_for_non_existing_user(session): 13 | user = services.get_user_by_email(db_session=session, email='none@gmail.com') 14 | assert user is None 15 | 16 | 17 | def test_get_user_by_username_for_existing_user(session, test_user): 18 | user = services.get_user_by_username(db_session=session, username=test_user.username) 19 | assert user 20 | 21 | 22 | def test_get_user_by_username_for_non_existing_user(session): 23 | user = services.get_user_by_username(db_session=session, username='none') 24 | assert user is None 25 | 26 | 27 | def test_delete_user(session, test_user): 28 | services.delete_user(db_session=session, user=test_user) 29 | user_exists = session.query(session.query(User).filter(User.id == test_user.id).exists()).scalar() 30 | assert user_exists is False 31 | 32 | 33 | def test_get_followers_by_user(session, user_as_following): 34 | user = user_as_following.following 35 | follower = user_as_following.follower 36 | followers = services.get_followers_by_user(db_session=session, user=user) 37 | follower_exists = session.query(followers.filter(User.id == follower.id).exists()).scalar() 38 | assert follower_exists 39 | 40 | 41 | def test_get_following_by_user(session, user_as_follower): 42 | user = user_as_follower.follower 43 | following = user_as_follower.following 44 | followings = services.get_followings_by_user(db_session=session, user=user) 45 | following_exists = session.query(followings.filter(User.id == following.id).exists()).scalar() 46 | assert following_exists 47 | 48 | 49 | def test_remove_user_from_followers(session, user_as_following): 50 | user = user_as_following.following 51 | follower_user = user_as_following.follower 52 | services.remove_user_from_followers(db_session=session, follower=user_as_following) 53 | followership_exists = session.query( 54 | session.query(Followership) 55 | .filter(Followership.following_id == user.id, Followership.follower_id == follower_user.id) 56 | .exists() 57 | ).scalar() 58 | assert followership_exists is False 59 | 60 | 61 | def test_follow_user(session, test_user): 62 | following_user = UserFactory() 63 | services.follow_user(db_session=session, user=test_user, following_id=following_user.id) 64 | followership_exists = session.query( 65 | session.query(Followership) 66 | .filter(Followership.following_id == following_user.id, Followership.follower_id == test_user.id) 67 | .exists() 68 | ).scalar() 69 | assert followership_exists 70 | 71 | 72 | def test_unfollow_user(session, user_as_follower): 73 | user = user_as_follower.follower 74 | following_user = user_as_follower.following 75 | services.unfollow_user(db_session=session, following=user_as_follower) 76 | followership_exists = session.query( 77 | session.query(Followership) 78 | .filter(Followership.following_id == following_user.id, Followership.follower_id == user.id) 79 | .exists() 80 | ).scalar() 81 | assert followership_exists is False 82 | 83 | 84 | def test_create_new_user(session): 85 | new_user = services.create_user(db_session=session, username='ali', email='a.abharya@gmail.com', password='123456') 86 | user_exists = session.query( 87 | session.query(User).filter(User.username == 'ali', User.email == 'a.abharya@gmail.com').exists() 88 | ).scalar() 89 | assert new_user 90 | assert user_exists 91 | -------------------------------------------------------------------------------- /twitter_api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/twitter_api/__init__.py -------------------------------------------------------------------------------- /twitter_api/core/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/twitter_api/core/__init__.py -------------------------------------------------------------------------------- /twitter_api/core/config.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | from pathlib import Path 3 | from typing import Any 4 | 5 | from pydantic import ConfigDict, PostgresDsn 6 | from pydantic_settings import BaseSettings 7 | 8 | 9 | class Environment(str, Enum): 10 | LOCAL = 'LOCAL' 11 | TEST = 'TEST' 12 | STAGING = 'STAGING' 13 | PRODUCTION = 'PRODUCTION' 14 | 15 | @property 16 | def is_debug(self): 17 | return self in (self.LOCAL, self.STAGING, self.TEST) 18 | 19 | @property 20 | def is_testing(self): 21 | return self == self.TEST 22 | 23 | @property 24 | def is_deployed(self) -> bool: 25 | return self in (self.STAGING, self.PRODUCTION) 26 | 27 | 28 | class Paths: 29 | ROOT_DIR: Path = Path(__file__).parent.parent.parent 30 | BASE_DIR: Path = ROOT_DIR / 'twitter_api' 31 | 32 | 33 | class Settings(BaseSettings): 34 | model_config = ConfigDict(env_file='.env') 35 | 36 | @property 37 | def PATHS(self) -> Paths: 38 | return Paths() 39 | 40 | ENVIRONMENT: Environment 41 | SECRET_KEY: str 42 | SENTRY_ENABLED: bool 43 | SENTRY_DSN: str 44 | DEBUG: bool = True 45 | DB_URL: PostgresDsn 46 | CORS_ORIGINS: list[str] = ['*'] 47 | CORS_ORIGINS_REGEX: str | None = None 48 | CORS_HEADERS: list[str] = ['*'] 49 | ANALYTICS_HOST: str 50 | ANALYTICS_PORT: int 51 | PAGINATION_PER_PAGE: int = 20 52 | JWT_SECRET: str 53 | JWT_ALG: str = 'HS256' 54 | JWT_EXP: int = 86400 # Seconds 55 | 56 | @property 57 | def ANALYTICS_URL(self) -> str: 58 | return f'{self.ANALYTICS_HOST}:{str(self.ANALYTICS_PORT)}' 59 | 60 | 61 | settings = Settings() 62 | 63 | app_configs: dict[str, Any] = { 64 | 'title': 'Twitter API', 65 | 'description': 'Minimal twitter twitter_api built with FastAPI', 66 | 'debug': settings.DEBUG, 67 | 'root_path': '/api/v1', 68 | 'swagger_ui_parameters': {'defaultModelsExpandDepth': -1}, 69 | } 70 | -------------------------------------------------------------------------------- /twitter_api/core/exceptions.py: -------------------------------------------------------------------------------- 1 | from fastapi import HTTPException, status 2 | 3 | 4 | class DetailedHTTPException(HTTPException): 5 | STATUS_CODE = status.HTTP_500_INTERNAL_SERVER_ERROR 6 | DETAIL = 'Server error' 7 | 8 | def __init__(self, *args, **kwargs) -> None: 9 | kwargs.setdefault('status_code', self.STATUS_CODE) 10 | kwargs.setdefault('detail', self.DETAIL) 11 | super().__init__(*args, **kwargs) 12 | 13 | 14 | class PermissionDenied(DetailedHTTPException): 15 | STATUS_CODE = status.HTTP_403_FORBIDDEN 16 | DETAIL = 'Permission denied' 17 | 18 | 19 | class NotFound(DetailedHTTPException): 20 | STATUS_CODE = status.HTTP_404_NOT_FOUND 21 | 22 | 23 | class BadRequest(DetailedHTTPException): 24 | STATUS_CODE = status.HTTP_400_BAD_REQUEST 25 | DETAIL = 'Bad Request' 26 | 27 | 28 | class NotAuthenticated(DetailedHTTPException): 29 | STATUS_CODE = status.HTTP_401_UNAUTHORIZED 30 | DETAIL = 'User not authenticated' 31 | 32 | def __init__(self) -> None: 33 | super().__init__(headers={'Authenticate': 'Bearer'}) 34 | -------------------------------------------------------------------------------- /twitter_api/core/lifespan.py: -------------------------------------------------------------------------------- 1 | from contextlib import asynccontextmanager 2 | from typing import AsyncGenerator 3 | 4 | from fastapi import FastAPI 5 | 6 | from .logging import configure_sentry 7 | 8 | 9 | @asynccontextmanager 10 | async def lifespan(application: FastAPI) -> AsyncGenerator: 11 | configure_sentry() 12 | yield 13 | # Shutdown 14 | -------------------------------------------------------------------------------- /twitter_api/core/logging.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import sentry_sdk 4 | from rich.logging import RichHandler 5 | from sentry_sdk.integrations.aiohttp import AioHttpIntegration 6 | from sentry_sdk.integrations.atexit import AtexitIntegration 7 | from sentry_sdk.integrations.dedupe import DedupeIntegration 8 | from sentry_sdk.integrations.excepthook import ExcepthookIntegration 9 | from sentry_sdk.integrations.logging import LoggingIntegration 10 | from sentry_sdk.integrations.modules import ModulesIntegration 11 | from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration 12 | from sentry_sdk.integrations.stdlib import StdlibIntegration 13 | 14 | from .config import settings 15 | 16 | logger = logging.getLogger(__name__) 17 | 18 | handler = RichHandler() 19 | 20 | logger.setLevel(logging.DEBUG) 21 | handler.setLevel(logging.DEBUG) 22 | 23 | handler.setFormatter(logging.Formatter('%(message)s')) 24 | 25 | logger.addHandler(handler) 26 | 27 | 28 | sentry_logging = LoggingIntegration( 29 | level=logging.INFO, # Capture info and above as breadcrumbs 30 | event_level=logging.ERROR, # Send errors as events 31 | ) 32 | 33 | 34 | def configure_sentry(): 35 | logger.debug('Configuring Sentry') 36 | if settings.SENTRY_ENABLED: 37 | sentry_sdk.init( 38 | dsn=str(settings.SENTRY_ENABLED), 39 | integrations=[ 40 | AioHttpIntegration(), 41 | AtexitIntegration(), 42 | DedupeIntegration(), 43 | ExcepthookIntegration(), 44 | ModulesIntegration(), 45 | SqlalchemyIntegration(), 46 | StdlibIntegration(), 47 | sentry_logging, 48 | ], 49 | environment=settings.ENVIRONMENT, 50 | auto_enabling_integrations=False, 51 | ) 52 | -------------------------------------------------------------------------------- /twitter_api/core/middleware.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | from uuid import uuid4 3 | 4 | from fastapi import HTTPException, status 5 | from fastapi.responses import JSONResponse, Response 6 | from fastapi.security.utils import get_authorization_scheme_param 7 | from jose import JWTError, jwt 8 | from jose.exceptions import JWKError 9 | from pydantic import BaseModel, ValidationError 10 | from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint 11 | from starlette.requests import Request 12 | 13 | from twitter_api.core.config import settings 14 | 15 | from .logging import logger 16 | 17 | 18 | class AnonymousUser: 19 | id = None 20 | username = None 21 | 22 | @property 23 | def is_authenticated(self): 24 | return False 25 | 26 | @property 27 | def is_anonymous(self): 28 | return True 29 | 30 | 31 | class AuthenticatedUser(BaseModel): 32 | id: int 33 | username: str 34 | 35 | @property 36 | def is_authenticated(self): 37 | return True 38 | 39 | @property 40 | def is_anonymous(self): 41 | return False 42 | 43 | 44 | class NoAuthenticationHeaderError(Exception): 45 | pass 46 | 47 | 48 | class AuthenticationMiddleware(BaseHTTPMiddleware): 49 | async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response: 50 | authorization: str = request.headers.get('Authorization') 51 | scheme, param = get_authorization_scheme_param(authorization) 52 | try: 53 | if not authorization or scheme.lower() != 'bearer': 54 | raise NoAuthenticationHeaderError() 55 | token = authorization.split()[1] 56 | data = jwt.decode(token, settings.JWT_SECRET) 57 | request.state.user = AuthenticatedUser(id=data['id'], username=data['username']) 58 | except (NoAuthenticationHeaderError, JWKError, JWTError): 59 | request.state.user = AnonymousUser() 60 | response = await call_next(request) 61 | return response 62 | 63 | 64 | class LoggingMiddleware(BaseHTTPMiddleware): 65 | async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response: 66 | start_time = datetime.datetime.utcnow() 67 | method_name = request.method.upper() 68 | url = request.url 69 | user = request.state.user.id or 'Anonymous' 70 | if '/healthcheck/' not in str(url): 71 | with open(f'{settings.PATHS.ROOT_DIR}/logs/requests.log', mode='a') as request_logs: 72 | log_id = str(uuid4()) 73 | log_message = f'Log [{log_id}]\n[{start_time}] [User #{user}] [{method_name}] {url}\n' 74 | request_logs.write(log_message) 75 | response = await call_next(request) 76 | process_time = datetime.datetime.utcnow() - start_time 77 | response.headers['X-Process-Time'] = str(process_time) 78 | return response 79 | 80 | 81 | class ExceptionMiddleware(BaseHTTPMiddleware): 82 | async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> JSONResponse: 83 | try: 84 | response = await call_next(request) 85 | except HTTPException as http_exception: 86 | response = JSONResponse( 87 | status_code=http_exception.status_code, content={'detail': str(http_exception.detail)} 88 | ) 89 | except ValidationError as e: 90 | response = JSONResponse(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content={'detail': e.errors()}) 91 | except Exception as e: # noqa 92 | logger.exception(e) 93 | content = {'detail': [{'msg': 'Unknown', 'loc': ['Unknown'], 'type': 'Unknown'}]} 94 | if settings.DEBUG: 95 | content = {'detail': [{'error': e.__class__.__name__, 'mgs': e.args}]} 96 | response = JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content=content) 97 | return response 98 | -------------------------------------------------------------------------------- /twitter_api/core/pagination.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.exc import ProgrammingError 2 | from sqlalchemy.orm.query import Query 3 | from sqlalchemy_filters import apply_pagination 4 | 5 | from twitter_api.database import PydanticBase 6 | 7 | from .config import settings 8 | from .logging import logger 9 | 10 | 11 | class Pagination(PydanticBase): 12 | itemsPerPage: int 13 | page: int 14 | total: int 15 | 16 | 17 | def paginate(*, items: Query, page: int) -> dict: 18 | try: 19 | query, pagination = apply_pagination(items, page_number=page, page_size=settings.PAGINATION_PER_PAGE) 20 | except ProgrammingError as e: 21 | logger.info(e) 22 | return { 23 | 'items': [], 24 | 'itemsPerPage': settings.PAGINATION_PER_PAGE, 25 | 'page': page, 26 | 'total': 0, 27 | } 28 | return { 29 | 'items': query.all(), 30 | 'itemsPerPage': pagination.page_size, 31 | 'page': pagination.page_number, 32 | 'total': pagination.total_results, 33 | } 34 | -------------------------------------------------------------------------------- /twitter_api/database/__init__.py: -------------------------------------------------------------------------------- 1 | from .base_models import PydanticBase, TimeStampedModel 2 | from .configs import Base, engine 3 | from .depends import DbSession 4 | -------------------------------------------------------------------------------- /twitter_api/database/base_models.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | from pydantic import BaseModel, ConfigDict 4 | from pydantic.types import SecretStr 5 | from sqlalchemy import Column, DateTime 6 | 7 | 8 | class PydanticBase(BaseModel): 9 | model_config = ConfigDict( 10 | from_attributes=True, 11 | validate_assignment=True, 12 | arbitrary_types_allowed=True, 13 | str_strip_whitespace=True, 14 | json_encoders={ 15 | datetime: lambda v: v.strftime('%Y-%m-%dT%H:%M:%SZ') if v else None, 16 | SecretStr: lambda v: v.get_secret_value() if v else None, 17 | }, 18 | ) 19 | 20 | 21 | class TimeStampedModel: 22 | created_at = Column(DateTime, default=datetime.utcnow) 23 | updated_at = Column(DateTime, default=datetime.utcnow) 24 | -------------------------------------------------------------------------------- /twitter_api/database/configs.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import MetaData, create_engine 2 | from sqlalchemy.orm import declarative_base 3 | 4 | from twitter_api.core.config import settings 5 | 6 | db_url = str(settings.DB_URL) 7 | engine = create_engine(db_url) 8 | 9 | POSTGRES_INDEXES_NAMING_CONVENTION = { 10 | 'ix': '%(column_0_label)s_idx', 11 | 'uq': '%(table_name)s_%(column_0_name)s_key', 12 | 'ck': '%(table_name)s_%(constraint_name)s_check', 13 | 'fk': '%(table_name)s_%(column_0_name)s_fkey', 14 | 'pk': '%(table_name)s_pkey', 15 | } 16 | 17 | metadata = MetaData(naming_convention=POSTGRES_INDEXES_NAMING_CONVENTION) 18 | 19 | Base = declarative_base(metadata=metadata) 20 | Base.metadata.create_all(engine) 21 | -------------------------------------------------------------------------------- /twitter_api/database/depends.py: -------------------------------------------------------------------------------- 1 | from typing import Annotated 2 | 3 | from fastapi import Depends 4 | from sqlalchemy.orm import Session, sessionmaker 5 | 6 | from .configs import engine 7 | 8 | 9 | def get_db_session() -> Session: 10 | session_class = sessionmaker(bind=engine) 11 | session = session_class() 12 | return session 13 | 14 | 15 | DbSession = Annotated[Session, Depends(get_db_session)] 16 | -------------------------------------------------------------------------------- /twitter_api/database/migrations/README: -------------------------------------------------------------------------------- 1 | Generic single-database configuration. -------------------------------------------------------------------------------- /twitter_api/database/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/twitter_api/database/migrations/__init__.py -------------------------------------------------------------------------------- /twitter_api/database/migrations/env.py: -------------------------------------------------------------------------------- 1 | from logging.config import fileConfig 2 | 3 | from sqlalchemy import engine_from_config 4 | from sqlalchemy import pool 5 | 6 | from alembic import context 7 | from twitter_api.core.config import settings 8 | from twitter_api.users.models import User, Followership 9 | from twitter_api.posts.models import Post, Mention 10 | from twitter_api.engagements.models import Like, Bookmark, View 11 | from twitter_api.database.configs import Base 12 | # this is the Alembic Config object, which provides 13 | # access to the values within the .ini file in use. 14 | config = context.config 15 | 16 | # Interpret the config file for Python logging. 17 | # This line sets up loggers basically. 18 | if config.config_file_name is not None: 19 | fileConfig(config.config_file_name) 20 | 21 | config.set_main_option('sqlalchemy.url', str(settings.DB_URL)) 22 | 23 | # add your model's MetaData object here 24 | # for 'autogenerate' support 25 | # from myapp import mymodel 26 | # target_metadata = mymodel.Base.metadata 27 | target_metadata = Base.metadata 28 | 29 | # other values from the config, defined by the needs of env.py, 30 | # can be acquired: 31 | # my_important_option = config.get_main_option("my_important_option") 32 | # ... etc. 33 | 34 | 35 | def run_migrations_offline() -> None: 36 | """Run migrations in 'offline' mode. 37 | 38 | This configures the context with just a URL 39 | and not an Engine, though an Engine is acceptable 40 | here as well. By skipping the Engine creation 41 | we don't even need a DBAPI to be available. 42 | 43 | Calls to context.execute() here emit the given string to the 44 | script output. 45 | 46 | """ 47 | url = config.get_main_option("sqlalchemy.url") 48 | context.configure( 49 | url=url, 50 | target_metadata=target_metadata, 51 | literal_binds=True, 52 | dialect_opts={"paramstyle": "named"}, 53 | ) 54 | 55 | with context.begin_transaction(): 56 | context.run_migrations() 57 | 58 | 59 | def run_migrations_online() -> None: 60 | """Run migrations in 'online' mode. 61 | 62 | In this scenario we need to create an Engine 63 | and associate a connection with the context. 64 | 65 | """ 66 | connectable = engine_from_config( 67 | config.get_section(config.config_ini_section, {}), 68 | prefix="sqlalchemy.", 69 | poolclass=pool.NullPool, 70 | ) 71 | 72 | with connectable.connect() as connection: 73 | context.configure( 74 | connection=connection, target_metadata=target_metadata 75 | ) 76 | 77 | with context.begin_transaction(): 78 | context.run_migrations() 79 | 80 | 81 | if context.is_offline_mode(): 82 | run_migrations_offline() 83 | else: 84 | run_migrations_online() 85 | -------------------------------------------------------------------------------- /twitter_api/database/migrations/script.py.mako: -------------------------------------------------------------------------------- 1 | """${message} 2 | 3 | Revision ID: ${up_revision} 4 | Revises: ${down_revision | comma,n} 5 | Create Date: ${create_date} 6 | 7 | """ 8 | from typing import Sequence, Union 9 | 10 | from alembic import op 11 | import sqlalchemy as sa 12 | ${imports if imports else ""} 13 | 14 | # revision identifiers, used by Alembic. 15 | revision: str = ${repr(up_revision)} 16 | down_revision: Union[str, None] = ${repr(down_revision)} 17 | branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} 18 | depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} 19 | 20 | 21 | def upgrade() -> None: 22 | ${upgrades if upgrades else "pass"} 23 | 24 | 25 | def downgrade() -> None: 26 | ${downgrades if downgrades else "pass"} 27 | -------------------------------------------------------------------------------- /twitter_api/database/migrations/versions/2024-06-05_7e6080593f5d.py: -------------------------------------------------------------------------------- 1 | """empty message 2 | 3 | Revision ID: 7e6080593f5d 4 | Revises: 5 | Create Date: 2024-06-05 20:53:11.946709 6 | 7 | """ 8 | from typing import Sequence, Union 9 | 10 | from alembic import op 11 | import sqlalchemy as sa 12 | 13 | 14 | # revision identifiers, used by Alembic. 15 | revision: str = '7e6080593f5d' 16 | down_revision: Union[str, None] = None 17 | branch_labels: Union[str, Sequence[str], None] = None 18 | depends_on: Union[str, Sequence[str], None] = None 19 | 20 | 21 | def upgrade() -> None: 22 | # ### commands auto generated by Alembic - please adjust! ### 23 | op.create_table('users', 24 | sa.Column('id', sa.Integer(), nullable=False), 25 | sa.Column('username', sa.String(length=32), nullable=True), 26 | sa.Column('first_name', sa.String(length=256), nullable=True), 27 | sa.Column('last_name', sa.String(length=256), nullable=True), 28 | sa.Column('email', sa.String(length=256), nullable=False), 29 | sa.Column('is_active', sa.Boolean(), nullable=True), 30 | sa.Column('password', sa.String(length=128), nullable=False), 31 | sa.Column('created_at', sa.DateTime(), nullable=True), 32 | sa.Column('updated_at', sa.DateTime(), nullable=True), 33 | sa.PrimaryKeyConstraint('id', name=op.f('users_pkey')) 34 | ) 35 | op.create_index(op.f('users_email_idx'), 'users', ['email'], unique=True) 36 | op.create_index(op.f('users_username_idx'), 'users', ['username'], unique=True) 37 | op.create_table('followerships', 38 | sa.Column('id', sa.Integer(), nullable=False), 39 | sa.Column('following_id', sa.Integer(), nullable=False), 40 | sa.Column('follower_id', sa.Integer(), nullable=False), 41 | sa.Column('created_at', sa.DateTime(), nullable=True), 42 | sa.Column('updated_at', sa.DateTime(), nullable=True), 43 | sa.CheckConstraint('follower_id <> following_id', name=op.f('followerships_user_can_not_follow_themself_check')), 44 | sa.ForeignKeyConstraint(['follower_id'], ['users.id'], name=op.f('followerships_follower_id_fkey'), ondelete='CASCADE'), 45 | sa.ForeignKeyConstraint(['following_id'], ['users.id'], name=op.f('followerships_following_id_fkey'), ondelete='CASCADE'), 46 | sa.PrimaryKeyConstraint('id', name=op.f('followerships_pkey')), 47 | sa.UniqueConstraint('following_id', 'follower_id', name='unique_followership_relations') 48 | ) 49 | op.create_table('posts', 50 | sa.Column('id', sa.Integer(), nullable=False), 51 | sa.Column('content', sa.String(length=128), nullable=False), 52 | sa.Column('author_id', sa.Integer(), nullable=False), 53 | sa.Column('quoted_post_id', sa.Integer(), nullable=True), 54 | sa.Column('created_at', sa.DateTime(), nullable=True), 55 | sa.Column('updated_at', sa.DateTime(), nullable=True), 56 | sa.ForeignKeyConstraint(['author_id'], ['users.id'], name=op.f('posts_author_id_fkey'), ondelete='CASCADE'), 57 | sa.ForeignKeyConstraint(['quoted_post_id'], ['posts.id'], name=op.f('posts_quoted_post_id_fkey')), 58 | sa.PrimaryKeyConstraint('id', name=op.f('posts_pkey')) 59 | ) 60 | op.create_table('bookmarks', 61 | sa.Column('id', sa.Integer(), nullable=False), 62 | sa.Column('user_id', sa.Integer(), nullable=False), 63 | sa.Column('post_id', sa.Integer(), nullable=False), 64 | sa.Column('created_at', sa.DateTime(), nullable=True), 65 | sa.Column('updated_at', sa.DateTime(), nullable=True), 66 | sa.ForeignKeyConstraint(['post_id'], ['posts.id'], name=op.f('bookmarks_post_id_fkey'), ondelete='CASCADE'), 67 | sa.ForeignKeyConstraint(['user_id'], ['users.id'], name=op.f('bookmarks_user_id_fkey'), ondelete='CASCADE'), 68 | sa.PrimaryKeyConstraint('id', name=op.f('bookmarks_pkey')), 69 | sa.UniqueConstraint('user_id', 'post_id', name='unique_bookmark_for_user_post_relations') 70 | ) 71 | op.create_table('likes', 72 | sa.Column('id', sa.Integer(), nullable=False), 73 | sa.Column('user_id', sa.Integer(), nullable=False), 74 | sa.Column('post_id', sa.Integer(), nullable=False), 75 | sa.Column('created_at', sa.DateTime(), nullable=True), 76 | sa.Column('updated_at', sa.DateTime(), nullable=True), 77 | sa.ForeignKeyConstraint(['post_id'], ['posts.id'], name=op.f('likes_post_id_fkey'), ondelete='CASCADE'), 78 | sa.ForeignKeyConstraint(['user_id'], ['users.id'], name=op.f('likes_user_id_fkey'), ondelete='CASCADE'), 79 | sa.PrimaryKeyConstraint('id', name=op.f('likes_pkey')), 80 | sa.UniqueConstraint('user_id', 'post_id', name='unique_like_for_user_post_relations') 81 | ) 82 | op.create_table('mentions', 83 | sa.Column('id', sa.Integer(), nullable=False), 84 | sa.Column('mention_id', sa.Integer(), nullable=False), 85 | sa.Column('original_post_id', sa.Integer(), nullable=False), 86 | sa.Column('created_at', sa.DateTime(), nullable=True), 87 | sa.Column('updated_at', sa.DateTime(), nullable=True), 88 | sa.ForeignKeyConstraint(['mention_id'], ['posts.id'], name=op.f('mentions_mention_id_fkey')), 89 | sa.ForeignKeyConstraint(['original_post_id'], ['posts.id'], name=op.f('mentions_original_post_id_fkey')), 90 | sa.PrimaryKeyConstraint('id', name=op.f('mentions_pkey')) 91 | ) 92 | op.create_table('views', 93 | sa.Column('id', sa.Integer(), nullable=False), 94 | sa.Column('post_id', sa.Integer(), nullable=False), 95 | sa.Column('count', sa.Integer(), nullable=True), 96 | sa.Column('created_at', sa.DateTime(), nullable=True), 97 | sa.Column('updated_at', sa.DateTime(), nullable=True), 98 | sa.ForeignKeyConstraint(['post_id'], ['posts.id'], name=op.f('views_post_id_fkey'), ondelete='CASCADE'), 99 | sa.PrimaryKeyConstraint('id', name=op.f('views_pkey')), 100 | sa.UniqueConstraint('post_id', name='unique_view_for_post_relations') 101 | ) 102 | # ### end Alembic commands ### 103 | 104 | 105 | def downgrade() -> None: 106 | # ### commands auto generated by Alembic - please adjust! ### 107 | op.drop_table('views') 108 | op.drop_table('mentions') 109 | op.drop_table('likes') 110 | op.drop_table('bookmarks') 111 | op.drop_table('posts') 112 | op.drop_table('followerships') 113 | op.drop_index(op.f('users_username_idx'), table_name='users') 114 | op.drop_index(op.f('users_email_idx'), table_name='users') 115 | op.drop_table('users') 116 | # ### end Alembic commands ### 117 | -------------------------------------------------------------------------------- /twitter_api/database/migrations/versions/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/twitter_api/database/migrations/versions/__init__.py -------------------------------------------------------------------------------- /twitter_api/engagements/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/twitter_api/engagements/__init__.py -------------------------------------------------------------------------------- /twitter_api/engagements/grpc/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/twitter_api/engagements/grpc/__init__.py -------------------------------------------------------------------------------- /twitter_api/engagements/grpc/post_views.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | message PostViewRequest { 4 | int32 post_id = 1; 5 | } 6 | 7 | message PostViewResponse { 8 | int32 post_id = 1; 9 | int32 post_view_count = 2; 10 | } 11 | 12 | service PostViewAnalytics { 13 | rpc GetViewCount (PostViewRequest) returns (PostViewResponse); 14 | rpc CreateViewCount (PostViewRequest) returns (PostViewResponse); 15 | rpc UpdateViewCount (PostViewRequest) returns (PostViewResponse); 16 | rpc DeleteViewCount (PostViewRequest) returns (PostViewResponse); 17 | } 18 | -------------------------------------------------------------------------------- /twitter_api/engagements/grpc/post_views_pb2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by the protocol buffer compiler. DO NOT EDIT! 3 | # source: post_views.proto 4 | # Protobuf Python Version: 5.26.1 5 | """Generated protocol buffer code.""" 6 | from google.protobuf import descriptor as _descriptor 7 | from google.protobuf import descriptor_pool as _descriptor_pool 8 | from google.protobuf import symbol_database as _symbol_database 9 | from google.protobuf.internal import builder as _builder 10 | 11 | # @@protoc_insertion_point(imports) 12 | 13 | _sym_db = _symbol_database.Default() 14 | 15 | 16 | 17 | 18 | DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x10post_views.proto\"\"\n\x0fPostViewRequest\x12\x0f\n\x07post_id\x18\x01 \x01(\x05\"<\n\x10PostViewResponse\x12\x0f\n\x07post_id\x18\x01 \x01(\x05\x12\x17\n\x0fpost_view_count\x18\x02 \x01(\x05\x32\xf0\x01\n\x11PostViewAnalytics\x12\x33\n\x0cGetViewCount\x12\x10.PostViewRequest\x1a\x11.PostViewResponse\x12\x36\n\x0f\x43reateViewCount\x12\x10.PostViewRequest\x1a\x11.PostViewResponse\x12\x36\n\x0fUpdateViewCount\x12\x10.PostViewRequest\x1a\x11.PostViewResponse\x12\x36\n\x0f\x44\x65leteViewCount\x12\x10.PostViewRequest\x1a\x11.PostViewResponseb\x06proto3') 19 | 20 | _globals = globals() 21 | _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) 22 | _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'post_views_pb2', _globals) 23 | if not _descriptor._USE_C_DESCRIPTORS: 24 | DESCRIPTOR._loaded_options = None 25 | _globals['_POSTVIEWREQUEST']._serialized_start=20 26 | _globals['_POSTVIEWREQUEST']._serialized_end=54 27 | _globals['_POSTVIEWRESPONSE']._serialized_start=56 28 | _globals['_POSTVIEWRESPONSE']._serialized_end=116 29 | _globals['_POSTVIEWANALYTICS']._serialized_start=119 30 | _globals['_POSTVIEWANALYTICS']._serialized_end=359 31 | # @@protoc_insertion_point(module_scope) 32 | -------------------------------------------------------------------------------- /twitter_api/engagements/grpc/post_views_pb2.pyi: -------------------------------------------------------------------------------- 1 | from google.protobuf import descriptor as _descriptor 2 | from google.protobuf import message as _message 3 | from typing import ClassVar as _ClassVar, Optional as _Optional 4 | 5 | DESCRIPTOR: _descriptor.FileDescriptor 6 | 7 | class PostViewRequest(_message.Message): 8 | __slots__ = ("post_id",) 9 | POST_ID_FIELD_NUMBER: _ClassVar[int] 10 | post_id: int 11 | def __init__(self, post_id: _Optional[int] = ...) -> None: ... 12 | 13 | class PostViewResponse(_message.Message): 14 | __slots__ = ("post_id", "post_view_count") 15 | POST_ID_FIELD_NUMBER: _ClassVar[int] 16 | POST_VIEW_COUNT_FIELD_NUMBER: _ClassVar[int] 17 | post_id: int 18 | post_view_count: int 19 | def __init__(self, post_id: _Optional[int] = ..., post_view_count: _Optional[int] = ...) -> None: ... 20 | -------------------------------------------------------------------------------- /twitter_api/engagements/grpc/post_views_pb2_grpc.py: -------------------------------------------------------------------------------- 1 | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! 2 | """Client and server classes corresponding to protobuf-defined services.""" 3 | import warnings 4 | 5 | import grpc 6 | 7 | from . import post_views_pb2 as post__views__pb2 8 | 9 | GRPC_GENERATED_VERSION = '1.64.1' 10 | GRPC_VERSION = grpc.__version__ 11 | EXPECTED_ERROR_RELEASE = '1.65.0' 12 | SCHEDULED_RELEASE_DATE = 'June 25, 2024' 13 | _version_not_supported = False 14 | 15 | try: 16 | from grpc._utilities import first_version_is_lower 17 | _version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION) 18 | except ImportError: 19 | _version_not_supported = True 20 | 21 | if _version_not_supported: 22 | warnings.warn( 23 | f'The grpc package installed is at version {GRPC_VERSION},' 24 | + f' but the generated code in post_views_pb2_grpc.py depends on' 25 | + f' grpcio>={GRPC_GENERATED_VERSION}.' 26 | + f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}' 27 | + f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.' 28 | + f' This warning will become an error in {EXPECTED_ERROR_RELEASE},' 29 | + f' scheduled for release on {SCHEDULED_RELEASE_DATE}.', 30 | RuntimeWarning 31 | ) 32 | 33 | 34 | class PostViewAnalyticsStub(object): 35 | """Missing associated documentation comment in .proto file.""" 36 | 37 | def __init__(self, channel): 38 | """Constructor. 39 | 40 | Args: 41 | channel: A grpc.Channel. 42 | """ 43 | self.GetViewCount = channel.unary_unary( 44 | '/PostViewAnalytics/GetViewCount', 45 | request_serializer=post__views__pb2.PostViewRequest.SerializeToString, 46 | response_deserializer=post__views__pb2.PostViewResponse.FromString, 47 | _registered_method=True) 48 | self.CreateViewCount = channel.unary_unary( 49 | '/PostViewAnalytics/CreateViewCount', 50 | request_serializer=post__views__pb2.PostViewRequest.SerializeToString, 51 | response_deserializer=post__views__pb2.PostViewResponse.FromString, 52 | _registered_method=True) 53 | self.UpdateViewCount = channel.unary_unary( 54 | '/PostViewAnalytics/UpdateViewCount', 55 | request_serializer=post__views__pb2.PostViewRequest.SerializeToString, 56 | response_deserializer=post__views__pb2.PostViewResponse.FromString, 57 | _registered_method=True) 58 | self.DeleteViewCount = channel.unary_unary( 59 | '/PostViewAnalytics/DeleteViewCount', 60 | request_serializer=post__views__pb2.PostViewRequest.SerializeToString, 61 | response_deserializer=post__views__pb2.PostViewResponse.FromString, 62 | _registered_method=True) 63 | 64 | 65 | class PostViewAnalyticsServicer(object): 66 | """Missing associated documentation comment in .proto file.""" 67 | 68 | def GetViewCount(self, request, context): 69 | """Missing associated documentation comment in .proto file.""" 70 | context.set_code(grpc.StatusCode.UNIMPLEMENTED) 71 | context.set_details('Method not implemented!') 72 | raise NotImplementedError('Method not implemented!') 73 | 74 | def CreateViewCount(self, request, context): 75 | """Missing associated documentation comment in .proto file.""" 76 | context.set_code(grpc.StatusCode.UNIMPLEMENTED) 77 | context.set_details('Method not implemented!') 78 | raise NotImplementedError('Method not implemented!') 79 | 80 | def UpdateViewCount(self, request, context): 81 | """Missing associated documentation comment in .proto file.""" 82 | context.set_code(grpc.StatusCode.UNIMPLEMENTED) 83 | context.set_details('Method not implemented!') 84 | raise NotImplementedError('Method not implemented!') 85 | 86 | def DeleteViewCount(self, request, context): 87 | """Missing associated documentation comment in .proto file.""" 88 | context.set_code(grpc.StatusCode.UNIMPLEMENTED) 89 | context.set_details('Method not implemented!') 90 | raise NotImplementedError('Method not implemented!') 91 | 92 | 93 | def add_PostViewAnalyticsServicer_to_server(servicer, server): 94 | rpc_method_handlers = { 95 | 'GetViewCount': grpc.unary_unary_rpc_method_handler( 96 | servicer.GetViewCount, 97 | request_deserializer=post__views__pb2.PostViewRequest.FromString, 98 | response_serializer=post__views__pb2.PostViewResponse.SerializeToString, 99 | ), 100 | 'CreateViewCount': grpc.unary_unary_rpc_method_handler( 101 | servicer.CreateViewCount, 102 | request_deserializer=post__views__pb2.PostViewRequest.FromString, 103 | response_serializer=post__views__pb2.PostViewResponse.SerializeToString, 104 | ), 105 | 'UpdateViewCount': grpc.unary_unary_rpc_method_handler( 106 | servicer.UpdateViewCount, 107 | request_deserializer=post__views__pb2.PostViewRequest.FromString, 108 | response_serializer=post__views__pb2.PostViewResponse.SerializeToString, 109 | ), 110 | 'DeleteViewCount': grpc.unary_unary_rpc_method_handler( 111 | servicer.DeleteViewCount, 112 | request_deserializer=post__views__pb2.PostViewRequest.FromString, 113 | response_serializer=post__views__pb2.PostViewResponse.SerializeToString, 114 | ), 115 | } 116 | generic_handler = grpc.method_handlers_generic_handler( 117 | 'PostViewAnalytics', rpc_method_handlers) 118 | server.add_generic_rpc_handlers((generic_handler,)) 119 | server.add_registered_method_handlers('PostViewAnalytics', rpc_method_handlers) 120 | 121 | 122 | # This class is part of an EXPERIMENTAL API. 123 | class PostViewAnalytics(object): 124 | """Missing associated documentation comment in .proto file.""" 125 | 126 | @staticmethod 127 | def GetViewCount(request, 128 | target, 129 | options=(), 130 | channel_credentials=None, 131 | call_credentials=None, 132 | insecure=False, 133 | compression=None, 134 | wait_for_ready=None, 135 | timeout=None, 136 | metadata=None): 137 | return grpc.experimental.unary_unary( 138 | request, 139 | target, 140 | '/PostViewAnalytics/GetViewCount', 141 | post__views__pb2.PostViewRequest.SerializeToString, 142 | post__views__pb2.PostViewResponse.FromString, 143 | options, 144 | channel_credentials, 145 | insecure, 146 | call_credentials, 147 | compression, 148 | wait_for_ready, 149 | timeout, 150 | metadata, 151 | _registered_method=True) 152 | 153 | @staticmethod 154 | def CreateViewCount(request, 155 | target, 156 | options=(), 157 | channel_credentials=None, 158 | call_credentials=None, 159 | insecure=False, 160 | compression=None, 161 | wait_for_ready=None, 162 | timeout=None, 163 | metadata=None): 164 | return grpc.experimental.unary_unary( 165 | request, 166 | target, 167 | '/PostViewAnalytics/CreateViewCount', 168 | post__views__pb2.PostViewRequest.SerializeToString, 169 | post__views__pb2.PostViewResponse.FromString, 170 | options, 171 | channel_credentials, 172 | insecure, 173 | call_credentials, 174 | compression, 175 | wait_for_ready, 176 | timeout, 177 | metadata, 178 | _registered_method=True) 179 | 180 | @staticmethod 181 | def UpdateViewCount(request, 182 | target, 183 | options=(), 184 | channel_credentials=None, 185 | call_credentials=None, 186 | insecure=False, 187 | compression=None, 188 | wait_for_ready=None, 189 | timeout=None, 190 | metadata=None): 191 | return grpc.experimental.unary_unary( 192 | request, 193 | target, 194 | '/PostViewAnalytics/UpdateViewCount', 195 | post__views__pb2.PostViewRequest.SerializeToString, 196 | post__views__pb2.PostViewResponse.FromString, 197 | options, 198 | channel_credentials, 199 | insecure, 200 | call_credentials, 201 | compression, 202 | wait_for_ready, 203 | timeout, 204 | metadata, 205 | _registered_method=True) 206 | 207 | @staticmethod 208 | def DeleteViewCount(request, 209 | target, 210 | options=(), 211 | channel_credentials=None, 212 | call_credentials=None, 213 | insecure=False, 214 | compression=None, 215 | wait_for_ready=None, 216 | timeout=None, 217 | metadata=None): 218 | return grpc.experimental.unary_unary( 219 | request, 220 | target, 221 | '/PostViewAnalytics/DeleteViewCount', 222 | post__views__pb2.PostViewRequest.SerializeToString, 223 | post__views__pb2.PostViewResponse.FromString, 224 | options, 225 | channel_credentials, 226 | insecure, 227 | call_credentials, 228 | compression, 229 | wait_for_ready, 230 | timeout, 231 | metadata, 232 | _registered_method=True) 233 | -------------------------------------------------------------------------------- /twitter_api/engagements/models.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column, ForeignKey, Integer, UniqueConstraint 2 | from sqlalchemy.orm import relationship 3 | 4 | from twitter_api.database import Base, TimeStampedModel 5 | 6 | 7 | class Like(Base, TimeStampedModel): 8 | __tablename__ = 'likes' 9 | __table_args__ = (UniqueConstraint('user_id', 'post_id', name='unique_like_for_user_post_relations'),) 10 | 11 | id = Column(Integer, primary_key=True) 12 | user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False) 13 | post_id = Column(Integer, ForeignKey('posts.id', ondelete='CASCADE'), nullable=False) 14 | user = relationship('User', foreign_keys='Like.user_id') 15 | post = relationship('Post', foreign_keys='Like.post_id') 16 | 17 | 18 | class Bookmark(Base, TimeStampedModel): 19 | __tablename__ = 'bookmarks' 20 | __table_args__ = (UniqueConstraint('user_id', 'post_id', name='unique_bookmark_for_user_post_relations'),) 21 | 22 | id = Column(Integer, primary_key=True) 23 | user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False) 24 | post_id = Column(Integer, ForeignKey('posts.id', ondelete='CASCADE'), nullable=False) 25 | user = relationship('User', foreign_keys='Bookmark.user_id') 26 | post = relationship('Post', foreign_keys='Bookmark.post_id') 27 | 28 | 29 | class View(Base, TimeStampedModel): 30 | __tablename__ = 'views' 31 | __table_args__ = (UniqueConstraint('post_id', name='unique_view_for_post_relations'),) 32 | 33 | id = Column(Integer, primary_key=True) 34 | post_id = Column(Integer, ForeignKey('posts.id', ondelete='CASCADE'), nullable=False) 35 | count = Column(Integer, default=0) 36 | post = relationship('Post', foreign_keys='View.post_id') 37 | -------------------------------------------------------------------------------- /twitter_api/engagements/routes.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status 2 | 3 | from twitter_api.core import exceptions 4 | from twitter_api.database import DbSession 5 | from twitter_api.posts.depends import PostByID 6 | from twitter_api.users.depends import CurrentUser 7 | 8 | from . import services 9 | 10 | router = APIRouter() 11 | 12 | 13 | @router.get('/statistics/{post_id}/', status_code=status.HTTP_200_OK) 14 | def count_total_post_statistics(db_session: DbSession, post: PostByID): 15 | likes_count = services.count_total_likes_for_post(db_session=db_session, post=post) 16 | bookmarks_count = services.count_total_bookmarks_for_post(db_session=db_session, post=post) 17 | views_count = services.count_total_views_for_post(post_id=post.id) 18 | return {'views_count': views_count, 'likes_count': likes_count, 'bookmarks_count': bookmarks_count} 19 | 20 | 21 | @router.get('/likes/{post_id}/', status_code=status.HTTP_200_OK) 22 | def count_post_likes(db_session: DbSession, post: PostByID): 23 | likes_count = services.count_total_likes_for_post(db_session=db_session, post=post) 24 | return {'likes_count': likes_count} 25 | 26 | 27 | @router.post('/likes/{post_id}/', status_code=status.HTTP_201_CREATED) 28 | def like_post(user: CurrentUser, db_session: DbSession, post: PostByID): 29 | like = services.get_like_by_user_post(db_session=db_session, user=user, post=post) 30 | if like is not None: 31 | raise exceptions.BadRequest(detail=f'You have already like post #{post.id}') 32 | services.create_like_for_post(db_session=db_session, user=user, post=post) 33 | return {'message': f'User #{user.id} liked post #{post.id}'} 34 | 35 | 36 | @router.delete('/likes/{post_id}/', status_code=status.HTTP_204_NO_CONTENT) 37 | def dislike_post(user: CurrentUser, db_session: DbSession, post: PostByID): 38 | like = services.get_like_by_user_post(db_session=db_session, user=user, post=post) 39 | if like is None: 40 | raise exceptions.NotFound(detail=f'User #{user.id} did not liked post #{post.id}') 41 | if like.user_id != user.id: 42 | raise exceptions.NotFound(detail=f'You did not like post #{post.id}') 43 | services.delete_like_for_post(db_session=db_session, like=like) 44 | return {'message': f'User #{user.id} disliked post #{post.id}'} 45 | 46 | 47 | @router.get('/bookmarks/{post_id}/', status_code=status.HTTP_200_OK) 48 | def count_post_bookmarks(db_session: DbSession, post: PostByID): 49 | bookmarks_count = services.count_total_bookmarks_for_post(db_session=db_session, post=post) 50 | return {'bookmarks_count': bookmarks_count} 51 | 52 | 53 | @router.post('/bookmarks/{post_id}/', status_code=status.HTTP_201_CREATED) 54 | def bookmark_post(user: CurrentUser, db_session: DbSession, post: PostByID): 55 | bookmark = services.get_bookmark_by_user_post(db_session=db_session, user=user, post=post) 56 | if bookmark is not None: 57 | raise exceptions.BadRequest(detail=f'You have already bookmarked post #{post.id}') 58 | services.create_bookmark_for_post(db_session=db_session, user=user, post=post) 59 | return {'message': f'User #{user.id} bookmarked post #{post.id}'} 60 | 61 | 62 | @router.delete('/bookmarks/{post_id}/', status_code=status.HTTP_204_NO_CONTENT) 63 | def un_bookmark_post(user: CurrentUser, db_session: DbSession, post: PostByID): 64 | bookmark = services.get_bookmark_by_user_post(db_session=db_session, user=user, post=post) 65 | if bookmark is None: 66 | raise exceptions.NotFound(detail=f'User #{user.id} did not bookmark post #{post.id}') 67 | if bookmark.user_id != user.id: 68 | raise exceptions.NotFound(detail=f'You did not bookmark post #{post.id}') 69 | services.delete_bookmark_for_post(db_session=db_session, bookmark=bookmark) 70 | return {'message': f'User #{user.id} un-bookmark post #{post.id}'} 71 | 72 | 73 | @router.get('/views/{post_id}/') 74 | def get_count_of_post_views(post: PostByID): 75 | post_view_count = services.count_total_views_for_post(post_id=post.id) 76 | return {'post_id': post.id, 'view_count': post_view_count} 77 | -------------------------------------------------------------------------------- /twitter_api/engagements/services.py: -------------------------------------------------------------------------------- 1 | import grpc 2 | from sqlalchemy.orm import Session 3 | 4 | from twitter_api.core.config import settings 5 | from twitter_api.posts.models import Post 6 | from twitter_api.users.models import User 7 | 8 | from .grpc import post_views_pb2, post_views_pb2_grpc 9 | from .models import Bookmark, Like 10 | 11 | 12 | def count_total_views_for_post(*, post_id: int) -> int: 13 | with grpc.insecure_channel(settings.ANALYTICS_URL) as channel: 14 | stub = post_views_pb2_grpc.PostViewAnalyticsStub(channel) 15 | response = stub.GetViewCount(post_views_pb2.PostViewRequest(post_id=post_id)) 16 | return response.post_view_count 17 | 18 | 19 | def count_total_likes_for_post(*, db_session: Session, post: Post) -> int: 20 | total_likes = db_session.query(Like).filter(Like.post_id == post.id).count() 21 | return total_likes 22 | 23 | 24 | def get_like_by_user_post(*, db_session: Session, user: User, post: Post) -> Like: 25 | like = db_session.query(Like).filter(Like.user_id == user.id, Like.post_id == post.id).one_or_none() 26 | return like 27 | 28 | 29 | def create_like_for_post(*, db_session: Session, user: User, post: Post) -> None: 30 | new_like = Like(user_id=user.id, post_id=post.id) 31 | db_session.add(new_like) 32 | db_session.commit() 33 | 34 | 35 | def delete_like_for_post(*, db_session: Session, like: Like) -> None: 36 | db_session.delete(like) 37 | db_session.commit() 38 | 39 | 40 | def count_total_bookmarks_for_post(*, db_session: Session, post: Post) -> int: 41 | total_bookmarks = db_session.query(Bookmark).filter(Bookmark.post_id == post.id).count() 42 | return total_bookmarks 43 | 44 | 45 | def get_bookmark_by_user_post(*, db_session: Session, user: User, post: Post) -> Bookmark: 46 | bookmark = db_session.query(Bookmark).filter(Bookmark.user_id == user.id, Bookmark.post_id == post.id).one_or_none() 47 | return bookmark 48 | 49 | 50 | def create_bookmark_for_post(*, db_session: Session, user: User, post: Post) -> None: 51 | new_like = Bookmark(user_id=user.id, post_id=post.id) 52 | db_session.add(new_like) 53 | db_session.commit() 54 | 55 | 56 | def delete_bookmark_for_post(*, db_session: Session, bookmark: Bookmark) -> None: 57 | db_session.delete(bookmark) 58 | db_session.commit() 59 | -------------------------------------------------------------------------------- /twitter_api/engagements/tasks.py: -------------------------------------------------------------------------------- 1 | import grpc 2 | 3 | from twitter_api.core.config import settings 4 | from twitter_api.core.logging import logger 5 | 6 | from .grpc import post_views_pb2, post_views_pb2_grpc 7 | 8 | 9 | def create_post_view_count_entry(post_id: int): 10 | logger.info('Task to create post #{} views entry has been called'.format(post_id)) 11 | with grpc.insecure_channel(settings.ANALYTICS_URL) as channel: 12 | stub = post_views_pb2_grpc.PostViewAnalyticsStub(channel) 13 | stub.CreateViewCount(post_views_pb2.PostViewRequest(post_id=post_id)) 14 | 15 | 16 | def increase_post_view_count(post_id: int): 17 | logger.info('Task to increase post #{} views entry has been called'.format(post_id)) 18 | with grpc.insecure_channel(settings.ANALYTICS_URL) as channel: 19 | stub = post_views_pb2_grpc.PostViewAnalyticsStub(channel) 20 | stub.UpdateViewCount(post_views_pb2.PostViewRequest(post_id=post_id)) 21 | 22 | 23 | def delete_post_view_count_entry(post_id: int): 24 | logger.info('Task to delete post #{} views entry has been called'.format(post_id)) 25 | with grpc.insecure_channel(settings.ANALYTICS_URL) as channel: 26 | stub = post_views_pb2_grpc.PostViewAnalyticsStub(channel) 27 | stub.DeleteViewCount(post_views_pb2.PostViewRequest(post_id=post_id)) 28 | -------------------------------------------------------------------------------- /twitter_api/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from fastapi.middleware.cors import CORSMiddleware 3 | from sentry_asgi import SentryMiddleware 4 | 5 | from twitter_api.core.config import app_configs, settings 6 | from twitter_api.core.lifespan import lifespan 7 | from twitter_api.core.middleware import AuthenticationMiddleware, ExceptionMiddleware, LoggingMiddleware 8 | from twitter_api.routes import api_router 9 | 10 | 11 | def get_application() -> FastAPI: 12 | app = FastAPI(**app_configs, lifespan=lifespan) 13 | app.include_router(api_router) 14 | return app 15 | 16 | 17 | api = get_application() 18 | 19 | api.add_middleware(SentryMiddleware) 20 | api.add_middleware(LoggingMiddleware) 21 | api.add_middleware( 22 | CORSMiddleware, 23 | allow_origins=settings.CORS_ORIGINS, 24 | allow_origin_regex=settings.CORS_ORIGINS_REGEX, 25 | allow_credentials=True, 26 | allow_methods=('GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'), 27 | allow_headers=settings.CORS_HEADERS, 28 | ) 29 | api.add_middleware(AuthenticationMiddleware) 30 | api.add_middleware(ExceptionMiddleware) 31 | -------------------------------------------------------------------------------- /twitter_api/posts/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/twitter_api/posts/__init__.py -------------------------------------------------------------------------------- /twitter_api/posts/depends.py: -------------------------------------------------------------------------------- 1 | from typing import Annotated 2 | 3 | from fastapi import Depends 4 | 5 | from twitter_api.core import exceptions 6 | from twitter_api.database import DbSession 7 | from twitter_api.users.depends import get_user_by_name 8 | from twitter_api.users.models import User 9 | 10 | from .models import Post 11 | 12 | AuthorByName = Annotated[User, Depends(get_user_by_name)] 13 | 14 | 15 | async def get_post_by_id(post_id: int, db_session: DbSession) -> Post: 16 | post = db_session.query(Post).filter(Post.id == post_id).one_or_none() 17 | if post is None: 18 | raise exceptions.NotFound(detail=f'Post {post_id} not found') 19 | return post 20 | 21 | 22 | PostByID = Annotated[Post, Depends(get_post_by_id)] 23 | 24 | 25 | async def get_post_by_post_id_and_author(post_id: int, author: AuthorByName, db_session: DbSession) -> Post: 26 | author_post = db_session.query(Post).filter(Post.id == post_id, Post.author_id == author.id).one_or_none() 27 | if author_post is None: 28 | raise exceptions.NotFound(detail=f'Post {post_id} not found') 29 | return author_post 30 | 31 | 32 | PostByAuthor = Annotated[Post, Depends(get_post_by_post_id_and_author)] 33 | -------------------------------------------------------------------------------- /twitter_api/posts/models.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | from typing import Optional 3 | 4 | from pydantic import Field 5 | from sqlalchemy import Column, ForeignKey, Integer, String 6 | from sqlalchemy.orm import relationship 7 | 8 | from twitter_api.core.pagination import Pagination 9 | from twitter_api.database import Base, PydanticBase, TimeStampedModel 10 | 11 | 12 | class Post(Base, TimeStampedModel): 13 | __tablename__ = 'posts' 14 | 15 | id = Column(Integer, primary_key=True) 16 | content = Column(String(128), nullable=False) 17 | author_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False) 18 | author = relationship('User', backref='posts') 19 | quoted_post_id = Column(Integer, ForeignKey('posts.id'), nullable=True) 20 | quoted_post = relationship('Post', remote_side='Post.id') 21 | 22 | def __str__(self): 23 | return f'{self.author}#{self.id}' 24 | 25 | 26 | class Mention(Base, TimeStampedModel): 27 | __tablename__ = 'mentions' 28 | 29 | id = Column(Integer, primary_key=True) 30 | mention_id = Column(Integer, ForeignKey('posts.id'), nullable=False) 31 | original_post_id = Column(Integer, ForeignKey('posts.id'), nullable=False) 32 | mention = relationship('Post', foreign_keys=[mention_id]) 33 | original_post = relationship('Post', foreign_keys=[original_post_id]) 34 | 35 | 36 | class PostPayload(PydanticBase): 37 | content: str = Field(max_length=128) 38 | 39 | 40 | class PostDetail(PydanticBase): 41 | id: int 42 | content: str 43 | created_at: datetime 44 | updated_at: datetime 45 | 46 | 47 | class PostDetailWithQuote(PostDetail): 48 | quoted_post: Optional[PostDetail] 49 | 50 | 51 | class PostList(Pagination): 52 | items: list[PostDetail] = [] 53 | 54 | 55 | class PostWithQuoteList(Pagination): 56 | items: list[PostDetailWithQuote] = [] 57 | -------------------------------------------------------------------------------- /twitter_api/posts/routes.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, BackgroundTasks, status 2 | 3 | from twitter_api.core import exceptions 4 | from twitter_api.core.pagination import paginate 5 | from twitter_api.database import DbSession 6 | from twitter_api.engagements import tasks 7 | from twitter_api.users.depends import CurrentUser 8 | 9 | from . import services 10 | from .depends import AuthorByName, PostByAuthor, PostByID 11 | from .models import PostDetail, PostDetailWithQuote, PostList, PostPayload, PostWithQuoteList 12 | 13 | router = APIRouter() 14 | 15 | 16 | @router.get('/{username}/', response_model=PostWithQuoteList) 17 | async def list_user_posts_with_their_quoted(db_session: DbSession, author: AuthorByName, page: int = 1): 18 | author_posts = services.get_post_by_author(db_session=db_session, author=author) 19 | return paginate(items=author_posts, page=page) 20 | 21 | 22 | @router.get('/{username}/{post_id}/', response_model=PostDetailWithQuote) 23 | async def get_user_post_detail_with_its_quoted(post: PostByAuthor, worker: BackgroundTasks): 24 | worker.add_task(tasks.increase_post_view_count, post.id) 25 | return post 26 | 27 | 28 | @router.get('/{username}/{post_id}/mentions/', response_model=PostList) 29 | async def get_mentions_of_user_post(db_session: DbSession, post: PostByAuthor, page: int = 1): 30 | mentions = services.get_mentions_by_post(db_session=db_session, post=post) 31 | return paginate(items=mentions, page=page) 32 | 33 | 34 | @router.post('/{username}/{post_id}/mentions/', status_code=status.HTTP_201_CREATED, response_model=PostDetail) 35 | async def create_mention_on_post( 36 | user: CurrentUser, db_session: DbSession, post: PostByAuthor, worker: BackgroundTasks, payload: PostPayload 37 | ): 38 | new_mention = services.create_mention_for_post(db_session=db_session, author=user, post=post, context=payload) 39 | worker.add_task(tasks.create_post_view_count_entry, new_mention.id) 40 | return new_mention 41 | 42 | 43 | @router.get('/{username}/{post_id}/quotes/', response_model=PostWithQuoteList) 44 | async def get_quotes_for_user_post(db_session: DbSession, post: PostByAuthor, page: int = 1): 45 | quotes = services.get_quotes_by_post(db_session=db_session, post=post) 46 | return paginate(items=quotes, page=page) 47 | 48 | 49 | @router.post('/{username}/{post_id}/quotes/', status_code=status.HTTP_201_CREATED, response_model=PostDetail) 50 | async def create_quote_on_user_post( 51 | user: CurrentUser, db_session: DbSession, post: PostByAuthor, worker: BackgroundTasks, payload: PostPayload 52 | ): 53 | new_quote = services.create_quote_for_post(db_session=db_session, author=user, post=post, context=payload) 54 | worker.add_task(tasks.create_post_view_count_entry, new_quote.id) 55 | return new_quote 56 | 57 | 58 | @router.post('/', status_code=status.HTTP_201_CREATED, response_model=PostDetail) 59 | async def create_user_post(user: CurrentUser, db_session: DbSession, worker: BackgroundTasks, payload: PostPayload): 60 | new_post = services.create_post_for_user(db_session=db_session, author=user, context=payload) 61 | worker.add_task(tasks.create_post_view_count_entry, new_post.id) 62 | return new_post 63 | 64 | 65 | @router.patch('/{post_id}/', status_code=status.HTTP_206_PARTIAL_CONTENT, response_model=PostDetail) 66 | async def update_user_post(user: CurrentUser, db_session: DbSession, post: PostByID, payload: PostPayload): 67 | if post.author_id != user.id: 68 | raise exceptions.PermissionDenied(detail=f'You do not own post #{post.id}') 69 | updated_post = services.update_post_for_user(db_session=db_session, post=post, context=payload) 70 | return updated_post 71 | 72 | 73 | @router.delete('/{post_id}/', status_code=status.HTTP_204_NO_CONTENT) 74 | async def delete_user_post(user: CurrentUser, db_session: DbSession, post: PostByID, worker: BackgroundTasks): 75 | post_id = post.id 76 | if post.author_id != user.id: 77 | raise exceptions.PermissionDenied(detail=f'You do not own post #{post.id}') 78 | services.delete_post_for_user(db_session=db_session, post=post) 79 | worker.add_task(tasks.delete_post_view_count_entry, post_id) 80 | return {'message': f'Deleted post {post_id}'} 81 | -------------------------------------------------------------------------------- /twitter_api/posts/services.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm import Query, Session 2 | 3 | from twitter_api.users.models import User 4 | 5 | from .models import Mention, Post, PostPayload 6 | 7 | 8 | def get_post_by_author(*, db_session: Session, author: User) -> Query[Post]: 9 | author_posts = db_session.query(Post).filter(Post.author_id == author.id) 10 | return author_posts 11 | 12 | 13 | def get_mentions_by_post(*, db_session: Session, post: Post) -> Query[Post]: 14 | subquery = db_session.query(Mention.mention_id).filter(Mention.original_post_id == post.id).subquery() 15 | mentions = db_session.query(Post).filter(Post.id.in_(subquery)) 16 | return mentions 17 | 18 | 19 | def create_mention_for_post(*, db_session: Session, author: User, post: Post, context: PostPayload) -> Post: 20 | new_mention = Post(content=context.content, author_id=author.id) 21 | db_session.add(new_mention) 22 | db_session.commit() 23 | mention_relation = Mention(original_post_id=post.id, mention_id=new_mention.id) 24 | db_session.add(mention_relation) 25 | db_session.commit() 26 | return new_mention 27 | 28 | 29 | def get_quotes_by_post(*, db_session: Session, post: Post) -> Query[Post]: 30 | subquery = db_session.query(Post.id).filter(Post.quoted_post_id == post.id).subquery() 31 | quotes = db_session.query(Post).filter(Post.id.in_(subquery)) 32 | return quotes 33 | 34 | 35 | def create_quote_for_post(*, db_session: Session, author: User, post: Post, context: PostPayload) -> Post: 36 | new_quote = Post(content=context.content, author_id=author.id, quoted_post_id=post.id) 37 | db_session.add(new_quote) 38 | db_session.commit() 39 | return new_quote 40 | 41 | 42 | def create_post_for_user(*, db_session: Session, author: User, context: PostPayload) -> Post: 43 | new_post = Post(content=context.content, author_id=author.id) 44 | db_session.add(new_post) 45 | db_session.commit() 46 | return new_post 47 | 48 | 49 | def update_post_for_user(*, db_session: Session, post: Post, context: PostPayload) -> Post: 50 | post.content = context.content 51 | db_session.commit() 52 | return post 53 | 54 | 55 | def delete_post_for_user(*, db_session: Session, post: Post) -> None: 56 | db_session.delete(post) 57 | db_session.commit() 58 | -------------------------------------------------------------------------------- /twitter_api/routes.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter 2 | 3 | from twitter_api.engagements.routes import router as engagement_router 4 | from twitter_api.posts.routes import router as post_router 5 | from twitter_api.users.routes import auth_router, user_router 6 | 7 | api_router = APIRouter() 8 | 9 | api_router.include_router(auth_router, prefix='/auth', tags=['Authentication']) 10 | api_router.include_router(user_router, prefix='/users', tags=['Users']) 11 | api_router.include_router(post_router, prefix='/posts', tags=['Posts']) 12 | api_router.include_router(engagement_router, prefix='/engagements', tags=['Engagements']) 13 | 14 | 15 | @api_router.get('/healthcheck/', include_in_schema=False) 16 | def healthcheck(): 17 | return {'status': 'ok'} 18 | -------------------------------------------------------------------------------- /twitter_api/users/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinDruid/twitter-fast-api/51222e79d33c8cca73574d66ec429a8240cdac2a/twitter_api/users/__init__.py -------------------------------------------------------------------------------- /twitter_api/users/auth.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | import bcrypt 4 | from jose import jwt 5 | 6 | from twitter_api.core.config import settings 7 | 8 | 9 | def generate_token(*, user) -> str: 10 | now = datetime.datetime.utcnow() 11 | exp = (now + datetime.timedelta(seconds=settings.JWT_EXP)).timestamp() 12 | data = {'exp': exp, 'username': user.username, 'id': user.id} 13 | return jwt.encode(data, settings.JWT_SECRET, algorithm=settings.JWT_ALG) 14 | 15 | 16 | def hash_password(password: str) -> str: 17 | pw = bytes(password, 'utf-8') 18 | salt = bcrypt.gensalt() 19 | return bcrypt.hashpw(pw, salt).decode('utf-8') 20 | 21 | 22 | def check_password(*, user, password: str) -> bool: 23 | return bcrypt.checkpw(password.encode('utf-8'), user.password.encode('utf-8')) 24 | -------------------------------------------------------------------------------- /twitter_api/users/depends.py: -------------------------------------------------------------------------------- 1 | from typing import Annotated 2 | 3 | from fastapi import Depends, Request 4 | 5 | from twitter_api.core import exceptions 6 | from twitter_api.core.middleware import AuthenticatedUser 7 | from twitter_api.database import DbSession 8 | 9 | from .models import Followership, User 10 | 11 | 12 | def get_current_user(request: Request) -> AuthenticatedUser: 13 | if request.state.user.is_anonymous: 14 | raise exceptions.NotAuthenticated 15 | return request.state.user 16 | 17 | 18 | CurrentUser = Annotated[AuthenticatedUser, Depends(get_current_user)] 19 | 20 | 21 | def get_user_by_name(username: str, db_session: DbSession) -> User: 22 | user = db_session.query(User).filter(User.username == username).one_or_none() 23 | if user is None: 24 | raise exceptions.NotFound(detail=f'User {username} not found') 25 | return user 26 | 27 | 28 | UserByName = Annotated[User, Depends(get_user_by_name)] 29 | 30 | 31 | def get_user_by_id(user_id: int, db_session: DbSession) -> User: 32 | user = db_session.query(User).filter(User.id == user_id).one_or_none() 33 | if user is None: 34 | raise exceptions.NotFound(detail=f'User {user_id} not found') 35 | return user 36 | 37 | 38 | UserByID = Annotated[User, Depends(get_user_by_id)] 39 | 40 | 41 | def get_follower_by_follower_id_and_user(follower_user_id: int, user: UserByID, db_session: DbSession) -> Followership: 42 | follower = ( 43 | db_session.query(Followership) 44 | .filter(Followership.follower_id == follower_user_id, Followership.following_id == user.id) 45 | .one_or_none() 46 | ) 47 | if not follower: 48 | raise exceptions.NotFound(detail=f'User #{follower_user_id} does not follow user #{user.id}') 49 | return follower 50 | 51 | 52 | FollowerByID = Annotated[Followership, Depends(get_follower_by_follower_id_and_user)] 53 | 54 | 55 | def get_following_by_following_user_id_and_user( 56 | following_user_id: int, user: UserByID, db_session: DbSession 57 | ) -> Followership: 58 | following = ( 59 | db_session.query(Followership) 60 | .filter(Followership.following_id == following_user_id, Followership.follower_id == user.id) 61 | .one_or_none() 62 | ) 63 | if not following: 64 | raise exceptions.NotFound(detail=f'User #{user.id} does not follow user #{following_user_id}') 65 | return following 66 | 67 | 68 | FollowingByID = Annotated[Followership, Depends(get_following_by_following_user_id_and_user)] 69 | -------------------------------------------------------------------------------- /twitter_api/users/models.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | from pydantic import field_validator 4 | from pydantic.networks import EmailStr 5 | from sqlalchemy import Boolean, CheckConstraint, Column, ForeignKey, Integer, String, UniqueConstraint 6 | from sqlalchemy.orm import relationship 7 | 8 | from twitter_api.core.pagination import Pagination 9 | from twitter_api.database import Base, PydanticBase, TimeStampedModel 10 | 11 | from .auth import hash_password 12 | 13 | 14 | class User(Base, TimeStampedModel): 15 | __tablename__ = 'users' 16 | 17 | id = Column(Integer, primary_key=True) 18 | username = Column(String(32), unique=True, index=True) 19 | first_name = Column(String(256), nullable=True) 20 | last_name = Column(String(256), nullable=True) 21 | email = Column(String(256), nullable=False, unique=True, index=True) 22 | is_active = Column(Boolean, default=True) 23 | password = Column(String(128), nullable=False) 24 | 25 | def __str__(self): 26 | return f'{self.first_name} {self.last_name}' 27 | 28 | 29 | class Followership(Base, TimeStampedModel): 30 | __tablename__ = 'followerships' 31 | __table_args__ = ( 32 | CheckConstraint('follower_id <> following_id', name='user_can_not_follow_themself'), 33 | UniqueConstraint('following_id', 'follower_id', name='unique_followership_relations'), 34 | ) 35 | id = Column(Integer, primary_key=True) 36 | following_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False) 37 | follower_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False) 38 | following = relationship('User', foreign_keys='Followership.following_id') 39 | follower = relationship('User', foreign_keys='Followership.follower_id') 40 | 41 | def __str__(self): 42 | return f'{self.following_id}->{self.follower_id}' 43 | 44 | 45 | class UserCreatePayload(PydanticBase): 46 | username: str 47 | email: EmailStr 48 | password: str 49 | 50 | @field_validator('password') 51 | @classmethod 52 | def make_hash(cls, password: str) -> str: 53 | return hash_password(password) 54 | 55 | 56 | class UserLoginPayload(PydanticBase): 57 | username: str 58 | password: str 59 | 60 | 61 | class UserDetail(PydanticBase): 62 | id: int 63 | username: str 64 | email: EmailStr 65 | first_name: Optional[str] = '' 66 | last_name: Optional[str] = '' 67 | 68 | 69 | class UserList(Pagination): 70 | items: list[UserDetail] = [] 71 | 72 | 73 | class FollowerShipPayload(PydanticBase): 74 | user_id: int 75 | -------------------------------------------------------------------------------- /twitter_api/users/routes.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status 2 | 3 | from twitter_api.core import exceptions 4 | from twitter_api.core.pagination import paginate 5 | from twitter_api.database import DbSession 6 | 7 | from . import services 8 | from .auth import check_password, generate_token 9 | from .depends import CurrentUser, FollowerByID, FollowingByID, UserByID 10 | from .models import FollowerShipPayload, User, UserCreatePayload, UserDetail, UserList, UserLoginPayload 11 | 12 | auth_router = APIRouter() 13 | user_router = APIRouter() 14 | 15 | 16 | @user_router.get('/profile/{user_id}/', response_model=UserDetail) 17 | def get_user_profile(db_session: DbSession, user: UserByID): 18 | return user 19 | 20 | 21 | @user_router.delete('/profile/{user_id}/', status_code=status.HTTP_204_NO_CONTENT) 22 | def delete_user(current_user: CurrentUser, db_session: DbSession, user: UserByID): 23 | if current_user.id != user.id: 24 | raise exceptions.PermissionDenied 25 | services.delete_user(db_session=db_session, user=user) 26 | return {'message': f'Deleted user {user.username}'} 27 | 28 | 29 | @user_router.get('/{user_id}/followers/', response_model=UserList) 30 | def get_user_followers(db_session: DbSession, user: UserByID, page: int = 1): 31 | followers = services.get_followers_by_user(db_session=db_session, user=user) 32 | return paginate(items=followers, page=page) 33 | 34 | 35 | @user_router.delete('/{user_id}/followers/{follower_user_id}/', status_code=status.HTTP_204_NO_CONTENT) 36 | def remove_user_from_followers( 37 | current_user: CurrentUser, db_session: DbSession, user: UserByID, follower: FollowerByID 38 | ): 39 | if current_user.id != user.id: 40 | raise exceptions.PermissionDenied 41 | services.remove_user_from_followers(db_session=db_session, follower=follower) 42 | return {'message': f'User #{follower.follower_id} removed from followers'} 43 | 44 | 45 | @user_router.get('/{user_id}/followings/', response_model=UserList) 46 | def get_user_followings(db_session: DbSession, user: UserByID, page: int = 1): 47 | followings = services.get_followings_by_user(db_session=db_session, user=user) 48 | return paginate(items=followings, page=page) 49 | 50 | 51 | @user_router.post('/{user_id}/followings/', status_code=status.HTTP_201_CREATED) 52 | def follow_user(current_user: CurrentUser, db_session: DbSession, user: UserByID, following: FollowerShipPayload): 53 | if current_user.id != user.id: 54 | raise exceptions.PermissionDenied 55 | if user.id == following.user_id: 56 | raise exceptions.BadRequest(detail='User can not follow themselves') 57 | services.follow_user(db_session=db_session, user=user, following_id=following.user_id) 58 | return {'message': f'User #{user.id} now is following user #{following.user_id}'} 59 | 60 | 61 | @user_router.delete('/{user_id}/followings/{following_user_id}/', status_code=status.HTTP_204_NO_CONTENT) 62 | def unfollow_user(current_user: CurrentUser, db_session: DbSession, user: UserByID, following: FollowingByID): 63 | if current_user.id != user.id: 64 | raise exceptions.PermissionDenied 65 | services.unfollow_user(db_session=db_session, following=following) 66 | return {'message': f'Unfollowed user #{following.following_id}'} 67 | 68 | 69 | @auth_router.post('/', response_model=UserDetail, status_code=status.HTTP_201_CREATED) 70 | def create_user(db_session: DbSession, payload: UserCreatePayload): 71 | email_already_exist = services.get_user_by_username(db_session=db_session, username=payload.username) 72 | username_already_exist = services.get_user_by_email(db_session=db_session, email=payload.email) 73 | if email_already_exist or username_already_exist: 74 | raise exceptions.BadRequest(detail='User already exists') 75 | new_user = services.create_user( 76 | db_session=db_session, username=payload.username, email=payload.email, password=payload.password 77 | ) 78 | return new_user 79 | 80 | 81 | @auth_router.post('/login/') 82 | def login_user(db_session: DbSession, payload: UserLoginPayload): 83 | user = db_session.query(User).filter(User.username == payload.username).one_or_none() 84 | if user is None: 85 | raise exceptions.NotAuthenticated 86 | is_authenticated = check_password(user=user, password=payload.password) 87 | if not is_authenticated: 88 | raise exceptions.NotAuthenticated 89 | token = generate_token(user=user) 90 | return {'username': user.username, 'token': token} 91 | -------------------------------------------------------------------------------- /twitter_api/users/services.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm import Query, Session 2 | 3 | from .depends import FollowerByID, FollowingByID 4 | from .models import Followership, User 5 | 6 | 7 | def get_user_by_email(*, db_session: Session, email: str): 8 | user = db_session.query(User.email == email).one_or_none() 9 | return user 10 | 11 | 12 | def get_user_by_username(*, db_session: Session, username: str): 13 | user = db_session.query(User.username == username).one_or_none() 14 | return user 15 | 16 | 17 | def delete_user(*, db_session: Session, user: User) -> None: 18 | db_session.delete(user) 19 | db_session.commit() 20 | 21 | 22 | def get_followers_by_user(*, db_session: Session, user: User) -> Query[User]: 23 | subquery = db_session.query(Followership.follower_id).filter(Followership.following_id == user.id).subquery() 24 | followers = db_session.query(User).filter(User.id.in_(subquery)) 25 | return followers 26 | 27 | 28 | def remove_user_from_followers(*, db_session: Session, follower: FollowerByID) -> None: 29 | db_session.delete(follower) 30 | db_session.commit() 31 | 32 | 33 | def get_followings_by_user(*, db_session: Session, user: User) -> Query[User]: 34 | subquery = db_session.query(Followership.following_id).filter(Followership.follower_id == user.id).subquery() 35 | followings = db_session.query(User).filter(User.id.in_(subquery)) 36 | return followings 37 | 38 | 39 | def follow_user(*, db_session: Session, user: User, following_id: int) -> None: 40 | followership = Followership(follower_id=user.id, following_id=following_id) 41 | db_session.add(followership) 42 | db_session.commit() 43 | 44 | 45 | def unfollow_user(*, db_session: Session, following: FollowingByID) -> None: 46 | db_session.delete(following) 47 | db_session.commit() 48 | 49 | 50 | def create_user(*, db_session: Session, username: str, email: str, password: str): 51 | user = User(email=email, username=username, password=password) 52 | db_session.add(user) 53 | db_session.commit() 54 | return user 55 | --------------------------------------------------------------------------------