Skip to content
Merged
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
5 changes: 3 additions & 2 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"UV_PROJECT_ENVIRONMENT": "/home/vscode/.venv"
},
"postCreateCommand": "uv sync --frozen",
"postStartCommand": "uv run pre-commit install",
"remoteUser": "vscode"
"postStartCommand": "uv run pre-commit install && uv run uvicorn backend.__main__:run --factory --reload --port 8080",
"remoteUser": "vscode",
"forwardPorts": [8080]
}
6 changes: 1 addition & 5 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ ARG DEBIAN_VERSION=bookworm
ARG UV_VERSION=latest
ARG VARIANT=3.13


FROM ghcr.io/astral-sh/uv:$UV_VERSION AS uv


FROM python:$VARIANT-slim-$DEBIAN_VERSION

WORKDIR /app
Expand All @@ -23,12 +21,10 @@ ENV UV_LINK_MODE=copy
# hadolint ignore=DL3008
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
# For OpenCV etc...
libgl1 libglib2.0-0 \
# To remove the image size, it is recommended refresh the package cache as follows
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*

RUN uv sync --frozen --no-install-project

ENTRYPOINT ["uv", "run", "python", "-m", "backend"]
ENTRYPOINT ["uv", "run", "uvicorn", "backend.__main__:run", "--factory", "--port", "8080", "--host", "0.0.0.0", "--reload"]
43 changes: 36 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,32 +1,61 @@
# backend-template-python
## 開発の進め方
1. [プロジェクト作成方法](#プロジェクト作成方法)に従ってプロジェクトを作成する
2. [Tools](#Tools)のうち、必要なツールをインストール
3. [実装方法](docs/implement.md)に従って開発を進める

## プロジェクト作成方法
### GUI
右上の `Use this template` からレポジトリを作成できます。

## How to run
```
docker build -t backend_python .
docker run --rm -p 8000:8000 backend_python
```
## uv
## Tools
### エディタ(必須)
エディタはVSCode、もしくはそのフォークであるCursorを推奨しています。

拡張機能として、`Dev Containers`をインストールしてください。

[参考: DevContainerを使ってみよう](https://zenn.dev/bells17/articles/devcontainer-2024)

### Docker(必須)
[公式ページ](https://www.docker.com/)
DevContainerを立ち上げるために必要です。

インストール方法は[こちら](https://github.com/Tech-JAIST/backend-template-go/blob/main/docs/docker.md)を参考にしてください。

### uv(DevContainerに内包)
```sh
# macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh

# Windows
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
```
[ref: uv documentation](https://docs.astral.sh/uv/getting-started/features/)

## Python
### Python(DevContainerに内包)
```sh
uv python install {version}
```

## How to run
DevContainerを立ち上げると8080番ポートでサーバーが立ち上がります。
http://localhost:8080/ (API)

DevContainerを使わず手動で立ち上げたい場合、以下のコマンドを使用してください。
```
docker build -t backend_python . && docker run --rm -p 8080:8080 backend_python
```

## format
```sh
uv run ruff format .
```

## linter check
```sh
ruff check . --fix
```

## Acknowledgements

This project is based on [a5chin/python-uv](https://github.com/a5chin/python-uv/tree/main), which is licensed under the MIT License.
19 changes: 2 additions & 17 deletions backend/__main__.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,12 @@
import asyncio
from typing import TYPE_CHECKING, cast

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from hypercorn.asyncio import serve
from hypercorn.config import Config
from tinydb import TinyDB

if TYPE_CHECKING:
from hypercorn.typing import ASGIFramework

from .handler import get_router
from .repository import get_repository


async def run() -> None:
def run() -> FastAPI:
"""Run the FastAPI application.

This function creates a FastAPI application, sets up CORS middleware,
Expand All @@ -35,11 +27,4 @@ async def run() -> None:
)

app.include_router(get_router(repository))

config = Config()
config.bind = ["0.0.0.0:8000"]
await serve(cast("ASGIFramework", app), config)


if __name__ == "__main__":
asyncio.run(run())
return app
2 changes: 1 addition & 1 deletion backend/handler/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def get_router(repository: Repository) -> APIRouter:
APIRouter: The main router for the application.

"""
router = APIRouter()
router = APIRouter(prefix="/api/v1")

router.include_router(get_ping_router(repository))
router.include_router(get_user_router(repository))
Expand Down
3 changes: 2 additions & 1 deletion backend/repository/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ def __init__(self, db: TinyDB) -> None:

"""
self.db = db
db.insert({"name": "root", "id": "0d9a2f49-99aa-49e6-bcf6-b123953aca63"})
if not self.db.contains(Query().name == "root"):
db.insert({"name": "root", "id": "0d9a2f49-99aa-49e6-bcf6-b123953aca63"})

def get_users(self) -> list[User]:
"""Get all users.
Expand Down
32 changes: 32 additions & 0 deletions docs/implement.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# 実装方法
## 前提知識
### ディレクトリ構造
ディレクトリ構造は以下のようになっています。
```sh
.
├── Dockerfile # PythonアプリのDockerfile
├── compose.yaml # Pythonアプリ, DB, adminerのcompose.yml
├── backend
│   ├── domain # サーバーにおけるメインのデータ型
│   ├── handler # ルーティング
│   ├── repository # DB操作
│   └── __main__.py
```

### 使用しているライブラリ
#### FastAPI
[FastAPI documentation](https://fastapi.tiangolo.com/)

#### tinyDB
[tinyDB documentation](https://tinydb.readthedocs.io/en/latest/)
[tinyDBを使ってみよう](https://scrapbox.io/PythonOsaka/TinyDB%E3%82%92%E4%BD%BF%E3%81%A3%E3%81%A6%E3%81%BF%E3%82%88%E3%81%86)

#### uvicorn
[uvicorn documentation](https://www.uvicorn.org/)

## APIの新規実装
順不同で
- `backend/handler`にルーティング&処理を記述する
- (DB操作があれば)`backend/repository/{model名}.py`に記述し、`backend/handler/{group名}.py`に呼び出し処理を記述する

と変更すると新たなAPIが実装できます。
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ license = { file = "LICENSE" }

dependencies = [
"fastapi>=0.115.12",
"hypercorn>=0.17.3",
"pydantic>=2.10.5",
"pydantic-settings>=2.7.1",
"tinydb>=4.8.2",
"uvicorn>=0.34.2",
]

[tool.uv]
Expand Down
Loading