├── backend
├── __init__.py
├── core
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── static
│ │ ├── js
│ │ │ └── main.js
│ │ └── css
│ │ │ └── main.css
│ ├── views.py
│ ├── apps.py
│ ├── urls.py
│ └── templates
│ │ ├── index.html
│ │ └── base.html
├── urls.py
├── asgi.py
├── wsgi.py
└── settings.py
├── requirements.txt
├── img
├── deploy_docker01.png
└── deploy_supervisor01.png
├── index.html
├── contrib
└── env_gen.py
├── .gitignore
└── README.md
/backend/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/backend/core/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/backend/core/migrations/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/backend/core/static/js/main.js:
--------------------------------------------------------------------------------
1 | console.log('Teste')
--------------------------------------------------------------------------------
/backend/core/static/css/main.css:
--------------------------------------------------------------------------------
1 | .title-blue {
2 | color: blue;
3 | }
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | Django==4.2.1
2 | django-extensions==3.2.1
3 | python-decouple==3.8
4 |
--------------------------------------------------------------------------------
/img/deploy_docker01.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rg3915/django-deploy/main/img/deploy_docker01.png
--------------------------------------------------------------------------------
/img/deploy_supervisor01.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rg3915/django-deploy/main/img/deploy_supervisor01.png
--------------------------------------------------------------------------------
/backend/core/views.py:
--------------------------------------------------------------------------------
1 | from django.shortcuts import render
2 |
3 |
4 | def index(request):
5 | template_name = 'index.html'
6 | return render(request, template_name)
7 |
--------------------------------------------------------------------------------
/backend/core/apps.py:
--------------------------------------------------------------------------------
1 | from django.apps import AppConfig
2 |
3 |
4 | class CoreConfig(AppConfig):
5 | default_auto_field = 'django.db.models.BigAutoField'
6 | name = 'backend.core'
7 |
--------------------------------------------------------------------------------
/backend/core/urls.py:
--------------------------------------------------------------------------------
1 | from django.urls import path
2 |
3 | from backend.core import views as v
4 |
5 |
6 | app_name = 'core'
7 |
8 |
9 | urlpatterns = [
10 | path('', v.index, name='index'),
11 | ]
12 |
--------------------------------------------------------------------------------
/backend/urls.py:
--------------------------------------------------------------------------------
1 | from django.contrib import admin
2 | from django.urls import include, path
3 |
4 | urlpatterns = [
5 | path('', include('backend.core.urls', namespace='core')),
6 | path('admin/', admin.site.urls),
7 | ]
8 |
--------------------------------------------------------------------------------
/backend/asgi.py:
--------------------------------------------------------------------------------
1 | """
2 | ASGI config for backend project.
3 |
4 | It exposes the ASGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.asgi import get_asgi_application
13 |
14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
15 |
16 | application = get_asgi_application()
17 |
--------------------------------------------------------------------------------
/backend/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for backend project.
3 |
4 | It exposes the WSGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.wsgi import get_wsgi_application
13 |
14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/backend/core/templates/index.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 |
3 | {% block content %}
4 |
Django
5 | Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
6 | tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
7 | quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
8 | consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
9 | cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
10 | proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
11 | {% endblock content %}
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | Document
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 | Django
19 |
20 |
--------------------------------------------------------------------------------
/backend/core/templates/base.html:
--------------------------------------------------------------------------------
1 | {% load static %}
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | Django
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 | {% block content %}{% endblock content %}
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/contrib/env_gen.py:
--------------------------------------------------------------------------------
1 | """
2 | Python SECRET_KEY generator.
3 | """
4 | import random
5 |
6 | chars = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!?@#$%^&*()"
7 | size = 50
8 | secret_key = "".join(random.sample(chars, size))
9 |
10 | chars = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!?@#$%_"
11 | size = 20
12 | password = "".join(random.sample(chars, size))
13 |
14 | CONFIG_STRING = """
15 | DEBUG=True
16 | SECRET_KEY=%s
17 | ALLOWED_HOSTS=127.0.0.1,.localhost,0.0.0.0
18 |
19 | #DATABASE_URL=postgres://USER:PASSWORD@HOST:PORT/NAME
20 | #POSTGRES_DB=
21 | #POSTGRES_USER=
22 | #POSTGRES_PASSWORD=%s
23 | #DB_HOST=localhost
24 |
25 | #DEFAULT_FROM_EMAIL=
26 | #EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend
27 | #EMAIL_HOST=localhost
28 | #EMAIL_PORT=
29 | #EMAIL_HOST_USER=
30 | #EMAIL_HOST_PASSWORD=
31 | #EMAIL_USE_TLS=True
32 | """.strip() % (secret_key, password)
33 |
34 | # Writing our configuration file to '.env'
35 | with open('.env', 'w') as configfile:
36 | configfile.write(CONFIG_STRING)
37 |
38 | print('Success!')
39 | print('Type: cat .env')
40 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
131 | .DS_Store
132 |
133 | media/
134 | staticfiles/
135 | .idea
136 | .ipynb_checkpoints/
137 | .vscode
138 | *.cast
139 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # django-deploy
2 |
3 | Estudo sobre como fazer o deploy de uma app Django.
4 |
5 | ## Servidor local do Python
6 |
7 | No Python nós temos um servidor bem simples onde podemos rodar uma página web na porta local.
8 |
9 | ```
10 | python -m http.server
11 | ```
12 |
13 | Ele vai renderizar o arquivo `index.html` em localhost:8000
14 |
15 |
16 | ## Servidor local do Django
17 |
18 | No Django também temos um servidor local.
19 |
20 | ```
21 | python manage.py runserver
22 | ```
23 |
24 |
25 | ## Deploy em produção
26 |
27 | A seguir temos um esboço do que podemos usar para fazer o nosso deploy em produção.
28 |
29 | 
30 |
31 | 
32 |
33 |
34 | ## Servidor de aplicação
35 |
36 | ### [Gunicorn](https://gunicorn.org/)
37 |
38 |
39 | ## Proxy Reverso
40 |
41 | https://www.nginx.com/
42 |
43 | https://traefik.io/traefik/
44 |
45 |
46 | ## PaaS
47 |
48 | * [fly.io](https://fly.io/)
49 | * [render.com](https://render.com/)
50 | * [vercel](https://vercel.com/)
51 | * [pythonanywhere](https://www.pythonanywhere.com/)
52 | * [railway.app](https://railway.app/)
53 | * [huggingface.co](https://huggingface.co/)
54 | * [AWS Elastic Beanstalk](https://aws.amazon.com/pt/elasticbeanstalk/)
55 |
56 |
57 |
58 | ## Serviços Externos
59 |
60 | ### [pusher.com](https://pusher.com/)
61 |
62 | É um serviço de mensageria Pub/Sub. Ele notifica em tempo real todos os inscritos num canal pré-definido.
63 |
64 | #### Exemplos de uso:
65 |
66 | * chat
67 | * notificação, exemplo TV que informa a senha do próximo cliente a ser atendido
68 |
69 |
70 | ### [Nginx Proxy Manager](https://nginxproxymanager.com/)
71 |
72 | Expõe os serviços da aplicação de uma forma fácil e segura.
73 |
74 |
75 |
76 | ## Serviços interessantes com Docker
77 |
78 | ### [Portainer](https://www.portainer.io/)
79 |
80 | É um gerenciador de containers com interface web.
81 |
82 | ```
83 | # Portainer
84 | docker run -d \
85 | --name myportainer \
86 | -p 9000:9000 \
87 | --restart always \
88 | -v /var/run/docker.sock:/var/run/docker.sock \
89 | -v /opt/portainer:/data \
90 | portainer/portainer
91 | ```
92 |
93 | ### [Mailhog](https://github.com/mailhog/MailHog)
94 |
95 | É um serviço de e-mail para testes locais.
96 |
97 | ```
98 | # docker-compose.yml
99 | mailhog:
100 | container_name: dicas_de_django_mailhog
101 | image: mailhog/mailhog
102 | restart: always
103 | logging:
104 | driver: 'none'
105 | ports:
106 | - 1025:1025
107 | - 8025:8025
108 | networks:
109 | - dicas-de-django-network
110 | ```
111 |
112 |
113 | ### [pgAdmin](https://www.pgadmin.org/download/)
114 |
115 | É um serviço que serve para gerenciar os bancos de dados em PostgreSQL.
116 |
117 | ```
118 | # docker-compose.yml
119 | pgadmin:
120 | container_name: dicas_de_django_pgadmin
121 | image: dpage/pgadmin4
122 | restart: unless-stopped
123 | volumes:
124 | - pgadmin:/var/lib/pgadmin
125 | environment:
126 | PGADMIN_DEFAULT_EMAIL: admin@admin.com
127 | PGADMIN_DEFAULT_PASSWORD: admin
128 | PGADMIN_CONFIG_SERVER_MODE: 'False'
129 | ports:
130 | - 5051:80
131 | networks:
132 | - dicas-de-django-network
133 | ```
134 |
135 |
136 | ### [Celery](https://docs.celeryq.dev/en/latest/)
137 |
138 | É um sistema de gerenciamento de filas de tarefas assíncrona.
139 |
140 |
--------------------------------------------------------------------------------
/backend/settings.py:
--------------------------------------------------------------------------------
1 | """
2 | Django settings for backend project.
3 |
4 | Generated by 'django-admin startproject' using Django 4.2.1.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/4.2/topics/settings/
8 |
9 | For the full list of settings and their values, see
10 | https://docs.djangoproject.com/en/4.2/ref/settings/
11 | """
12 | from pathlib import Path
13 |
14 | from decouple import config, Csv
15 |
16 |
17 | BASE_DIR = Path(__file__).resolve().parent.parent
18 |
19 | # SECURITY WARNING: keep the secret key used in production secret!
20 | SECRET_KEY = config('SECRET_KEY')
21 |
22 | # SECURITY WARNING: don't run with debug turned on in production!
23 | DEBUG = config('DEBUG', default=False, cast=bool)
24 |
25 | ALLOWED_HOSTS = config('ALLOWED_HOSTS', default=[], cast=Csv())
26 |
27 |
28 | # Application definition
29 |
30 | INSTALLED_APPS = [
31 | 'django.contrib.admin',
32 | 'django.contrib.auth',
33 | 'django.contrib.contenttypes',
34 | 'django.contrib.sessions',
35 | 'django.contrib.messages',
36 | 'django.contrib.staticfiles',
37 | 'django_extensions',
38 | 'backend.core',
39 | ]
40 |
41 | MIDDLEWARE = [
42 | 'django.middleware.security.SecurityMiddleware',
43 | 'django.contrib.sessions.middleware.SessionMiddleware',
44 | 'django.middleware.common.CommonMiddleware',
45 | 'django.middleware.csrf.CsrfViewMiddleware',
46 | 'django.contrib.auth.middleware.AuthenticationMiddleware',
47 | 'django.contrib.messages.middleware.MessageMiddleware',
48 | 'django.middleware.clickjacking.XFrameOptionsMiddleware',
49 | ]
50 |
51 | ROOT_URLCONF = 'backend.urls'
52 |
53 | TEMPLATES = [
54 | {
55 | 'BACKEND': 'django.template.backends.django.DjangoTemplates',
56 | 'DIRS': [],
57 | 'APP_DIRS': True,
58 | 'OPTIONS': {
59 | 'context_processors': [
60 | 'django.template.context_processors.debug',
61 | 'django.template.context_processors.request',
62 | 'django.contrib.auth.context_processors.auth',
63 | 'django.contrib.messages.context_processors.messages',
64 | ],
65 | },
66 | },
67 | ]
68 |
69 | WSGI_APPLICATION = 'backend.wsgi.application'
70 |
71 |
72 | # Database
73 | # https://docs.djangoproject.com/en/4.2/ref/settings/#databases
74 |
75 | DATABASES = {
76 | 'default': {
77 | 'ENGINE': 'django.db.backends.sqlite3',
78 | 'NAME': BASE_DIR / 'db.sqlite3',
79 | }
80 | }
81 |
82 |
83 | # Password validation
84 | # https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
85 |
86 | AUTH_PASSWORD_VALIDATORS = [
87 | {
88 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
89 | },
90 | {
91 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
92 | },
93 | {
94 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
95 | },
96 | {
97 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
98 | },
99 | ]
100 |
101 |
102 | # Internationalization
103 | # https://docs.djangoproject.com/en/4.2/topics/i18n/
104 |
105 | LANGUAGE_CODE = 'pt-br'
106 |
107 | TIME_ZONE = 'America/Sao_Paulo'
108 |
109 | USE_I18N = True
110 |
111 | USE_TZ = True
112 |
113 |
114 | # Static files (CSS, JavaScript, Images)
115 | # https://docs.djangoproject.com/en/4.2/howto/static-files/
116 |
117 | STATIC_URL = 'static/'
118 | STATIC_ROOT = BASE_DIR.joinpath('staticfiles')
119 |
120 | # Default primary key field type
121 | # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
122 |
123 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
124 |
--------------------------------------------------------------------------------