Initial commit

This commit is contained in:
Pablo Moreno
2024-03-21 23:17:58 +01:00
committed by GitHub
commit a13eb6c9d9
25 changed files with 612 additions and 0 deletions
+162
View File
@@ -0,0 +1,162 @@
# Created by https://www.toptal.com/developers/gitignore/api/django
# Edit at https://www.toptal.com/developers/gitignore?templates=django
### Django ###
*.log
*.pot
*.pyc
__pycache__/
local_settings.py
db.sqlite3
db.sqlite3-journal
media
# If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/
# in your Git repository. Update and uncomment the following line accordingly.
# <django-project-name>/staticfiles/
### Django.Python Stack ###
# Byte-compiled / optimized / DLL files
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
# Django stuff:
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
poetry.lock
.idea/
data/
.vscode/
static/
# End of https://www.toptal.com/developers/gitignore/api/django
+20
View File
@@ -0,0 +1,20 @@
FROM python:3.11-slim-buster
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
COPY . /code
RUN apt-get update && \
apt-get install -y gcc vim postgresql-client nginx && \
apt-get remove --purge --auto-remove -y
COPY nginx/nginx.conf /etc/nginx/sites-enabled/default
RUN pip install -r requirements.txt && \
python manage.py collectstatic --noinput
CMD [ "bash", "./scripts/run.sh" ]
+11
View File
@@ -0,0 +1,11 @@
# Django Template
## How to use the template?
Just run this, changing the project name:
```bash
django-admin startproject --template=https://github.com/pablo-moreno/django-template/archive/refs/heads/main.zip <project name>
```
- Django's extensions already installed (such as the beautiful shell plus)
View File
View File
View File
+10
View File
@@ -0,0 +1,10 @@
from django.urls import path, include
from drf_spectacular.views import SpectacularSwaggerView, SpectacularRedocView
from config.api.v1.views import APISchema
urlpatterns = [
path("schema/", APISchema.as_view(), name="schema"),
path("swagger/", SpectacularSwaggerView.as_view(url_name="schema"), name="swagger-ui"),
path("redoc/", SpectacularRedocView.as_view(url_name="schema"), name="redoc"),
]
+6
View File
@@ -0,0 +1,6 @@
from drf_spectacular.views import SpectacularAPIView
class APISchema(SpectacularAPIView):
api_version = "v1"
+7
View File
@@ -0,0 +1,7 @@
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production")
application = get_asgi_application()
+16
View File
@@ -0,0 +1,16 @@
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.base")
app = Celery("config")
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object("django.conf:settings", namespace="CELERY")
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
+1
View File
@@ -0,0 +1 @@
from config.settings.base import *
+178
View File
@@ -0,0 +1,178 @@
import datetime
from config.settings.environ import * # noqa
APP_NAME = 'template'
DESCRIPTION = ''
VERSION = '0.1.0'
DJANGO_APPS = [
"unfold", # before django.contrib.admin
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
# 'django.contrib.gis', -- Requires gdal-bin
]
THIRD_PARTY_APPS = [
"corsheaders",
"django_extensions",
"django_filters",
"watchman",
"drf_spectacular",
]
PROJECT_APPS = [
]
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + PROJECT_APPS
PROJECT_MIDDLEWARE = []
DJANGO_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",
]
MIDDLEWARE = DJANGO_MIDDLEWARE + PROJECT_MIDDLEWARE
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",
],
},
},
]
WSGI_APPLICATION = "config.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
"default": DATABASE_URL,
}
# Password validation
# https://docs.djangoproject.com/en/4.2/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/4.2/topics/i18n/
LANGUAGE_CODE = "es-es"
TIME_ZONE = "Europe/Madrid"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = "/static/"
STATIC_ROOT = BASE_DIR / "static"
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"
STORAGES = {
"default": {
"BACKEND": "django.core.files.storage.FileSystemStorage",
},
"staticfiles": {
"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage",
},
}
# Django Rest Framework Configuration
REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",),
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTAuthentication",
"rest_framework.authentication.SessionAuthentication",
"rest_framework.authentication.BasicAuthentication",
),
"DEFAULT_RENDERER_CLASSES": ("rest_framework.renderers.JSONRenderer",),
"DEFAULT_FILTER_BACKENDS": [
"rest_framework.filters.OrderingFilter",
"django_filters.rest_framework.DjangoFilterBackend",
"rest_framework.filters.SearchFilter",
],
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
"PAGE_SIZE": PAGE_SIZE,
}
JWT_AUTH = {
"JWT_SECRET_KEY": SECRET_KEY,
"JWT_VERIFY": True,
"JWT_VERIFY_EXPIRATION": True,
"JWT_EXPIRATION_DELTA": datetime.timedelta(days=7),
"JWT_ALLOW_REFRESH": True,
"JWT_REFRESH_EXPIRATION_DELTA": datetime.timedelta(days=7),
"JWT_AUTH_HEADER_PREFIX": "JWT",
"JWT_AUTH_COOKIE": "jwt",
}
LOCALE_PATHS = [
BASE_DIR / "locale",
]
if S3_ENABLED:
STORAGES["default"] = {
"BACKEND": "storages.backends.s3boto3.S3Boto3Storage",
}
WATCHMAN_STORAGE_PATH = "tmp"
SPECTACULAR_SETTINGS = {
"TITLE": APP_NAME,
"DESCRIPTION": DESCRIPTION,
"VERSION": VERSION,
"SERVE_INCLUDE_SCHEMA": False,
}
CELERY_BROKER_URL = env.str("CELERY_BROKER_URL", default="redis://172.17.0.1:6379/0")
CELERY_TIME_ZONE = TIME_ZONE
CELERY_ALWAYS_EAGER = DEBUG
+4
View File
@@ -0,0 +1,4 @@
from .base import *
DEBUG = True
ALLOWED_HOSTS = ["*"]
+34
View File
@@ -0,0 +1,34 @@
import os
import environ
from pathlib import Path
BASE_DIR = Path(".")
env = environ.Env()
env_file = BASE_DIR / ".env"
if os.path.exists(env_file):
environ.Env.read_env(env_file)
SECRET_KEY = env.str("SECRET_KEY", "this-is-the-default-secret-key")
DEBUG = env.bool("DEBUG", True)
DATABASE_URL = env.db_url("DATABASE_URL", "sqlite:///db.sqlite3")
STATIC_ROOT = env.str("STATIC_ROOT", "static")
MEDIA_ROOT = env.str("MEDIA_ROOT", "media")
REDIS_HOST = env.str("REDIS_HOST", "redis")
REDIS_PORT = env.str("REDIS_PORT", 6379)
PAGE_SIZE = env.int("PAGE_SIZE", 20)
ALLOWED_HOSTS = env.str("ALLOWED_HOSTS", "*").split(",")
S3_ENABLED = env.bool("S3_ENABLED", False)
AWS_S3_HOST = env.str("S3_HOST", "")
AWS_ACCESS_KEY_ID = env.str("S3_ACCESS_KEY_ID", "")
AWS_SECRET_ACCESS_KEY = env.str("S3_SECRET_ACCESS_KEY", "")
AWS_STORAGE_BUCKET_NAME = env.str("S3_STORAGE_BUCKET_NAME", "")
AWS_S3_ENDPOINT_URL = env.str("S3_ENDPOINT_URL", "")
+1
View File
@@ -0,0 +1 @@
from .base import *
View File
+6
View File
@@ -0,0 +1,6 @@
from rest_framework.test import APITestCase
class TestItWorks(APITestCase):
def test_it_works(self):
assert 1 == 1
+9
View File
@@ -0,0 +1,9 @@
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
path("api/v1/", include("config.api.v1.urls")),
path("watchman", include("watchman.urls")),
]
+7
View File
@@ -0,0 +1,7 @@
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production")
application = get_wsgi_application()
+36
View File
@@ -0,0 +1,36 @@
version: "3"
services:
postgres:
image: postgres:14.1
environment:
POSTGRES_USER: admin
POSTGRES_PASSWORD: development
POSTGRES_DB: default
volumes:
- "./data:/var/lib/postgres/data"
minio:
image: bitnami/minio:latest
ports:
- "9001:9000"
- "9002:9001"
environment:
MINIO_ROOT_USER: admin
MINIO_ROOT_PASSWORD: admin
volumes:
- "./storage:/data"
django:
build: .
ports:
- "8000:8000"
volumes:
- .:/code
environment:
DATABASE_URL: "postgres://admin:development@postgres:5432/default"
links:
- postgres
- minio
depends_on:
- postgres
- minio
Executable
+22
View File
@@ -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", "config.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()
+38
View File
@@ -0,0 +1,38 @@
server {
listen 80;
# Static files
location /static {
alias /code/static;
}
# Reverse proxy
location / {
proxy_pass http://127.0.0.1:8000;
}
# security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
# gzip
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml application/json application/javascript application/xml+rss application/atom+xml image/svg+xml;
# Proxy
proxy_cache_bypass $http_upgrade;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
}
+4
View File
@@ -0,0 +1,4 @@
-r requirements.txt
pytest==7.3.0
coverage==7.2.3
pytest-cov==4.0.0
+19
View File
@@ -0,0 +1,19 @@
celery==5.2.7
django==5.0.1
django-cors-headers==3.13.0
django-extensions==3.2.0
django-filter==23.1
django-environ==0.10.0
django-watchman==1.3.0
django-storages==1.13.2
django-unfold==0.12.0
dj-database-url==1.0.0
djangorestframework-simplejwt==5.3.0
drf-spectacular==0.26.1
ipython==8.16.1
Pillow==10.0.1
psycopg2-binary==2.9.5
redis==4.5.4
requests==2.31.0
uvicorn==0.21.1
xmltodict==0.13.0
+21
View File
@@ -0,0 +1,21 @@
#!/bin/bash
ASGI_HOST=${WSGI_HOST:="0.0.0.0"}
ASGI_PORT=8000
ASGI_WORKERS=${WSGI_WORKERS:=1}
WORKER_NUM_PROCESSES=${WORKER_NUM_PROCESSES:=1}
RUN_SERVER=${RUN_SERVER:="FALSE"}
RUN_CELERY=${RUN_CELERY:="FALSE"}
if [ $RUN_SERVER = "TRUE" ]; then
service nginx restart
uvicorn --workers $ASGI_WORKERS --host $ASGI_HOST --port $ASGI_PORT config.asgi:application
elif [ $RUN_CELERY = "TRUE" ]; then
service nginx stop
celery -A config worker
else
echo "You have to set RUN_CELERY or RUN_SERVER to TRUE"
echo "Exiting"
fi