Skip to content

Commit

Permalink
Merge pull request #81 from ShotaTanemura/refactor/71-add-linter-and-…
Browse files Browse the repository at this point in the history
…formatter-for-python

linter, formatter の追加
  • Loading branch information
ShotaTanemura authored Jul 20, 2024
2 parents c648a6b + 6771e67 commit fca2776
Show file tree
Hide file tree
Showing 23 changed files with 841 additions and 697 deletions.
1 change: 1 addition & 0 deletions .devcontainer/requirements/Django/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ uvicorn==0.30.1
channels==4.1.0
channels_redis==4.2.0
websockets==12.0.0
ruff==0.5.2
pillow==10.4.0
11 changes: 11 additions & 0 deletions .github/workflows/ruff.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
name: ruff
on: push
jobs:
ruff:
name: syntax-check-python
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: chartboost/ruff-action@v1
with:
args: 'format --check'
31 changes: 17 additions & 14 deletions pong/config/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,30 @@

import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.urls import path
from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
django_asgi_app = application = get_asgi_application()

# import consumers here
from .consumers import SampleConsumer
from .consumers import SampleConsumer
from pong.middleware.auth import ChannelsJWTAuthenticationMiddleware

application = ProtocolTypeRouter({
"http": django_asgi_app,
"websocket": AllowedHostsOriginValidator(
ChannelsJWTAuthenticationMiddleware(
URLRouter([
path("test/", SampleConsumer.as_asgi()),
#path("chat/", PublicChatConsumer.as_asgi()),
])
)
),
})
application = ProtocolTypeRouter(
{
"http": django_asgi_app,
"websocket": AllowedHostsOriginValidator(
ChannelsJWTAuthenticationMiddleware(
URLRouter(
[
path("test/", SampleConsumer.as_asgi()),
# path("chat/", PublicChatConsumer.as_asgi()),
]
)
)
),
}
)
3 changes: 1 addition & 2 deletions pong/config/consumers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from channels.generic.websocket import AsyncWebsocketConsumer
from django.contrib.auth.models import AnonymousUser

class SampleConsumer(AsyncWebsocketConsumer):

class SampleConsumer(AsyncWebsocketConsumer):
async def connect(self):
if self.scope["user"] == AnonymousUser():
await self.close()
Expand All @@ -15,4 +15,3 @@ async def connect(self):

async def receive(self, text_data=None, bytes_data=None):
print(text_data)

129 changes: 64 additions & 65 deletions pong/config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
from pathlib import Path
import datetime
import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
Expand All @@ -23,69 +22,69 @@
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-f9o0g5c=(hz*lj*=qppxb4$+l-#2#g)+lr2#2f-#m*8fiskm^#'
SECRET_KEY = "django-insecure-f9o0g5c=(hz*lj*=qppxb4$+l-#2#g)+lr2#2f-#m*8fiskm^#"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']
ALLOWED_HOSTS = ["*"]


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pong',
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"pong",
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'pong.middleware.auth.JWTAuthenticationMiddleware'
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"pong.middleware.auth.JWTAuthenticationMiddleware",
]

ROOT_URLCONF = 'config.urls'
ROOT_URLCONF = "config.urls"

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]

WSGI_APPLICATION = 'config.wsgi.application'
WSGI_APPLICATION = "config.wsgi.application"


# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
import os;

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.getenv("POSTGRES_NAME"),
'USER': os.getenv("POSTGRES_USER"),
'PASSWORD': os.getenv("POSTGRES_PASSWORD"),
'HOST': 'db',
'PORT': 5432
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": os.getenv("POSTGRES_NAME"),
"USER": os.getenv("POSTGRES_USER"),
"PASSWORD": os.getenv("POSTGRES_PASSWORD"),
"HOST": "db",
"PORT": 5432,
}
}

Expand All @@ -95,26 +94,26 @@

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]


# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/

LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = "en-us"

TIME_ZONE = 'UTC'
TIME_ZONE = "UTC"

USE_I18N = True

Expand All @@ -124,44 +123,44 @@
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = 'static/'
STATIC_ROOT = 'static/'
STATIC_URL = "static/"
STATIC_ROOT = "static/"

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# 追加
AUTH_USER_MODEL = 'pong.User'
PRIVATE_KEY_PATH = os.path.join(BASE_DIR, 'keys', 'private_key.pem')
PUBLIC_KEY_PATH = os.path.join(BASE_DIR, 'keys', 'public_key.pem')
with open(PRIVATE_KEY_PATH, 'r') as f:
AUTH_USER_MODEL = "pong.User"
PRIVATE_KEY_PATH = os.path.join(BASE_DIR, "keys", "private_key.pem")
PUBLIC_KEY_PATH = os.path.join(BASE_DIR, "keys", "public_key.pem")
with open(PRIVATE_KEY_PATH, "r") as f:
PRIVATE_KEY = f.read()
with open(PUBLIC_KEY_PATH, 'r') as f:
with open(PUBLIC_KEY_PATH, "r") as f:
PUBLIC_KEY = f.read()
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=30),
'JWT_PRIVATE_KEY': PRIVATE_KEY,
'JWT_PUBLIC_KEY': PUBLIC_KEY,
'JWT_ALGORITHM': 'RS256',
"JWT_EXPIRATION_DELTA": datetime.timedelta(days=1),
"JWT_REFRESH_EXPIRATION_DELTA": datetime.timedelta(days=30),
"JWT_PRIVATE_KEY": PRIVATE_KEY,
"JWT_PUBLIC_KEY": PUBLIC_KEY,
"JWT_ALGORITHM": "RS256",
}

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"

PEPPER = os.getenv('PEPPER')
OAUTH_CALLBACK_42API = os.getenv('OAUTH_CALLBACK_42API')
CLIENT_ID_42API = os.getenv('CLIENT_ID_42API')
CLIENT_SECRET_42API = os.getenv('CLIENT_SECRET_42API')
PEPPER = os.getenv("PEPPER")
OAUTH_CALLBACK_42API = os.getenv("OAUTH_CALLBACK_42API")
CLIENT_ID_42API = os.getenv("CLIENT_ID_42API")
CLIENT_SECRET_42API = os.getenv("CLIENT_SECRET_42API")

REDIS_HOST = 'redis'
REDIS_HOST = "redis"
REDIS_PORT = 6379
REDIS_DB = 0
REDIS_URL = f'redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}'
REDIS_URL = f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}"

# channelsのためのlayerの追加 
# channelsのためのlayerの追加
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
Expand Down
7 changes: 4 additions & 3 deletions pong/config/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""

from django.contrib import admin
from django.urls import path, re_path, include
from pong.views.index import index

urlpatterns = [
path('admin/', admin.site.urls),
path('pong/', include('pong.urls')),
re_path(r'^.*$', index, name='index'),
path("admin/", admin.site.urls),
path("pong/", include("pong.urls")),
re_path(r"^.*$", index, name="index"),
]
2 changes: 1 addition & 1 deletion pong/config/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")

application = get_wsgi_application()
5 changes: 3 additions & 2 deletions pong/manage.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""

import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
Expand All @@ -18,5 +19,5 @@ def main():
execute_from_command_line(sys.argv)


if __name__ == '__main__':
if __name__ == "__main__":
main()
2 changes: 0 additions & 2 deletions pong/pong/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
from django.contrib import admin

# Register your models here.
4 changes: 2 additions & 2 deletions pong/pong/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@


class PongConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'pong'
default_auto_field = "django.db.models.BigAutoField"
name = "pong"
Loading

0 comments on commit fca2776

Please sign in to comment.