Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add examples #64

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
## Example leaderboard project

Example leaderboard project to demonstrate how to get started with templates.

It includes 3 endpoints:

## `/api/v1/user/create`

### Request

```json
HTTP POST /api/v1/user/create

{
"country": "tr",
"display_name": "yagu"
}
```

### Response

```json
{
"error": "",
"success": true,
"data": {
"user_id": "2be26a1d-ee4e-45b1-98fe-f66e3a224c9b"
}
}
```


## `/api/v1/score/submit`


### Request

```json
HTTP POST /api/v1/user/create

{
"user_id": "2be26a1d-ee4e-45b1-98fe-f66e3a224c9b",
"score": 43
}
```

### Response

```json
{
"error": "",
"success": true,
"data": {}
}
```




## `/api/v1/leaderboard`

### Request

```json
HTTP GET /api/v1/leaderboard
```

### Response

```json
{
"error": "",
"success": true,
"data": [
{
"user_id": "7cacffca-3cd0-44e0-a7ef-d1675211a4ca",
"name": "yagu",
"country": "tr",
"points": 100,
"rank": 1
},
{
"user_id": "2be26a1d-ee4e-45b1-98fe-f66e3a224c9b",
"name": "yagu",
"country": "tr",
"points": 43,
"rank": 2
}
]
}
```


### How to run the project?


1. Create the docker image with `docker build . -t leaderboard`
1. Run `docker-compose up` which will start the project
1. Check out the api at http://0.0.0.0:8000/docs

141 changes: 141 additions & 0 deletions examples/leaderboard/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# Text Editor
.vscode
13 changes: 13 additions & 0 deletions examples/leaderboard/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
FROM python:3.9-slim

RUN pip install --upgrade pip

COPY ./requirements.txt /app/

RUN apt-get update \
&& apt-get install gcc -y \
&& apt-get clean

RUN pip install -r app/requirements.txt

COPY ./app .
21 changes: 21 additions & 0 deletions examples/leaderboard/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Yagiz Degirmenci

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
7 changes: 7 additions & 0 deletions examples/leaderboard/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# leaderboard

This project was generated via [manage-fastapi](https://ycd.github.io/manage-fastapi/)! :tada:

## License

This project is licensed under the terms of the MIT license.
Empty file.
Empty file.
Empty file.
64 changes: 64 additions & 0 deletions examples/leaderboard/app/api/v1/crud.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
from typing import Any
import random, time
from uuid import uuid4
from pydantic.types import UUID1

from sqlalchemy.engine import create_engine
from app.app.core.models.model import Score, User, UserCreate
from fastapi import APIRouter
from pydantic import BaseModel
from app.app.database import (
database,
user_table,
score_table,
CREATE_LEADERBOARD_VIEW,
CREATE_USERS_WITH_SCORES_VIEW,
GET_LEADERBOARD,
CREATE_SCORE_TABLE,
CREATE_USERS_TABLE,
)

router = APIRouter()


@router.on_event("startup")
async def connect_database():
await database.connect()
await database.execute(CREATE_USERS_TABLE)
await database.execute(CREATE_SCORE_TABLE)
await database.execute(CREATE_USERS_WITH_SCORES_VIEW)
await database.execute(CREATE_LEADERBOARD_VIEW)


@router.on_event("shutdown")
async def disconnect_database():
await database.disconnect()


class Response(BaseModel):
error: str
success: bool
data: Any


@router.post("/user/create")
async def create_user(user: UserCreate):
user_id = str(uuid4())[:40]
query = user_table.insert()
values = {"user_id": user_id, "name": user.display_name, "country": user.country}
await database.execute(query=query, values=values)
return Response(error="", success=True, data={"user_id": user_id})


@router.get("/leaderboard")
async def leaderboard():
rows = await database.fetch_all(GET_LEADERBOARD)
return Response(success=True, error="", data=rows)


@router.post("/score/submit")
async def submit_score(score: Score):
query = score_table.insert()
values = {"user_id": score.user_id, "point": score.score}
await database.execute(query=query, values=values)
return Response(error="", success=True, data={})
Empty file.
40 changes: 40 additions & 0 deletions examples/leaderboard/app/core/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from typing import Any, Dict, List, Optional, Union

from pydantic import AnyHttpUrl, BaseSettings, validator


class Settings(BaseSettings):
PROJECT_NAME: str
BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []

@validator("BACKEND_CORS_ORIGINS", pre=True)
def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]:
if isinstance(v, str) and not v.startswith("["):
return [i.strip() for i in v.split(",")]
elif isinstance(v, (list, str)):
return v
raise ValueError(v)

MYSQL_USER: str
MYSQL_PASSWORD: str
MYSQL_HOST: str
MYSQL_PORT: str
MYSQL_DATABASE: str
DATABASE_URI: Optional[str] = None

@validator("DATABASE_URI", pre=True)
def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Any:
if isinstance(v, str):
return v
return (
f"mysql://{values.get('MYSQL_USER')}:{values.get('MYSQL_PASSWORD')}@{values.get('MYSQL_HOST')}:"
f"{values.get('MYSQL_PORT')}/{values.get('MYSQL_DATABASE')}"
)

class Config:
case_sensitive = True
env_file = "../env"


settings = Settings()
print(settings.DATABASE_URI)
Empty file.
Loading