Skip to content

Commit

Permalink
6-start-project-with-django-and-docker (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
srezal authored Mar 9, 2025
2 parents fde6f00 + 0263e53 commit e820f55
Show file tree
Hide file tree
Showing 12 changed files with 221 additions and 75 deletions.
4 changes: 0 additions & 4 deletions .env.example

This file was deleted.

18 changes: 7 additions & 11 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
FROM python:3.12-alpine

RUN addgroup --system gdwrapper && adduser --system --ingroup gdwrapper --disabled-password gdwrapper

USER gdwrapper

RUN cd ~ && mkdir app
FROM python:3.9-slim

WORKDIR /app
COPY . /app/

WORKDIR /app/backend

COPY requirements.txt .
RUN pip install --upgrade pip && pip install -r /app/requirements.txt

Check failure on line 8 in Dockerfile

View workflow job for this annotation

GitHub Actions / Проверка наличия тега 0.8 и работоспособности docker compose

DL3013 warning: Pin versions in pip. Instead of `pip install <package>` use `pip install <package>==<version>` or `pip install --requirement <requirements file>`

Check failure on line 8 in Dockerfile

View workflow job for this annotation

GitHub Actions / Проверка наличия тега 0.8 и работоспособности docker compose

DL3042 warning: Avoid use of cache directory with pip. Use `pip install --no-cache-dir <package>`

RUN pip3 install -r requirements.txt
EXPOSE 8000

COPY ./hello_world .
CMD ["sh", "-c", "python backend/manage.py migrate && python backend/manage.py runserver 0.0.0.0:8000"]

CMD [ "python3", "main.py" ]
Empty file added backend/backend/__init__.py
Empty file.
16 changes: 16 additions & 0 deletions backend/backend/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for backend project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')

application = get_asgi_application()
101 changes: 101 additions & 0 deletions backend/backend/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
"""
Django settings for backend project.
Generated by 'django-admin startproject' using Django 3.2.12.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
import urllib.parse
from pathlib import Path
from os.path import join as path_join
from dotenv import dotenv_values

BASE_DIR = Path(__file__).resolve().parent.parent

# Загружаем переменные окружения из файла .env (на уровне выше BASE_DIR)
config = dotenv_values(path_join(BASE_DIR.parent, ".env"))

SECRET_KEY = config.get("DJANGO_SECRET_KEY")
ALLOWED_HOSTS = ['localhost', '0.0.0.0']
DEBUG = True

# Получаем переменные подключения к MongoDB
DB_NAME = config.get("DB_NAME")
DB_USER = config.get("DB_USER")
DB_PASSWORD = config.get("DB_PASSWORD")
DATABASE_HOST = config.get("DATABASE_HOST", "mongodb")
DATABASE_PORT = config.get("DATABASE_PORT", "27017")

# Экранируем пароль для корректного формирования URI
DB_PASSWORD_ENCODED = urllib.parse.quote_plus(DB_PASSWORD)

# Формируем строку подключения к MongoDB с указанием authSource=admin
MONGO_URI = f"mongodb://{DB_USER}:{DB_PASSWORD_ENCODED}@{DATABASE_HOST}:{DATABASE_PORT}/{DB_NAME}?authSource=admin"

DATABASES = {
'default': {
'ENGINE': 'djongo',
'CLIENT': {
'host': MONGO_URI,
}
}
}

# Остальные настройки (INSTALLED_APPS, MIDDLEWARE, TEMPLATES, WSGI_APPLICATION и т.д.)
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

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 = 'backend.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',
],
},
},
]

WSGI_APPLICATION = 'backend.wsgi.application'

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',},
]

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

STATIC_URL = '/static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
21 changes: 21 additions & 0 deletions backend/backend/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""backend URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/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

urlpatterns = [
path('admin/', admin.site.urls),
]
16 changes: 16 additions & 0 deletions backend/backend/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for backend project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')

application = get_wsgi_application()
22 changes: 22 additions & 0 deletions backend/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python3
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.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()
55 changes: 29 additions & 26 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,33 +1,36 @@
version: '3.1'
version: '3.8'

services:

mongo:
image: mongo
restart: always
web:
build: .
container_name: django_app
command: python manage.py runserver 0.0.0.0:8000
env_file: .env
volumes:
- .:/app
ports:
- ${MONGO_DB_PORT}:${MONGO_DB_PORT}
- "8000:8000"
environment:
MONGO_INITDB_ROOT_USERNAME: ${MONGO_INITDB_ROOT_USERNAME}
MONGO_INITDB_ROOT_PASSWORD: ${MONGO_INITDB_ROOT_PASSWORD}
networks:
- gdwrapper_network

DJANGO_SECRET_KEY: ${DJANGO_SECRET_KEY}
DB_NAME: ${DB_NAME}
DB_USER: ${DB_USER}
DB_PASSWORD: ${DB_PASSWORD}
DATABASE_HOST: ${DATABASE_HOST}
DATABASE_PORT: ${DATABASE_PORT}

gdwrapper:
image: gdwrapepr
build: .
mongodb:
image: mongo:4.4
container_name: mongo_db
restart: always
env_file: .env
environment:
MONGO_INITDB_ROOT_USERNAME: ${MONGO_INITDB_ROOT_USERNAME}
MONGO_INITDB_ROOT_PASSWORD: ${MONGO_INITDB_ROOT_PASSWORD}
MONGO_DB_HOST: ${MONGO_DB_HOST}
MONGO_DB_PORT: ${MONGO_DB_PORT}
depends_on:
- mongo
networks:
- gdwrapper_network

MONGO_INITDB_ROOT_USERNAME: ${DB_USER}
MONGO_INITDB_ROOT_PASSWORD: ${DB_PASSWORD}
MONGO_INITDB_DATABASE: ${DB_NAME}
ports:
- "27017:27017"
volumes:
- mongo-data:/data/db

networks:
gdwrapper_network:
driver: bridge
volumes:
mongo-data:
6 changes: 6 additions & 0 deletions env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
DB_NAME=...
DB_USER=...
DB_PASSWORD=...
DJANGO_SECRET_KEY=...
DATABASE_HOST=...
DATABASE_PORT=...
34 changes: 0 additions & 34 deletions hello_world/main.py

This file was deleted.

3 changes: 3 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@ dnspython==2.7.0
dotenv==0.9.9
pymongo==4.11.1
python-dotenv==1.0.1
Django>=3.2
djongo==1.3.6
pytz==2023.3

0 comments on commit e820f55

Please sign in to comment.