Skip to content

Commit

Permalink
Merge pull request #7 from keem-hyun/feat/backend-setting
Browse files Browse the repository at this point in the history
[BE] 코드 품질 향상 도구 세팅
  • Loading branch information
viaunixue authored Oct 1, 2024
2 parents 0a8ba2c + 5f5a27e commit b8a2cf2
Show file tree
Hide file tree
Showing 11 changed files with 268 additions and 63 deletions.
81 changes: 81 additions & 0 deletions .github/workflows/code-quality-check-integration.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
name: Backend Code Quality CI

on:
push:
branches: [ develop, release ]
paths:
- 'app/backend/**'
pull_request:
paths:
- 'app/backend/**'

jobs:
lint-and-test:
# Ubuntu 최신 환경에서 실행
runs-on: ubuntu-latest

steps:
# Github Repository 체크아웃
- name: Checkout code
uses: actions/checkout@v4

# python 환경 설정
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.10"

# python 버전 표시
- name : Display Python version
run : python --version

# Python 패키지 설치
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r app/backend/requirements.txt
# 코드 포맷팅 Pre-commit 실행
- name: Run pre-commit
run: |
cd app/backend
pre-commit run --files **/*.py
# 변경사항 확인
- name: Check for changes
id: git-check
run: |
cd app/backend
git diff --exit-code || echo "changes=true" >> $GITHUB_OUTPUT
# 변경사항 커밋 & 푸시
- name: Commit and push changes
if: steps.git-check.outputs.changes == 'true' && github.event_name == 'pull_request'
run: |
git config --local user.email "github-actions[bot]@users.noreply.github.com"
git config --local user.name "github-actions[bot]"
git add app/backend
git commit -m "Apply automatic formatting changes"
git push https://${{ github.actor }}:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git HEAD:${{ github.head_ref }}
# PR에 코멘트 추가
- name: Comment PR
if: steps.git-check.outputs.changes == 'true' && github.event_name == 'pull_request'
uses: actions/github-script@v6
with:
github-token: ${{secrets.GITHUB_TOKEN}}
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.name,
body: '✨ Code has been automatically formatted. Please review the changes.'
})
# 남은 문제 확인
- name: Check for remaining issues
if: failure()
run: |
echo "There are still some issues that couldn't be automatically fixed. Please address them manually."
exit 1
7 changes: 5 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# 개발 환경
.env
app/backend/.env
.env.*
!.env.example

#sonarqube
app/backend/.scannerwork

# 의존성
/node_modules
/.pnp
Expand Down Expand Up @@ -89,7 +92,7 @@ celerybeat.pid
*.sage.py

# dotenv
.env
app/backend/.env

# virtualenv
.venv
Expand Down
32 changes: 32 additions & 0 deletions app/backend/.flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
[flake8]
show-source = true
extend-ignore = E203, E266, E501, W503
exclude =
# No need to traverse our git directory
.git,
# There's no value in checking cache directories
__pycache__,
# The conf file is mostly autogenerated, ignore it
docs/source/conf.py,
# The old directory contains Flake8 2.0
old,
# This contains our built documentation
build,
# This contains builds of flake8 that we don't want to check
dist,
.gitignore,
*/migrations/*
max-complexity = 10
max-line-length = 120
select = B,C,E,F,W,T4,B9,PT
# B : bugbear
# C : comprehensions
# PT : pytest style
#bugbear, comprehensions
extend-select = B950, C4
#pytest style
pytest-fixture-no-parentheses = True
pytest-mark-no-parentheses = True
per-file-ignores =
__init__.py:F401
app/utils/prompts.py:W291,W293
20 changes: 20 additions & 0 deletions app/backend/.pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- repo: https://github.com/psf/black
rev: 24.8.0
hooks:
- id: black
language_version: python3.10
- repo: https://github.com/pycqa/flake8
rev: 7.1.1
hooks:
- id: flake8
additional_dependencies: [flake8-bugbear, flake8-comprehensions, flake8-pytest-style]
5 changes: 3 additions & 2 deletions app/backend/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
# 개발 및 프로덕션 환경을 위한 Dockerfile
FROM python:3.9-slim
FROM python:3.10-slim

WORKDIR /app
WORKDIR /app/backend

# 시스템 의존성 설치
RUN apt-get update && apt-get install -y \
build-essential \
libpq-dev \
&& rm -rf /var/lib/apt/lists/*

# 파이썬 의존성 파일 복사 및 설치
Expand Down
35 changes: 32 additions & 3 deletions app/backend/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@ version: '3.8'
services:
backend:
build:
context: ./backend
context: .
dockerfile: Dockerfile
ports:
- "8000:8000"
environment:
- DATABASE_URL=postgresql://user:password@db:5432/neonadeuli
volumes:
- ./backend:/app
- .:/app/backend
depends_on:
- db


db:
image: postgres:13
environment:
Expand All @@ -23,5 +24,33 @@ services:
volumes:
- postgres_data:/var/lib/postgresql/data

sonarqube:
image: sonarqube:latest
ports:
- "9000:9000"
environment:
- SONAR_JDBC_URL=jdbc:postgresql://sonarqube_db:5432/sonar
- SONAR_JDBC_USERNAME=sonar
- SONAR_JDBC_PASSWORD=sonar
volumes:
- sonarqube_data:/opt/sonarqube/data
- sonarqube_extensions:/opt/sonarqube/extensions
- sonarqube_logs:/opt/sonarqube/logs
depends_on:
- sonarqube_db

sonarqube_db:
image: postgres:13
environment:
- POSTGRES_DB=sonar
- POSTGRES_USER=sonar
- POSTGRES_PASSWORD=sonar
volumes:
- sonarqube_db_data:/var/lib/postgresql/data

volumes:
postgres_data:
postgres_data:
sonarqube_data:
sonarqube_extensions:
sonarqube_logs:
sonarqube_db_data:
40 changes: 22 additions & 18 deletions app/backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@
from src.main.core.exceptions import BaseCustomException, custom_exception_handler
from src.main.middleware.auth import auth_middleware


def custom_generate_unique_id(route: APIRoute) -> str:
if route.tags:
return f"{route.tags[0]}-{route.name}"
return route.name


@asynccontextmanager
async def app_lifespan(app: FastAPI):
# 애플리케이션 시작 시 실행될 로직
Expand All @@ -28,37 +30,39 @@ async def app_lifespan(app: FastAPI):
yield
# 애플리케이션 종료 시 실행될 로직 (필요한 경우)


def create_application() -> FastAPI:
app = FastAPI(
lifespan= app_lifespan,
lifespan=app_lifespan,
# 배포 시 swagger UI, Redoc 비활성화
# docs_url= None,
# redoc_url= None,
title = settings.PROJECT_NAME,
openapi_url=f"{settings.API_V1_STR}/openapi.json",
generate_unique_id_function=custom_generate_unique_id
title=settings.PROJECT_NAME,
# openapi_url=f"{settings.API_V1_STR}/openapi.json",
generate_unique_id_function=custom_generate_unique_id,
)

app.add_exception_handler(BaseCustomException, custom_exception_handler)

app.add_middleware(SessionMiddleware, secret_key=settings.BACKEND_SESSION_SECRET_KEY)
# app.add_middleware(SessionMiddleware, secret_key=settings.BACKEND_SESSION_SECRET_KEY)
app.middleware("http")(auth_middleware)
# Base.metadata.create_all(bind=engine)

# Set All CORS enabled origins
if settings.BACKEND_CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=[
str(origin).strip("/") for origin in settings.BACKEND_CORS_ORIGINS
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)

app.include_router(api_router, prefix=settings.API_V1_STR)
# if settings.BACKEND_CORS_ORIGINS:
# app.add_middleware(
# CORSMiddleware,
# allow_origins=[
# str(origin).strip("/") for origin in settings.BACKEND_CORS_ORIGINS
# ],
# allow_credentials=True,
# allow_methods=["*"],
# allow_headers=["*"]
# )

# app.include_router(api_router, prefix=settings.API_V1_STR)

return app

app = create_application()

app = create_application()
31 changes: 30 additions & 1 deletion app/backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,33 @@ pre-commit = "^3.4.0"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
build-backend = "poetry.core.masonry.api"

[tool.black]
line-length = 120
target-version = ['py37', 'py38']
include = '\.pyi?$'
extend-exclude = '''
/(
# The following are specific to Black, you probably don't want those.
\.eggs
| \.git
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| build
| dist
| blib2to3
| tests/data
| profiling
)/
'''

[tool.isort]
line_length = 120
skip_glob = ["*/migrations/*"]

[tool.mypy]
no_namespace_packages = true
no_strict_optional = true
16 changes: 11 additions & 5 deletions app/backend/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,21 +1,27 @@
fastapi
uvicorn
sqlalchemy[asyncio]>=2.0.0
pymysql==1.1.1
pydantic
passlib
bcrypt
aiomysql
greenlet
python-dotenv
alembic
pytest
cryptography
mysqlclient
alembic
aiohttp
python-jose
boto3
haversine
aiofiles
asyncpg
asyncpg
flake8
black
itsdangerous
pydantic-settings
pre-commit
flake8-bugbear
flake8-comprehensions
flake8-pytest-style
isort
mypy
Loading

0 comments on commit b8a2cf2

Please sign in to comment.