diff --git a/Caddyfile b/Caddyfile new file mode 100644 index 0000000..ebcf6be --- /dev/null +++ b/Caddyfile @@ -0,0 +1,11 @@ +http://guitarlions.localhost + +root * /usr/src/app/ + +@notStatic { + not path /static/* /media/* +} + +reverse_proxy @notStatic django:8000 + +file_server diff --git a/Dockerfiles/django/Dockerfile b/Dockerfiles/django/Dockerfile new file mode 100644 index 0000000..d97949c --- /dev/null +++ b/Dockerfiles/django/Dockerfile @@ -0,0 +1,21 @@ +FROM debian:stable-slim + +ENV PYTHONUNBUFFERED: 1 + +# set work directory +WORKDIR /usr/src/app + +# install software +RUN apt update +RUN apt install -y build-essential cron python3-pip gettext + +# install dependencies +RUN pip3 install --upgrade pip +COPY ./requirements.txt . +RUN pip3 install -r requirements.txt + +# launcher +COPY django-launcher.dev.sh /django-launcher.dev.sh +COPY django-launcher.pro.sh /django-launcher.pro.sh +RUN chmod +x /django-launcher.dev.sh +RUN chmod +x /django-launcher.pro.sh diff --git a/apps/back/__init__.py b/apps/back/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/back/admin.py b/apps/back/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/apps/back/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/apps/back/apps.py b/apps/back/apps.py new file mode 100644 index 0000000..1856dbe --- /dev/null +++ b/apps/back/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class BackConfig(AppConfig): + name = 'back' diff --git a/apps/back/consumers.py b/apps/back/consumers.py new file mode 100644 index 0000000..9b44383 --- /dev/null +++ b/apps/back/consumers.py @@ -0,0 +1,55 @@ +import json +from channels.generic.websocket import AsyncWebsocketConsumer +from asgiref.sync import sync_to_async + +class BackConsumer(AsyncWebsocketConsumer): + + def connect(self): + ''' Cliente se conecta ''' + + # Recoge el nombre de la sala + self.room_name = self.scope["url_route"]["kwargs"]["room_name"] + self.room_group_name = "blog_%s" % self.room_name + + # Se une a la sala + await self.channel_layer.group_add(self.room_group_name, self.channel_name) + + # Informa al cliente del éxito + await self.accept() + + def disconnect(self, close_code): + ''' Cliente se desconecta ''' + # Leave room group + await self.channel_layer.group_discard(self.room_group_name, self.channel_name) + + def receive(self, text_data): + ''' Cliente envía información y nosotros la recibimos ''' + text_data_json = json.loads(text_data) + name = text_data_json["name"] + text = text_data_json["text"] + + # Enviamos el mensaje a la sala + await self.channel_layer.group_send( + self.room_group_name, + { + "type": "chat_message", + "name": name, + "text": text + } + ) + + def chat_message(self, event): + ''' Recibimos información de la sala ''' + name = event["name"] + text = event["text"] + + # Send message to WebSocket + await self.send( + text_data=json.dumps( + { + "type": "chat_message", + "name": name, + "text": text + } + ) + ) diff --git a/apps/back/migrations/__init__.py b/apps/back/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/back/models.py b/apps/back/models.py new file mode 100644 index 0000000..71a8362 --- /dev/null +++ b/apps/back/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/apps/back/routing.py b/apps/back/routing.py new file mode 100644 index 0000000..949661e --- /dev/null +++ b/apps/back/routing.py @@ -0,0 +1,7 @@ +from django.urls import re_path + +from . import consumers + +websocket_urlpatterns = [ + re_path(r'ws/blog/(?P\w+)/$', consumers.BlogConsumer), +] diff --git a/apps/back/views.py b/apps/back/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/apps/back/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/apps/front/__init__.py b/apps/front/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/front/apps.py b/apps/front/apps.py new file mode 100644 index 0000000..3616320 --- /dev/null +++ b/apps/front/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class FrontConfig(AppConfig): + name = 'front' diff --git a/apps/front/templates/blog.html b/apps/front/templates/blog.html new file mode 100644 index 0000000..2c2273c --- /dev/null +++ b/apps/front/templates/blog.html @@ -0,0 +1,125 @@ + + + + + Chat + + + + +
+

Chat con Django

+
+ +
+ + +
+ + + +
+ + +
+ +
+
+
+ + + diff --git a/apps/front/views.py b/apps/front/views.py new file mode 100644 index 0000000..b19f6f5 --- /dev/null +++ b/apps/front/views.py @@ -0,0 +1,4 @@ +from django.shortcuts import render + +def blog(request): + return render(request, 'blog.html') diff --git a/asgi.py b/asgi.py new file mode 100644 index 0000000..872bba4 --- /dev/null +++ b/asgi.py @@ -0,0 +1,11 @@ +import os + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") +import django + +django.setup() + +from channels.routing import ProtocolTypeRouter + + +application = ProtocolTypeRouter({}) diff --git a/django-launcher.dev.sh b/django-launcher.dev.sh new file mode 100644 index 0000000..d328d64 --- /dev/null +++ b/django-launcher.dev.sh @@ -0,0 +1,14 @@ +#!/bin/sh + +# Collect static files +echo "Collect static files" +python3 manage.py collectstatic --noinput + +# Apply database migrations +echo "Apply database migrations" +python3 manage.py makemigrations +python3 manage.py migrate + +# Start server +echo "Starting server" +uvicorn --host 0.0.0.0 --port 8000 --reload chapps.asgi:application diff --git a/django-launcher.pro.sh b/django-launcher.pro.sh new file mode 100644 index 0000000..2623dff --- /dev/null +++ b/django-launcher.pro.sh @@ -0,0 +1,14 @@ +#!/bin/sh + +# Collect static files +echo "Collect static files" +python3 manage.py collectstatic --noinput + +# Apply database migrations +echo "Apply database migrations" +python3 manage.py makemigrations +python3 manage.py migrate + +# Start server +echo "Starting server" +uvicorn --host 0.0.0.0 --port 8000 chapps.asgi:application diff --git a/docker-compose.dev.yaml b/docker-compose.dev.yaml new file mode 100644 index 0000000..0fd9ce9 --- /dev/null +++ b/docker-compose.dev.yaml @@ -0,0 +1,62 @@ +version: '3.1' + +services: + + db: + image: postgres + restart: always + volumes: + - ./../postgres_data:/var/lib/postgresql/data + environment: + POSTGRES_DB: demo + POSTGRES_PASSWORD: postgres + expose: + - 5432 + + django: + build: + context: . + dockerfile: ./Dockerfiles/django/Dockerfile + restart: always + entrypoint: /django-launcher.dev.sh + volumes: + - .:/usr/src/app/ + environment: + DEBUG: "True" + ALLOWED_HOSTS: "localhost" + SECRET_KEY: "mysecret" + DB_HOST: db + DB_NAME: "demo" + DB_USER: "postgres" + DB_PASSWORD: "postgres" + DB_PORT: "5432" + DOMAIN: "localhost" + DOMAIN_URL: "http://localhost" + STATIC_URL: "/static/" + MEDIA_URL: "/media/" + expose: + - 8000 + depends_on: + - db + + redis: + image: redis:alpine + restart: always + expose: + - 6379 + depends_on: + - django + + + caddy: + image: caddy:alpine + restart: always + ports: + - 80:80 + - 443:443 + volumes: + - ./Caddyfile:/etc/caddy/Caddyfile + - ./../caddy_data:/data + - .:/usr/src/app/ + depends_on: + - django \ No newline at end of file diff --git a/docker-compose.pro.yaml b/docker-compose.pro.yaml new file mode 100644 index 0000000..0fc739a --- /dev/null +++ b/docker-compose.pro.yaml @@ -0,0 +1,66 @@ +version: '3.1' + +services: + + db: + image: postgres + restart: always + volumes: + - ./../postgres_data:/var/lib/postgresql/data + environment: + POSTGRES_DB: guitarlions + POSTGRES_PASSWORD: postgres + expose: + - 5432 + + django: + build: . + restart: always + entrypoint: /django-launcher.pro.sh + volumes: + - .:/usr/src/app/ + environment: + DEBUG: "False" + ALLOWED_HOSTS: "" + SECRET_KEY: "secret" + DB_HOST: db + DB_NAME: "guitarlions" + DB_USER: "postgres" + DB_PASSWORD: "postgres" + DB_PORT: "5432" + DOMAIN: "" + DOMAIN_URL: "https://" + STATIC_URL: "/static/" + MEDIA_URL: "/media/" + EMAIL_USE_TLS: True + EMAIL_HOST: "" + EMAIL_USE_TLS: "True" + EMAIL_PORT: "2525" + EMAIL_USER: "" + EMAIL_PASSWORD: "" + expose: + - 8000 + depends_on: + - db + + redis: + image: redis:alpine + restart: always + expose: + - 6379 + depends_on: + - django + + caddy: + image: caddy:alpine + restart: always + ports: + - 80:80 + - 443:443 + volumes: + - .:/usr/src/app/ + - ./Caddyfile:/etc/caddy/Caddyfile + - ./../caddy_data:/data + depends_on: + - django + diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..089ff59 --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/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', 'mi_web.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/mi_web/__init__.py b/mi_web/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/mi_web/asgi.py b/mi_web/asgi.py new file mode 100644 index 0000000..4141348 --- /dev/null +++ b/mi_web/asgi.py @@ -0,0 +1,18 @@ +import os + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mi_web.settings") +import django + +django.setup() + +from channels.auth import AuthMiddlewareStack +from channels.routing import ProtocolTypeRouter, URLRouter +from django.core.asgi import get_asgi_application +from apps.chat.routing import websocket_urlpatterns + + +application = ProtocolTypeRouter( + { + "websocket": AuthMiddlewareStack(URLRouter(websocket_urlpatterns)), + } +) diff --git a/mi_web/settings.py b/mi_web/settings.py new file mode 100644 index 0000000..aba53a8 --- /dev/null +++ b/mi_web/settings.py @@ -0,0 +1,134 @@ +""" +Django settings for mi_web project. + +Generated by 'django-admin startproject' using Django 3.1.3. + +For more information on this file, see +https://docs.djangoproject.com/en/3.1/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.1/ref/settings/ +""" +import os +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'pzcj^u^ktd7$9#pd196m+=#384=*%^il2r5po-)jutl^zpt%k0' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ["*"] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'channels', + 'apps.chat', + 'apps.front', +] + +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', +] + +ROOT_URLCONF = 'mi_web.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', + ], + }, + }, +] + + + +# Database +# https://docs.djangoproject.com/en/3.1/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': 'mydatabase', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/3.1/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = False + +USE_L10N = False + +USE_TZ = False + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/3.1/howto/static-files/ + +STATIC_URL = '/static/' + +ASGI_APPLICATION = "asgi.application" + +CHANNEL_LAYERS = { + "default": { + "BACKEND": "channels_redis.core.RedisChannelLayer", + "CONFIG": { + "hosts": [(os.environ.get("REDIS_URL", "127.0.0.1"), 6379)], + }, + }, +} + diff --git a/mi_web/urls.py b/mi_web/urls.py new file mode 100644 index 0000000..ebd09c8 --- /dev/null +++ b/mi_web/urls.py @@ -0,0 +1,23 @@ +"""mi_web URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/3.1/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 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 +from apps.front import views + +urlpatterns = [ + path('admin/', admin.site.urls), + path('', views.blog), +] diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e95b771 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,10 @@ +# Django +django +# Servidor para Django +daphne==2.4.1 +# Conector para PostgreSQL +psycopg2-binary +# Channels +channels==2.4.0 +# Conector de Redis para Channels +channels_redis \ No newline at end of file