inicia o projeto com traefik e uvicorn

This commit is contained in:
2025-06-18 10:13:22 -04:00
commit 1e018e7b07
104 changed files with 4233 additions and 0 deletions

View File

@ -0,0 +1,20 @@
#
# .bashrc.override.sh
#
# persistent bash history
HISTFILE=~/.bash_history
PROMPT_COMMAND="history -a; $PROMPT_COMMAND"
# set some django env vars
source /entrypoint
# restore default shell options
set +o errexit
set +o pipefail
set +o nounset
# start ssh-agent
# https://code.visualstudio.com/docs/remote/troubleshooting
eval "$(ssh-agent -s)"

View File

@ -0,0 +1,36 @@
// For format details, see https://containers.dev/implementors/json_reference/
{
"name": "diarios_oficiais_search_alems_dev",
"dockerComposeFile": [
"../docker-compose.local.yml"
],
"init": true,
"mounts": [
{
"source": "./.devcontainer/bash_history",
"target": "/home/dev-user/.bash_history",
"type": "bind"
},
{
"source": "~/.ssh",
"target": "/home/dev-user/.ssh",
"type": "bind"
}
],
// Tells devcontainer.json supporting services / tools whether they should run
// /bin/sh -c "while sleep 1000; do :; done" when starting the container instead of the containers default command
"overrideCommand": false,
"service": "django",
// "remoteEnv": {"PATH": "/home/dev-user/.local/bin:${containerEnv:PATH}"},
"remoteUser": "dev-user",
"workspaceFolder": "/app",
// Set *default* container specific settings.json values on container create.
"customizations": {
},
// Uncomment the next line if you want start specific services in your Docker Compose config.
// "runServices": [],
// Uncomment the next line if you want to keep your containers running after VS Code shuts down.
// "shutdownAction": "none",
// Uncomment the next line to run commands after the container is created.
"postCreateCommand": "cat .devcontainer/bashrc.override.sh >> ~/.bashrc"
}

12
.dockerignore Normal file
View File

@ -0,0 +1,12 @@
.editorconfig
.gitattributes
.github
.gitignore
.gitlab-ci.yml
.idea
.pre-commit-config.yaml
.readthedocs.yml
.travis.yml
venv
.git
.envs/

27
.editorconfig Normal file
View File

@ -0,0 +1,27 @@
# http://editorconfig.org
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.{py,rst,ini}]
indent_style = space
indent_size = 4
[*.{html,css,scss,json,yml,xml,toml}]
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = false
[Makefile]
indent_style = tab
[default.conf]
indent_style = space
indent_size = 2

1
.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
* text=auto

278
.gitignore vendored Normal file
View File

@ -0,0 +1,278 @@
### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# 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/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
staticfiles/
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Environments
.venv
venv/
ENV/
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
### Node template
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Typescript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
### Linux template
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### VisualStudioCode template
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for devcontainer
.devcontainer/bash_history
### Windows template
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
### macOS template
# General
*.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### SublimeText template
# Cache files for Sublime Text
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache
# Workspace files are user-specific
*.sublime-workspace
# Project files should be checked into the repository, unless a significant
# proportion of contributors will probably not be using Sublime Text
# *.sublime-project
# SFTP configuration file
sftp-config.json
# Package control specific files
Package Control.last-run
Package Control.ca-list
Package Control.ca-bundle
Package Control.system-ca-bundle
Package Control.cache/
Package Control.ca-certs/
Package Control.merged-ca-bundle
Package Control.user-ca-bundle
oscrypto-ca-bundle.crt
bh_unicode_properties.cache
# Sublime-github package stores a github token in this file
# https://packagecontrol.io/packages/sublime-github
GitHub.sublime-settings
### Vim template
# Swap
[._]*.s[a-v][a-z]
[._]*.sw[a-p]
[._]s[a-v][a-z]
[._]sw[a-p]
# Session
Session.vim
# Temporary
.netrwhist
# Auto-generated tag files
tags
# Redis dump file
dump.rdb
### Project template
diarios_oficiais_search_alems/media/
.pytest_cache/
.ipython/
.env
.envs/
.envs/*
!.envs/.production/

50
.pre-commit-config.yaml Normal file
View File

@ -0,0 +1,50 @@
exclude: '^docs/|/migrations/|devcontainer.json'
default_stages: [pre-commit]
minimum_pre_commit_version: "3.2.0"
default_language_version:
python: python3.12
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-json
- id: check-toml
- id: check-xml
- id: check-yaml
- id: debug-statements
- id: check-builtin-literals
- id: check-case-conflict
- id: check-docstring-first
- id: detect-private-key
- repo: https://github.com/adamchainz/django-upgrade
rev: '1.25.0'
hooks:
- id: django-upgrade
args: ['--target-version', '5.0']
# Run the Ruff linter.
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.11.13
hooks:
# Linter
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
# Formatter
- id: ruff-format
- repo: https://github.com/Riverside-Healthcare/djLint
rev: v1.36.4
hooks:
- id: djlint-reformat-django
- id: djlint-django
# sets up .pre-commit-ci.yaml to ensure pre-commit dependencies stay up to date
ci:
autoupdate_schedule: weekly
skip: []
submodules: false

1
.python-version Normal file
View File

@ -0,0 +1 @@
3.12

52
README.md Normal file
View File

@ -0,0 +1,52 @@
# Diarios Oficiais Search ALEMS
Busca textual nos diários oficiais
[![Built with Cookiecutter Django](https://img.shields.io/badge/built%20with-Cookiecutter%20Django-ff69b4.svg?logo=cookiecutter)](https://github.com/cookiecutter/cookiecutter-django/)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
## Settings
Moved to [settings](https://cookiecutter-django.readthedocs.io/en/latest/1-getting-started/settings.html).
## Basic Commands
### Setting Up Your Users
- To create a **normal user account**, just go to Sign Up and fill out the form. Once you submit it, you'll see a "Verify Your E-mail Address" page. Go to your console to see a simulated email verification message. Copy the link into your browser. Now the user's email should be verified and ready to go.
- To create a **superuser account**, use this command:
$ python manage.py createsuperuser
For convenience, you can keep your normal user logged in on Chrome and your superuser logged in on Firefox (or similar), so that you can see how the site behaves for both kinds of users.
### Type checks
Running type checks with mypy:
$ mypy diarios_oficiais_search_alems
### Test coverage
To run the tests, check your test coverage, and generate an HTML coverage report:
$ coverage run -m pytest
$ coverage html
$ open htmlcov/index.html
#### Running tests with pytest
$ pytest
### Live reloading and Sass CSS compilation
Moved to [Live reloading and SASS compilation](https://cookiecutter-django.readthedocs.io/en/latest/2-local-development/developing-locally.html#using-webpack-or-gulp).
## Deployment
The following details how to deploy this application.
### Docker
See detailed [cookiecutter-django Docker documentation](https://cookiecutter-django.readthedocs.io/en/latest/3-deployment/deployment-with-docker.html).

View File

@ -0,0 +1,80 @@
# define an alias for the specific python version used in this file.
FROM docker.io/python:3.12.11-slim-bookworm AS python
# Python build stage
FROM python AS python-build-stage
ARG BUILD_ENVIRONMENT=local
# Install apt packages
RUN apt-get update && apt-get install --no-install-recommends -y \
# dependencies for building Python packages
build-essential \
# psycopg dependencies
libpq-dev
# Requirements are installed here to ensure they will be cached.
COPY ./requirements .
# Create Python Dependency and Sub-Dependency Wheels.
RUN pip wheel --wheel-dir /usr/src/app/wheels \
-r ${BUILD_ENVIRONMENT}.txt
# Python 'run' stage
FROM python AS python-run-stage
ARG BUILD_ENVIRONMENT=local
ARG APP_HOME=/app
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
ENV BUILD_ENV=${BUILD_ENVIRONMENT}
WORKDIR ${APP_HOME}
# devcontainer dependencies and utils
RUN apt-get update && apt-get install --no-install-recommends -y \
sudo git bash-completion nano ssh
# Create devcontainer user and add it to sudoers
RUN groupadd --gid 1000 dev-user \
&& useradd --uid 1000 --gid dev-user --shell /bin/bash --create-home dev-user \
&& echo dev-user ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/dev-user \
&& chmod 0440 /etc/sudoers.d/dev-user
# Install required system dependencies
RUN apt-get update && apt-get install --no-install-recommends -y \
# psycopg dependencies
libpq-dev \
wait-for-it \
# Translations dependencies
gettext \
# cleaning up unused files
&& apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \
&& rm -rf /var/lib/apt/lists/*
# All absolute dir copies ignore workdir instruction. All relative dir copies are wrt to the workdir instruction
# copy python dependency wheels from python-build-stage
COPY --from=python-build-stage /usr/src/app/wheels /wheels/
# use wheels to install python dependencies
RUN pip install --no-cache-dir --no-index --find-links=/wheels/ /wheels/* \
&& rm -rf /wheels/
COPY ./compose/production/django/entrypoint /entrypoint
RUN sed -i 's/\r$//g' /entrypoint
RUN chmod +x /entrypoint
COPY ./compose/local/django/start /start
RUN sed -i 's/\r$//g' /start
RUN chmod +x /start
# copy application code to WORKDIR
COPY . ${APP_HOME}
ENTRYPOINT ["/entrypoint"]

View File

@ -0,0 +1,16 @@
#!/bin/bash
set -o errexit
set -o pipefail
set -o nounset
# Garanta que os diretórios existam
mkdir -p /app/staticfiles
mkdir -p /app/media
python /app/manage.py collectstatic --noinput --clear
python /app/manage.py compress --force
python /app/manage.py migrate
exec uvicorn config.asgi:application --host 0.0.0.0 --port 8000 --reload
# exec python manage.py runserver 0.0.0.0:8000

View File

@ -0,0 +1,62 @@
# define an alias for the specific python version used in this file.
FROM docker.io/python:3.12.11-slim-bookworm AS python
# Python build stage
FROM python AS python-build-stage
ENV PYTHONDONTWRITEBYTECODE=1
RUN apt-get update && apt-get install --no-install-recommends -y \
# dependencies for building Python packages
build-essential \
# psycopg dependencies
libpq-dev \
# cleaning up unused files
&& apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \
&& rm -rf /var/lib/apt/lists/*
# Requirements are installed here to ensure they will be cached.
COPY ./requirements /requirements
# create python dependency wheels
RUN pip wheel --no-cache-dir --wheel-dir /usr/src/app/wheels \
-r /requirements/local.txt -r /requirements/production.txt \
&& rm -rf /requirements
# Python 'run' stage
FROM python AS python-run-stage
ARG BUILD_ENVIRONMENT
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
RUN apt-get update && apt-get install --no-install-recommends -y \
# To run the Makefile
make \
# psycopg dependencies
libpq-dev \
# Translations dependencies
gettext \
# Uncomment below lines to enable Sphinx output to latex and pdf
# texlive-latex-recommended \
# texlive-fonts-recommended \
# texlive-latex-extra \
# latexmk \
# cleaning up unused files
&& apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \
&& rm -rf /var/lib/apt/lists/*
# copy python dependency wheels from python-build-stage
COPY --from=python-build-stage /usr/src/app/wheels /wheels
# use wheels to install python dependencies
RUN pip install --no-cache /wheels/* \
&& rm -rf /wheels
COPY ./compose/local/docs/start /start-docs
RUN sed -i 's/\r$//g' /start-docs
RUN chmod +x /start-docs
WORKDIR /docs

7
compose/local/docs/start Normal file
View File

@ -0,0 +1,7 @@
#!/bin/bash
set -o errexit
set -o pipefail
set -o nounset
exec make livehtml

View File

@ -0,0 +1,28 @@
upstream django {
server django:8000 resolve;
zone django_upstream 64k;
}
server {
listen 80;
server_name localhost;
resolver 0.0.0.0 valid=30s;
location / {
# No need for resolver here anymore
set $backend http://django;
proxy_pass $backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /static/ {
alias /app/staticfiles/;
}
location /media/ {
alias /app/media/;
}
}

View File

@ -0,0 +1,87 @@
# define an alias for the specific python version used in this file.
FROM docker.io/python:3.12.11-slim-bookworm AS python
# Python build stage
FROM python AS python-build-stage
ARG BUILD_ENVIRONMENT=production
# Install apt packages
RUN apt-get update && apt-get install --no-install-recommends -y \
# dependencies for building Python packages
build-essential \
# psycopg dependencies
libpq-dev
# Requirements are installed here to ensure they will be cached.
COPY ./requirements .
# Create Python Dependency and Sub-Dependency Wheels.
RUN pip wheel --wheel-dir /usr/src/app/wheels \
-r ${BUILD_ENVIRONMENT}.txt
# Python 'run' stage
FROM python AS python-run-stage
ARG BUILD_ENVIRONMENT=production
ARG APP_HOME=/app
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
ENV BUILD_ENV=${BUILD_ENVIRONMENT}
WORKDIR ${APP_HOME}
RUN addgroup --system django \
&& adduser --system --ingroup django django
# Install required system dependencies
RUN apt-get update && apt-get install --no-install-recommends -y \
# psycopg dependencies
libpq-dev \
# Translations dependencies
gettext \
# entrypoint
wait-for-it \
# cleaning up unused files
&& apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \
&& rm -rf /var/lib/apt/lists/*
# All absolute dir copies ignore workdir instruction. All relative dir copies are wrt to the workdir instruction
# copy python dependency wheels from python-build-stage
COPY --from=python-build-stage /usr/src/app/wheels /wheels/
# use wheels to install python dependencies
RUN pip install --no-cache-dir --no-index --find-links=/wheels/ /wheels/* \
&& rm -rf /wheels/
COPY --chown=django:django ./compose/production/django/entrypoint /entrypoint
RUN sed -i 's/\r$//g' /entrypoint
RUN chmod +x /entrypoint
COPY --chown=django:django ./compose/production/django/start /start
RUN sed -i 's/\r$//g' /start
RUN chmod +x /start
# copy application code to WORKDIR
COPY --chown=django:django . ${APP_HOME}
# explicitly create the media folder before changing ownership below
RUN mkdir -p ${APP_HOME}/diarios_oficiais_search_alems/media
# make django owner of the WORKDIR directory as well.
RUN chown -R django:django ${APP_HOME}
USER django
RUN DATABASE_URL="" \
DJANGO_SETTINGS_MODULE="config.settings.test" \
python manage.py compilemessages
ENTRYPOINT ["/entrypoint"]

View File

@ -0,0 +1,17 @@
#!/bin/bash
set -o errexit
set -o pipefail
set -o nounset
if [ -z "${POSTGRES_USER}" ]; then
base_postgres_image_default_user='postgres'
export POSTGRES_USER="${base_postgres_image_default_user}"
fi
export DATABASE_URL="postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}"
wait-for-it "${POSTGRES_HOST}:${POSTGRES_PORT}" -t 30
>&2 echo 'PostgreSQL is available'
exec "$@"

View File

@ -0,0 +1,29 @@
#!/bin/bash
set -o errexit
set -o pipefail
set -o nounset
python /app/manage.py collectstatic --noinput
compress_enabled() {
python << END
import sys
from environ import Env
env = Env(COMPRESS_ENABLED=(bool, True))
if env('COMPRESS_ENABLED'):
sys.exit(0)
else:
sys.exit(1)
END
}
if compress_enabled; then
# NOTE this command will fail if django-compressor is disabled
python /app/manage.py compress
fi
exec /usr/local/bin/gunicorn config.asgi --bind 0.0.0.0:5000 --chdir=/app -k uvicorn_worker.UvicornWorker

View File

@ -0,0 +1,2 @@
FROM docker.io/nginx:1.17.8-alpine
COPY ./compose/production/nginx/default.conf /etc/nginx/conf.d/default.conf

View File

@ -0,0 +1,7 @@
server {
listen 80;
server_name localhost;
location /media/ {
alias /usr/share/nginx/media/;
}
}

View File

@ -0,0 +1,6 @@
FROM docker.io/postgres:17
COPY ./compose/production/postgres/maintenance /usr/local/bin/maintenance
RUN chmod +x /usr/local/bin/maintenance/*
RUN mv /usr/local/bin/maintenance/* /usr/local/bin \
&& rmdir /usr/local/bin/maintenance

View File

@ -0,0 +1,5 @@
#!/usr/bin/env bash
BACKUP_DIR_PATH='/backups'
BACKUP_FILE_PREFIX='backup'

View File

@ -0,0 +1,12 @@
#!/usr/bin/env bash
countdown() {
declare desc="A simple countdown. Source: https://superuser.com/a/611582"
local seconds="${1}"
local d=$(($(date +%s) + "${seconds}"))
while [ "$d" -ge `date +%s` ]; do
echo -ne "$(date -u --date @$(($d - `date +%s`)) +%H:%M:%S)\r";
sleep 0.1
done
}

View File

@ -0,0 +1,41 @@
#!/usr/bin/env bash
message_newline() {
echo
}
message_debug()
{
echo -e "DEBUG: ${@}"
}
message_welcome()
{
echo -e "\e[1m${@}\e[0m"
}
message_warning()
{
echo -e "\e[33mWARNING\e[0m: ${@}"
}
message_error()
{
echo -e "\e[31mERROR\e[0m: ${@}"
}
message_info()
{
echo -e "\e[37mINFO\e[0m: ${@}"
}
message_suggestion()
{
echo -e "\e[33mSUGGESTION\e[0m: ${@}"
}
message_success()
{
echo -e "\e[32mSUCCESS\e[0m: ${@}"
}

View File

@ -0,0 +1,16 @@
#!/usr/bin/env bash
yes_no() {
declare desc="Prompt for confirmation. \$\"\{1\}\": confirmation message."
local arg1="${1}"
local response=
read -r -p "${arg1} (y/[n])? " response
if [[ "${response}" =~ ^[Yy]$ ]]
then
exit 0
else
exit 1
fi
}

View File

@ -0,0 +1,38 @@
#!/usr/bin/env bash
### Create a database backup.
###
### Usage:
### $ docker compose -f <environment>.yml (exec |run --rm) postgres backup
set -o errexit
set -o pipefail
set -o nounset
working_dir="$(dirname ${0})"
source "${working_dir}/_sourced/constants.sh"
source "${working_dir}/_sourced/messages.sh"
message_welcome "Backing up the '${POSTGRES_DB}' database..."
if [[ "${POSTGRES_USER}" == "postgres" ]]; then
message_error "Backing up as 'postgres' user is not supported. Assign 'POSTGRES_USER' env with another one and try again."
exit 1
fi
export PGHOST="${POSTGRES_HOST}"
export PGPORT="${POSTGRES_PORT}"
export PGUSER="${POSTGRES_USER}"
export PGPASSWORD="${POSTGRES_PASSWORD}"
export PGDATABASE="${POSTGRES_DB}"
backup_filename="${BACKUP_FILE_PREFIX}_$(date +'%Y_%m_%dT%H_%M_%S').sql.gz"
pg_dump | gzip > "${BACKUP_DIR_PATH}/${backup_filename}"
message_success "'${POSTGRES_DB}' database backup '${backup_filename}' has been created and placed in '${BACKUP_DIR_PATH}'."

View File

@ -0,0 +1,22 @@
#!/usr/bin/env bash
### View backups.
###
### Usage:
### $ docker compose -f <environment>.yml (exec |run --rm) postgres backups
set -o errexit
set -o pipefail
set -o nounset
working_dir="$(dirname ${0})"
source "${working_dir}/_sourced/constants.sh"
source "${working_dir}/_sourced/messages.sh"
message_welcome "These are the backups you have got:"
ls -lht "${BACKUP_DIR_PATH}"

View File

@ -0,0 +1,55 @@
#!/usr/bin/env bash
### Restore database from a backup.
###
### Parameters:
### <1> filename of an existing backup.
###
### Usage:
### $ docker compose -f <environment>.yml (exec |run --rm) postgres restore <1>
set -o errexit
set -o pipefail
set -o nounset
working_dir="$(dirname ${0})"
source "${working_dir}/_sourced/constants.sh"
source "${working_dir}/_sourced/messages.sh"
if [[ -z ${1+x} ]]; then
message_error "Backup filename is not specified yet it is a required parameter. Make sure you provide one and try again."
exit 1
fi
backup_filename="${BACKUP_DIR_PATH}/${1}"
if [[ ! -f "${backup_filename}" ]]; then
message_error "No backup with the specified filename found. Check out the 'backups' maintenance script output to see if there is one and try again."
exit 1
fi
message_welcome "Restoring the '${POSTGRES_DB}' database from the '${backup_filename}' backup..."
if [[ "${POSTGRES_USER}" == "postgres" ]]; then
message_error "Restoring as 'postgres' user is not supported. Assign 'POSTGRES_USER' env with another one and try again."
exit 1
fi
export PGHOST="${POSTGRES_HOST}"
export PGPORT="${POSTGRES_PORT}"
export PGUSER="${POSTGRES_USER}"
export PGPASSWORD="${POSTGRES_PASSWORD}"
export PGDATABASE="${POSTGRES_DB}"
message_info "Dropping the database..."
dropdb "${PGDATABASE}"
message_info "Creating a new database..."
createdb --owner="${POSTGRES_USER}"
message_info "Applying the backup to the new database..."
gunzip -c "${backup_filename}" | psql "${POSTGRES_DB}"
message_success "The '${POSTGRES_DB}' database has been restored from the '${backup_filename}' backup."

View File

@ -0,0 +1,36 @@
#!/usr/bin/env bash
### Remove a database backup.
###
### Parameters:
### <1> filename of a backup to remove.
###
### Usage:
### $ docker-compose -f <environment>.yml (exec |run --rm) postgres rmbackup <1>
set -o errexit
set -o pipefail
set -o nounset
working_dir="$(dirname ${0})"
source "${working_dir}/_sourced/constants.sh"
source "${working_dir}/_sourced/messages.sh"
if [[ -z ${1+x} ]]; then
message_error "Backup filename is not specified yet it is a required parameter. Make sure you provide one and try again."
exit 1
fi
backup_filename="${BACKUP_DIR_PATH}/${1}"
if [[ ! -f "${backup_filename}" ]]; then
message_error "No backup with the specified filename found. Check out the 'backups' maintenance script output to see if there is one and try again."
exit 1
fi
message_welcome "Removing the '${backup_filename}' backup file..."
rm -r "${backup_filename}"
message_success "The '${backup_filename}' database backup has been removed."

View File

@ -0,0 +1,5 @@
FROM docker.io/traefik:3.4.1
RUN mkdir -p /etc/traefik/acme \
&& touch /etc/traefik/acme/acme.json \
&& chmod 600 /etc/traefik/acme/acme.json
COPY ./compose/production/traefik/traefik.yml /etc/traefik

View File

@ -0,0 +1,73 @@
log:
level: INFO
entryPoints:
web:
# http
address: ':80'
http:
# https://doc.traefik.io/traefik/routing/entrypoints/#entrypoint
redirections:
entryPoint:
to: web-secure
web-secure:
# https
address: ':443'
certificatesResolvers:
letsencrypt:
# https://doc.traefik.io/traefik/https/acme/#lets-encrypt
acme:
email: 'antoniorobertojunior96@gmail.com'
storage: /etc/traefik/acme/acme.json
# https://doc.traefik.io/traefik/https/acme/#httpchallenge
httpChallenge:
entryPoint: web
http:
routers:
web-secure-router:
rule: 'Host(`al.ms.gov.br`)'
entryPoints:
- web-secure
middlewares:
- csrf
service: django
tls:
# https://doc.traefik.io/traefik/routing/routers/#certresolver
certResolver: letsencrypt
web-media-router:
rule: 'Host(`al.ms.gov.br`) && PathPrefix(`/media/`)'
entryPoints:
- web-secure
middlewares:
- csrf
service: django-media
tls:
certResolver: letsencrypt
middlewares:
csrf:
# https://doc.traefik.io/traefik/master/middlewares/http/headers/#hostsproxyheaders
# https://docs.djangoproject.com/en/dev/ref/csrf/#ajax
headers:
hostsProxyHeaders: ['X-CSRFToken']
services:
django:
loadBalancer:
servers:
- url: http://django:5000
django-media:
loadBalancer:
servers:
- url: http://nginx:80
providers:
# https://doc.traefik.io/traefik/master/providers/file/
file:
filename: /etc/traefik/traefik.yml
watch: true

0
config/__init__.py Normal file
View File

39
config/asgi.py Normal file
View File

@ -0,0 +1,39 @@
"""
ASGI config for Diarios Oficiais Search ALEMS 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/dev/howto/deployment/asgi/
"""
import os
import sys
from pathlib import Path
from django.core.asgi import get_asgi_application
# This allows easy placement of apps within the interior
# diarios_oficiais_search_alems directory.
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
sys.path.append(str(BASE_DIR / "diarios_oficiais_search_alems"))
# If DJANGO_SETTINGS_MODULE is unset, default to the local settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
# This application object is used by any ASGI server configured to use this file.
django_application = get_asgi_application()
# Import websocket application here, so apps from django_application are loaded first
from config.websocket import websocket_application # noqa: E402
async def application(scope, receive, send):
if scope["type"] == "http":
await django_application(scope, receive, send)
elif scope["type"] == "websocket":
await websocket_application(scope, receive, send)
else:
msg = f"Unknown scope type {scope['type']}"
raise NotImplementedError(msg)

View File

288
config/settings/base.py Normal file
View File

@ -0,0 +1,288 @@
# ruff: noqa: ERA001, E501
"""Base settings to build other settings files upon."""
from pathlib import Path
import environ
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent.parent
# diarios_oficiais_search_alems/
APPS_DIR = BASE_DIR / "diarios_oficiais_search_alems"
env = environ.Env()
READ_DOT_ENV_FILE = env.bool("DJANGO_READ_DOT_ENV_FILE", default=False)
if READ_DOT_ENV_FILE:
# OS environment variables take precedence over variables from .env
env.read_env(str(BASE_DIR / ".env"))
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = env.bool("DJANGO_DEBUG", False)
# Local time zone. Choices are
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# though not all of them may be available with every OS.
# In Windows, this must be set to your system time zone.
TIME_ZONE = "America/Campo_Grande"
# https://docs.djangoproject.com/en/dev/ref/settings/#language-code
LANGUAGE_CODE = "en-us"
# https://docs.djangoproject.com/en/dev/ref/settings/#languages
# from django.utils.translation import gettext_lazy as _
# LANGUAGES = [
# ('en', _('English')),
# ('fr-fr', _('French')),
# ('pt-br', _('Portuguese')),
# ]
# https://docs.djangoproject.com/en/dev/ref/settings/#site-id
SITE_ID = 1
# https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
USE_I18N = True
# https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
USE_TZ = True
# https://docs.djangoproject.com/en/dev/ref/settings/#locale-paths
LOCALE_PATHS = [str(BASE_DIR / "locale")]
# DATABASES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {"default": env.db("DATABASE_URL")}
DATABASES["default"]["ATOMIC_REQUESTS"] = True
# https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-DEFAULT_AUTO_FIELD
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
# URLS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf
ROOT_URLCONF = "config.urls"
# https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = "config.wsgi.application"
# APPS
# ------------------------------------------------------------------------------
DJANGO_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.sites",
"django.contrib.messages",
"django.contrib.staticfiles",
# "django.contrib.humanize", # Handy template tags
"django.contrib.admin",
"django.forms",
]
THIRD_PARTY_APPS = [
"crispy_forms",
"crispy_bootstrap5",
"allauth",
"allauth.account",
"allauth.mfa",
"allauth.socialaccount",
]
LOCAL_APPS = [
"diarios_oficiais_search_alems.users",
# Your stuff: custom apps go here
]
# https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
# MIGRATIONS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#migration-modules
MIGRATION_MODULES = {"sites": "diarios_oficiais_search_alems.contrib.sites.migrations"}
# AUTHENTICATION
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#authentication-backends
AUTHENTICATION_BACKENDS = [
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
]
# https://docs.djangoproject.com/en/dev/ref/settings/#auth-user-model
AUTH_USER_MODEL = "users.User"
# https://docs.djangoproject.com/en/dev/ref/settings/#login-redirect-url
LOGIN_REDIRECT_URL = "users:redirect"
# https://docs.djangoproject.com/en/dev/ref/settings/#login-url
LOGIN_URL = "account_login"
# PASSWORDS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers
PASSWORD_HASHERS = [
# https://docs.djangoproject.com/en/dev/topics/auth/passwords/#using-argon2-with-django
"django.contrib.auth.hashers.Argon2PasswordHasher",
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
"django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
"django.contrib.auth.hashers.BCryptSHA256PasswordHasher",
]
# https://docs.djangoproject.com/en/dev/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"},
]
# MIDDLEWARE
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#middleware
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.locale.LocaleMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"allauth.account.middleware.AccountMiddleware",
]
# STATIC
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = str(BASE_DIR / "staticfiles")
# https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = "/static/"
# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = [str(APPS_DIR / "static")]
# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
# MEDIA
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = str(APPS_DIR / "media")
# https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = "/media/"
# TEMPLATES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#templates
TEMPLATES = [
{
# https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND
"BACKEND": "django.template.backends.django.DjangoTemplates",
# https://docs.djangoproject.com/en/dev/ref/settings/#dirs
"DIRS": [str(APPS_DIR / "templates")],
# https://docs.djangoproject.com/en/dev/ref/settings/#app-dirs
"APP_DIRS": True,
"OPTIONS": {
# https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"diarios_oficiais_search_alems.users.context_processors.allauth_settings",
],
},
},
]
# https://docs.djangoproject.com/en/dev/ref/settings/#form-renderer
FORM_RENDERER = "django.forms.renderers.TemplatesSetting"
# http://django-crispy-forms.readthedocs.io/en/latest/install.html#template-packs
CRISPY_TEMPLATE_PACK = "bootstrap5"
CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5"
# FIXTURES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#fixture-dirs
FIXTURE_DIRS = (str(APPS_DIR / "fixtures"),)
# SECURITY
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-httponly
SESSION_COOKIE_HTTPONLY = True
# https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-httponly
CSRF_COOKIE_HTTPONLY = True
# https://docs.djangoproject.com/en/dev/ref/settings/#x-frame-options
X_FRAME_OPTIONS = "DENY"
# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = env(
"DJANGO_EMAIL_BACKEND",
default="django.core.mail.backends.smtp.EmailBackend",
)
# https://docs.djangoproject.com/en/dev/ref/settings/#email-timeout
EMAIL_TIMEOUT = 5
# ADMIN
# ------------------------------------------------------------------------------
# Django Admin URL.
ADMIN_URL = "admin/"
# https://docs.djangoproject.com/en/dev/ref/settings/#admins
ADMINS = [("""Antonio Roberto""", "antoniorobertojunior96@gmail.com")]
# https://docs.djangoproject.com/en/dev/ref/settings/#managers
MANAGERS = ADMINS
# https://cookiecutter-django.readthedocs.io/en/latest/settings.html#other-environment-settings
# Force the `admin` sign in process to go through the `django-allauth` workflow
DJANGO_ADMIN_FORCE_ALLAUTH = env.bool("DJANGO_ADMIN_FORCE_ALLAUTH", default=False)
# LOGGING
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#logging
# See https://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"verbose": {
"format": "%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s",
},
},
"handlers": {
"console": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"formatter": "verbose",
},
},
"root": {"level": "INFO", "handlers": ["console"]},
}
REDIS_URL = env("REDIS_URL", default="redis://redis:6379/0")
REDIS_SSL = REDIS_URL.startswith("rediss://")
# django-allauth
# ------------------------------------------------------------------------------
ACCOUNT_ALLOW_REGISTRATION = env.bool("DJANGO_ACCOUNT_ALLOW_REGISTRATION", True)
# https://docs.allauth.org/en/latest/account/configuration.html
ACCOUNT_LOGIN_METHODS = {"username"}
# https://docs.allauth.org/en/latest/account/configuration.html
ACCOUNT_SIGNUP_FIELDS = ["email*", "username*", "password1*", "password2*"]
# https://docs.allauth.org/en/latest/account/configuration.html
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
# https://docs.allauth.org/en/latest/account/configuration.html
ACCOUNT_ADAPTER = "diarios_oficiais_search_alems.users.adapters.AccountAdapter"
# https://docs.allauth.org/en/latest/account/forms.html
ACCOUNT_FORMS = {"signup": "diarios_oficiais_search_alems.users.forms.UserSignupForm"}
# https://docs.allauth.org/en/latest/socialaccount/configuration.html
SOCIALACCOUNT_ADAPTER = "diarios_oficiais_search_alems.users.adapters.SocialAccountAdapter"
# https://docs.allauth.org/en/latest/socialaccount/configuration.html
SOCIALACCOUNT_FORMS = {"signup": "diarios_oficiais_search_alems.users.forms.UserSocialSignupForm"}
# django-compressor
# ------------------------------------------------------------------------------
# https://django-compressor.readthedocs.io/en/latest/quickstart/#installation
INSTALLED_APPS += ["compressor"]
STATICFILES_FINDERS += ["compressor.finders.CompressorFinder"]
# Your stuff...
# ------------------------------------------------------------------------------

93
config/settings/local.py Normal file
View File

@ -0,0 +1,93 @@
# ruff: noqa: E501
from .base import * # noqa: F403
from .base import INSTALLED_APPS
from .base import MIDDLEWARE
from .base import env
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = False
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env(
"DJANGO_SECRET_KEY",
)
# https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ["localhost", "0.0.0.0", "127.0.0.1", "192.168.235.234"] # noqa: S104
# CACHES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#caches
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "",
},
}
# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = env(
"DJANGO_EMAIL_BACKEND", default="django.core.mail.backends.console.EmailBackend",
)
# WhiteNoise
# ------------------------------------------------------------------------------
# http://whitenoise.evans.io/en/latest/django.html#using-whitenoise-in-development
INSTALLED_APPS = ["whitenoise.runserver_nostatic", *INSTALLED_APPS]
# django-debug-toolbar
# ------------------------------------------------------------------------------
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#prerequisites
INSTALLED_APPS += ["debug_toolbar"]
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#middleware
MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"]
# https://django-debug-toolbar.readthedocs.io/en/latest/configuration.html#debug-toolbar-config
DEBUG_TOOLBAR_CONFIG = {
"DISABLE_PANELS": [
"debug_toolbar.panels.redirects.RedirectsPanel",
# Disable profiling panel due to an issue with Python 3.12:
# https://github.com/jazzband/django-debug-toolbar/issues/1875
"debug_toolbar.panels.profiling.ProfilingPanel",
],
"SHOW_TEMPLATE_CONTEXT": True,
}
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#internal-ips
INTERNAL_IPS = ["127.0.0.1", "10.0.2.2"]
if env("USE_DOCKER") == "yes":
import socket
hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
INTERNAL_IPS += [".".join(ip.split(".")[:-1] + ["1"]) for ip in ips]
# django-extensions
# ------------------------------------------------------------------------------
# https://django-extensions.readthedocs.io/en/latest/installation_instructions.html#configuration
INSTALLED_APPS += ["django_extensions"]
# Permitir o proxy Nginx
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'http')
USE_X_FORWARDED_HOST = True
# django-compressor
# ------------------------------------------------------------------------------
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_ENABLED
COMPRESS_ENABLED = env.bool("COMPRESS_ENABLED", default=True)
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_STORAGE
COMPRESS_STORAGE = "compressor.storage.GzipCompressorFileStorage"
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_URL
COMPRESS_URL = STATIC_URL # noqa: F405
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_OFFLINE
COMPRESS_OFFLINE = True # Offline compression is required when using Whitenoise
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_FILTERS
COMPRESS_FILTERS = {
"css": [
"compressor.filters.css_default.CssAbsoluteFilter",
"compressor.filters.cssmin.rCSSMinFilter",
],
"js": ["compressor.filters.jsmin.JSMinFilter"],
}

View File

@ -0,0 +1,172 @@
# ruff: noqa: E501
from .base import * # noqa: F403
from .base import DATABASES
from .base import INSTALLED_APPS
from .base import REDIS_URL
from .base import env
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env("DJANGO_SECRET_KEY")
# https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=["al.ms.gov.br"])
# DATABASES
# ------------------------------------------------------------------------------
DATABASES["default"]["CONN_MAX_AGE"] = env.int("CONN_MAX_AGE", default=60)
# CACHES
# ------------------------------------------------------------------------------
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": REDIS_URL,
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
# Mimicking memcache behavior.
# https://github.com/jazzband/django-redis#memcached-exceptions-behavior
"IGNORE_EXCEPTIONS": True,
},
},
}
# SECURITY
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-proxy-ssl-header
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-ssl-redirect
SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True)
# https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-secure
SESSION_COOKIE_SECURE = True
# https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-name
SESSION_COOKIE_NAME = "__Secure-sessionid"
# https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-secure
CSRF_COOKIE_SECURE = True
# https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-name
CSRF_COOKIE_NAME = "__Secure-csrftoken"
# https://docs.djangoproject.com/en/dev/topics/security/#ssl-https
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-seconds
# TODO: set this to 60 seconds first and then to 518400 once you prove the former works
SECURE_HSTS_SECONDS = 60
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-include-subdomains
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(
"DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS",
default=True,
)
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-preload
SECURE_HSTS_PRELOAD = env.bool("DJANGO_SECURE_HSTS_PRELOAD", default=True)
# https://docs.djangoproject.com/en/dev/ref/middleware/#x-content-type-options-nosniff
SECURE_CONTENT_TYPE_NOSNIFF = env.bool(
"DJANGO_SECURE_CONTENT_TYPE_NOSNIFF",
default=True,
)
# STATIC & MEDIA
# ------------------------
STORAGES = {
"default": {
"BACKEND": "django.core.files.storage.FileSystemStorage",
},
"staticfiles": {
"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage",
},
}
# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email
DEFAULT_FROM_EMAIL = env(
"DJANGO_DEFAULT_FROM_EMAIL",
default="Diarios Oficiais Search ALEMS <noreply@al.ms.gov.br>",
)
# https://docs.djangoproject.com/en/dev/ref/settings/#server-email
SERVER_EMAIL = env("DJANGO_SERVER_EMAIL", default=DEFAULT_FROM_EMAIL)
# https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix
EMAIL_SUBJECT_PREFIX = env(
"DJANGO_EMAIL_SUBJECT_PREFIX",
default="[Diarios Oficiais Search ALEMS] ",
)
ACCOUNT_EMAIL_SUBJECT_PREFIX = EMAIL_SUBJECT_PREFIX
# ADMIN
# ------------------------------------------------------------------------------
# Django Admin URL regex.
ADMIN_URL = env("DJANGO_ADMIN_URL")
# Anymail
# ------------------------------------------------------------------------------
# https://anymail.readthedocs.io/en/stable/installation/#installing-anymail
INSTALLED_APPS += ["anymail"]
# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
# https://anymail.readthedocs.io/en/stable/installation/#anymail-settings-reference
# https://anymail.readthedocs.io/en/stable/esps
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
ANYMAIL = {}
# django-compressor
# ------------------------------------------------------------------------------
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_ENABLED
COMPRESS_ENABLED = env.bool("COMPRESS_ENABLED", default=True)
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_STORAGE
COMPRESS_STORAGE = "compressor.storage.GzipCompressorFileStorage"
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_URL
COMPRESS_URL = STATIC_URL # noqa: F405
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_OFFLINE
COMPRESS_OFFLINE = True # Offline compression is required when using Whitenoise
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_FILTERS
COMPRESS_FILTERS = {
"css": [
"compressor.filters.css_default.CssAbsoluteFilter",
"compressor.filters.cssmin.rCSSMinFilter",
],
"js": ["compressor.filters.jsmin.JSMinFilter"],
}
# LOGGING
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#logging
# See https://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}},
"formatters": {
"verbose": {
"format": "%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s",
},
},
"handlers": {
"mail_admins": {
"level": "ERROR",
"filters": ["require_debug_false"],
"class": "django.utils.log.AdminEmailHandler",
},
"console": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"formatter": "verbose",
},
},
"root": {"level": "INFO", "handlers": ["console"]},
"loggers": {
"django.request": {
"handlers": ["mail_admins"],
"level": "ERROR",
"propagate": True,
},
"django.security.DisallowedHost": {
"level": "ERROR",
"handlers": ["console", "mail_admins"],
"propagate": True,
},
},
}
# Your stuff...
# ------------------------------------------------------------------------------

38
config/settings/test.py Normal file
View File

@ -0,0 +1,38 @@
"""
With these settings, tests run faster.
"""
from .base import * # noqa: F403
from .base import TEMPLATES
from .base import env
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env(
"DJANGO_SECRET_KEY",
default="5VRhygBDHsMfJ3bQXl6QQINTW7RIqriCxvOBcN8MtE8BHYQuo94WjT0DDsBq2MUt",
)
# https://docs.djangoproject.com/en/dev/ref/settings/#test-runner
TEST_RUNNER = "django.test.runner.DiscoverRunner"
# PASSWORDS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers
PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]
# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"
# DEBUGGING FOR TEMPLATES
# ------------------------------------------------------------------------------
TEMPLATES[0]["OPTIONS"]["debug"] = True # type: ignore[index]
# MEDIA
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = "http://media.testserver/"
# Your stuff...
# ------------------------------------------------------------------------------

59
config/urls.py Normal file
View File

@ -0,0 +1,59 @@
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.urls import include
from django.urls import path
from django.views import defaults as default_views
from django.views.generic import TemplateView
urlpatterns = [
path("", TemplateView.as_view(template_name="pages/home.html"), name="home"),
path(
"about/",
TemplateView.as_view(template_name="pages/about.html"),
name="about",
),
# Django Admin, use {% url 'admin:index' %}
path(settings.ADMIN_URL, admin.site.urls),
# User management
path("users/", include("diarios_oficiais_search_alems.users.urls", namespace="users")),
path("accounts/", include("allauth.urls")),
# Your stuff: custom urls includes go here
# ...
# Media files
*static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT),
]
if settings.DEBUG:
# Static file serving when using Gunicorn + Uvicorn for local web socket development
urlpatterns += staticfiles_urlpatterns()
if settings.DEBUG:
# This allows the error pages to be debugged during development, just visit
# these url in browser to see how these error pages look like.
urlpatterns += [
path(
"400/",
default_views.bad_request,
kwargs={"exception": Exception("Bad Request!")},
),
path(
"403/",
default_views.permission_denied,
kwargs={"exception": Exception("Permission Denied")},
),
path(
"404/",
default_views.page_not_found,
kwargs={"exception": Exception("Page not Found")},
),
path("500/", default_views.server_error),
]
if "debug_toolbar" in settings.INSTALLED_APPS:
import debug_toolbar
urlpatterns = [
path("__debug__/", include(debug_toolbar.urls)),
*urlpatterns,
]

13
config/websocket.py Normal file
View File

@ -0,0 +1,13 @@
async def websocket_application(scope, receive, send):
while True:
event = await receive()
if event["type"] == "websocket.connect":
await send({"type": "websocket.accept"})
if event["type"] == "websocket.disconnect":
break
if event["type"] == "websocket.receive":
if event["text"] == "ping":
await send({"type": "websocket.send", "text": "pong!"})

32
config/wsgi.py Normal file
View File

@ -0,0 +1,32 @@
"""
WSGI config for Diarios Oficiais Search ALEMS project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
import sys
from pathlib import Path
from django.core.wsgi import get_wsgi_application
# This allows easy placement of apps within the interior
# diarios_oficiais_search_alems directory.
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
sys.path.append(str(BASE_DIR / "diarios_oficiais_search_alems"))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
application = get_wsgi_application()

View File

@ -0,0 +1,5 @@
__version__ = "0.1.0"
__version_info__ = tuple(
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
)

View File

@ -0,0 +1,14 @@
import pytest
from diarios_oficiais_search_alems.users.models import User
from diarios_oficiais_search_alems.users.tests.factories import UserFactory
@pytest.fixture(autouse=True)
def _media_storage(settings, tmpdir) -> None:
settings.MEDIA_ROOT = tmpdir.strpath
@pytest.fixture
def user(db) -> User:
return UserFactory()

View File

@ -0,0 +1,5 @@
"""
To understand why this file is here, please read:
https://cookiecutter-django.readthedocs.io/en/latest/5-help/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
"""

View File

@ -0,0 +1,5 @@
"""
To understand why this file is here, please read:
https://cookiecutter-django.readthedocs.io/en/latest/5-help/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
"""

View File

@ -0,0 +1,43 @@
import django.contrib.sites.models
from django.contrib.sites.models import _simple_domain_name_validator
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
name="Site",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"domain",
models.CharField(
max_length=100,
verbose_name="domain name",
validators=[_simple_domain_name_validator],
),
),
("name", models.CharField(max_length=50, verbose_name="display name")),
],
options={
"ordering": ("domain",),
"db_table": "django_site",
"verbose_name": "site",
"verbose_name_plural": "sites",
},
bases=(models.Model,),
managers=[("objects", django.contrib.sites.models.SiteManager())],
),
]

View File

@ -0,0 +1,21 @@
import django.contrib.sites.models
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
dependencies = [("sites", "0001_initial")]
operations = [
migrations.AlterField(
model_name="site",
name="domain",
field=models.CharField(
max_length=100,
unique=True,
validators=[django.contrib.sites.models._simple_domain_name_validator],
verbose_name="domain name",
),
)
]

View File

@ -0,0 +1,63 @@
"""
To understand why this file is here, please read:
https://cookiecutter-django.readthedocs.io/en/latest/5-help/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
"""
from django.conf import settings
from django.db import migrations
def _update_or_create_site_with_sequence(site_model, connection, domain, name):
"""Update or create the site with default ID and keep the DB sequence in sync."""
site, created = site_model.objects.update_or_create(
id=settings.SITE_ID,
defaults={
"domain": domain,
"name": name,
},
)
if created:
# We provided the ID explicitly when creating the Site entry, therefore the DB
# sequence to auto-generate them wasn't used and is now out of sync. If we
# don't do anything, we'll get a unique constraint violation the next time a
# site is created.
# To avoid this, we need to manually update DB sequence and make sure it's
# greater than the maximum value.
max_id = site_model.objects.order_by("-id").first().id
with connection.cursor() as cursor:
cursor.execute("SELECT last_value from django_site_id_seq")
(current_id,) = cursor.fetchone()
if current_id <= max_id:
cursor.execute(
"alter sequence django_site_id_seq restart with %s",
[max_id + 1],
)
def update_site_forward(apps, schema_editor):
"""Set site domain and name."""
Site = apps.get_model("sites", "Site")
_update_or_create_site_with_sequence(
Site,
schema_editor.connection,
"al.ms.gov.br",
"Diarios Oficiais Search ALEMS",
)
def update_site_backward(apps, schema_editor):
"""Revert site domain and name to default."""
Site = apps.get_model("sites", "Site")
_update_or_create_site_with_sequence(
Site,
schema_editor.connection,
"example.com",
"example.com",
)
class Migration(migrations.Migration):
dependencies = [("sites", "0002_alter_domain_unique")]
operations = [migrations.RunPython(update_site_forward, update_site_backward)]

View File

@ -0,0 +1,21 @@
# Generated by Django 3.1.7 on 2021-02-04 14:49
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("sites", "0003_set_site_domain_and_name"),
]
operations = [
migrations.AlterModelOptions(
name="site",
options={
"ordering": ["domain"],
"verbose_name": "site",
"verbose_name_plural": "sites",
},
),
]

View File

@ -0,0 +1,5 @@
"""
To understand why this file is here, please read:
https://cookiecutter-django.readthedocs.io/en/latest/5-help/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
"""

View File

@ -0,0 +1,13 @@
/* These styles are generated from project.scss. */
.alert-debug {
color: black;
background-color: white;
border-color: #d6e9c6;
}
.alert-error {
color: #b94a48;
background-color: #f2dede;
border-color: #eed3d7;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

View File

@ -0,0 +1 @@
/* Project specific Javascript goes here. */

View File

@ -0,0 +1,13 @@
{% extends "base.html" %}
{% block title %}Forbidden (403){% endblock title %}
{% block content %}
<h1>Forbidden (403)</h1>
<p>
{% if exception %}
{{ exception }}
{% else %}
You're not allowed to access this page.
{% endif %}
</p>
{% endblock content %}

View File

@ -0,0 +1,13 @@
{% extends "base.html" %}
{% block title %}Forbidden (403){% endblock title %}
{% block content %}
<h1>Forbidden (403)</h1>
<p>
{% if exception %}
{{ exception }}
{% else %}
You're not allowed to access this page.
{% endif %}
</p>
{% endblock content %}

View File

@ -0,0 +1,13 @@
{% extends "base.html" %}
{% block title %}Page not found{% endblock title %}
{% block content %}
<h1>Page not found</h1>
<p>
{% if exception %}
{{ exception }}
{% else %}
This is not the page you were looking for.
{% endif %}
</p>
{% endblock content %}

View File

@ -0,0 +1,10 @@
{% extends "base.html" %}
{% block title %}Server Error{% endblock title %}
{% block content %}
<h1>Ooops!!! 500</h1>
<h3>Looks like something went wrong!</h3>
<p>
We track these errors automatically, but if the problem persists feel free to contact us. In the meantime, try refreshing.
</p>
{% endblock content %}

View File

@ -0,0 +1,11 @@
{% extends "account/base_manage.html" %}
{% block main %}
<div class="card">
<div class="card-body">
{% block content %}
{% endblock content %}
</div>
</div>
{% endblock main %}

View File

@ -0,0 +1,7 @@
{% load i18n %}
{% load allauth %}
<div class="alert alert-error">
{% slot message %}
{% endslot %}
</div>

View File

@ -0,0 +1,6 @@
{% load allauth %}
<span class="badge {% if 'success' in attrs.tags %}bg-success{% endif %} {% if 'warning' in attrs.tags %}bg-warning{% endif %} {% if 'secondary' in attrs.tags %}bg-secondary{% endif %} {% if 'danger' in attrs.tags %}bg-danger{% endif %} {% if 'primary' in attrs.tags %}bg-primary{% endif %}">
{% slot %}
{% endslot %}
</span>

View File

@ -0,0 +1,20 @@
{% load allauth %}
{% comment %} djlint:off {% endcomment %}
<{% if attrs.href %}a href="{{ attrs.href }}"{% else %}button{% endif %}
{% if attrs.form %}form="{{ attrs.form }}"{% endif %}
{% if attrs.id %}id="{{ attrs.id }}"{% endif %}
{% if attrs.name %}name="{{ attrs.name }}"{% endif %}
{% if attrs.type %}type="{{ attrs.type }}"{% endif %}
class="btn
{% if 'success' in attrs.tags %}btn-success
{% elif 'warning' in attrs.tags %}btn-warning
{% elif 'secondary' in attrs.tags %}btn-secondary
{% elif 'danger' in attrs.tags %}btn-danger
{% elif 'primary' in attrs.tags %}btn-primary
{% else %}btn-primary
{% endif %}"
>
{% slot %}
{% endslot %}
</{% if attrs.href %}a{% else %}button{% endif %}>

View File

@ -0,0 +1,66 @@
{% load allauth %}
{% load crispy_forms_tags %}
{% if attrs.type == "textarea" %}
<div class="row mb-3">
<div class="col-sm-10">
<label for="{{ attrs.id }}">
{% slot label %}
{% endslot %}
</label>
</div>
<textarea {% if attrs.required %}required{% endif %}
{% if attrs.rows %}rows="{{ attrs.rows }}"{% endif %}
{% if attrs.disabled %}disabled{% endif %}
{% if attrs.readonly %}readonly{% endif %}
{% if attrs.checked %}checked{% endif %}
{% if attrs.name %}name="{{ attrs.name }}"{% endif %}
{% if attrs.id %}id="{{ attrs.id }}"{% endif %}
{% if attrs.placeholder %}placeholder="{{ attrs.placeholder }}"{% endif %}
class="form-control">{% slot value %}{% endslot %}</textarea>
</div>
{% elif attrs.type == "radio" %}
<div class="row mb-3">
<div class="col-sm-10">
<div class="form-check">
<input {% if attrs.required %}required{% endif %}
{% if attrs.disabled %}disabled{% endif %}
{% if attrs.readonly %}readonly{% endif %}
{% if attrs.checked %}checked{% endif %}
{% if attrs.name %}name="{{ attrs.name }}"{% endif %}
{% if attrs.id %}id="{{ attrs.id }}"{% endif %}
{% if attrs.placeholder %}placeholder="{{ attrs.placeholder }}"{% endif %}
{% if attrs.autocomplete %}autocomplete="{{ attrs.autocomplete }}"{% endif %}
value="{{ attrs.value|default_if_none:"" }}"
type="{{ attrs.type }}" />
<label class="form-check-label" for="{{ attrs.id }}">
{% slot label %}
{% endslot %}
</label>
</div>
</div>
</div>
{% else %}
<div class="col-sm-10">
<label for="{{ attrs.id }}">
{% slot label %}
{% endslot %}
</label>
</div>
<div class="col-sm-10">
<input {% if attrs.required %}required{% endif %}
{% if attrs.disabled %}disabled{% endif %}
{% if attrs.readonly %}readonly{% endif %}
{% if attrs.checked %}checked{% endif %}
{% if attrs.name %}name="{{ attrs.name }}"{% endif %}
{% if attrs.id %}id="{{ attrs.id }}"{% endif %}
{% if attrs.placeholder %}placeholder="{{ attrs.placeholder }}"{% endif %}
{% if attrs.autocomplete %}autocomplete="{{ attrs.autocomplete }}"{% endif %}
value="{{ attrs.value|default_if_none:"" }}"
type="{{ attrs.type }}"
class="form-control" />
</div>
{% endif %}
{% if slots.help_text %}
<div class="form-text">{% slot help_text %}{% endslot %}</div>
{% endif %}

View File

@ -0,0 +1,3 @@
{% load crispy_forms_tags %}
{{ attrs.form|crispy }}

View File

@ -0,0 +1,19 @@
{% load allauth %}
<section>
<div class="card mb-4">
<div class="card-body">
<h2 class="card-title">
{% slot title %}
{% endslot %}
</h2>
{% slot body %}
{% endslot %}
{% if slots.actions %}
<ul>
{% for action in slots.actions %}<li>{{ action }}</li>{% endfor %}
</ul>
{% endif %}
</div>
</div>
</section>

View File

@ -0,0 +1,6 @@
{% load allauth %}
<table class="table">
{% slot %}
{% endslot %}
</table>

View File

@ -0,0 +1,31 @@
{% extends "base.html" %}
{% load i18n %}
{% block bodyclass %}bg-light{% endblock bodyclass %}
{% block css %}{{ block.super }}{% endblock css %}
{% block title %}
{% block head_title %}
{% trans "Sign In" %}
{% endblock head_title %}
{% endblock title %}
{% block body %}
<div class="d-flex justify-content-center h-100 py-4">
<div class="col-md-4 py-4 my-4 px-4">
{% if messages %}
{% for message in messages %}
<div class="alert alert-dismissible {% if message.tags %}alert-{{ message.tags }}{% endif %}">
{{ message }}
<button type="button"
class="btn-close"
data-bs-dismiss="alert"
aria-label="Close"></button>
</div>
{% endfor %}
{% endif %}
{% block content %}
{% endblock content %}
{% block extra_body %}
{% endblock extra_body %}
</div>
</div>
{% endblock body %}

View File

@ -0,0 +1,6 @@
{% extends "base.html" %}
{% block main %}
{% block content %}
{% endblock content %}
{% endblock main %}

View File

@ -0,0 +1,145 @@
{% load static i18n compress%}<!DOCTYPE html>
{% get_current_language as LANGUAGE_CODE %}
<html lang="{{ LANGUAGE_CODE }}">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<title>
{% block title %}
Diarios Oficiais Search ALEMS
{% endblock title %}
</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description"
content="Busca textual nos diários oficiais" />
<meta name="author"
content="Antonio Roberto" />
<link rel="icon" href="{% static 'images/favicons/favicon.ico' %}" />
{% block css %}
<!-- Latest compiled and minified Bootstrap CSS -->
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/css/bootstrap.min.css"
integrity="sha512-SbiR/eusphKoMVVXysTKG/7VseWii+Y3FdHrt0EpKgpToZeemhqHeZeLWLhJutz/2ut2Vw1uQEj2MbRF+TVBUA=="
crossorigin="anonymous"
referrerpolicy="no-referrer" />
<!-- Your stuff: Third-party CSS libraries go here -->
<!-- This file stores project-specific CSS -->
{% compress css %}
<link href="{% static 'css/project.css' %}" rel="stylesheet" />
{% endcompress %}
{% endblock css %}
<!-- Le javascript
================================================== -->
{# Placed at the top of the document so pages load faster with defer #}
{% block javascript %}
<!-- Bootstrap JS -->
<script defer
src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/js/bootstrap.min.js"
integrity="sha512-1/RvZTcCDEUjY/CypiMz+iqqtaoQfAITmNSJY17Myp4Ms5mdxPS5UV7iOfdZoxcGhzFbOm6sntTKJppjvuhg4g=="
crossorigin="anonymous"
referrerpolicy="no-referrer"></script>
<!-- Your stuff: Third-party javascript libraries go here -->
<!-- place project specific Javascript in this file -->
{% compress js %}
<script defer src="{% static 'js/project.js' %}"></script>
{% endcompress %}
{% endblock javascript %}
</head>
<body class="{% block bodyclass %}{% endblock bodyclass %}">
{% block body %}
<div class="mb-1">
<nav class="navbar navbar-expand-md navbar-light bg-light">
<div class="container-fluid">
<button class="navbar-toggler navbar-toggler-right"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="{% url 'home' %}">Diarios Oficiais Search ALEMS</a>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="{% url 'home' %}">Home <span class="visually-hidden">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'about' %}">About</a>
</li>
{% if request.user.is_authenticated %}
<li class="nav-item">
<a class="nav-link"
href="{% url 'users:detail' request.user.username %}">{% translate "My Profile" %}</a>
</li>
<li class="nav-item">
{# URL provided by django-allauth/account/urls.py #}
<a class="nav-link" href="{% url 'account_logout' %}">{% translate "Sign Out" %}</a>
</li>
{% else %}
{% if ACCOUNT_ALLOW_REGISTRATION %}
<li class="nav-item">
{# URL provided by django-allauth/account/urls.py #}
<a id="sign-up-link" class="nav-link" href="{% url 'account_signup' %}">{% translate "Sign Up" %}</a>
</li>
{% endif %}
<li class="nav-item">
{# URL provided by django-allauth/account/urls.py #}
<a id="log-in-link" class="nav-link" href="{% url 'account_login' %}">{% translate "Sign In" %}</a>
</li>
{% endif %}
</ul>
</div>
</div>
</nav>
</div>
<div class="container">
{% if messages %}
{% for message in messages %}
<div class="alert alert-dismissible {% if message.tags %}alert-{{ message.tags }}{% endif %}">
{{ message }}
<button type="button"
class="btn-close"
data-bs-dismiss="alert"
aria-label="Close"></button>
</div>
{% endfor %}
{% endif %}
{% block main %}
{% block content %}
<p>Use this document as a way to quick start any new project.</p>
{% endblock content %}
{% endblock main %}
</div>
{% endblock body %}
<!-- /container -->
{% block modal %}
{% endblock modal %}
{% block inline_javascript %}
{% comment %}
Script tags with only code, no src (defer by default). To run
with a "defer" so that you run inline code:
<script>
window.addEventListener('DOMContentLoaded', () => {
/* Run whatever you want */
});
</script>
{% endcomment %}
{% endblock inline_javascript %}
</body>
</html>

View File

@ -0,0 +1,3 @@
{% extends "base.html" %}

View File

@ -0,0 +1,3 @@
{% extends "base.html" %}

View File

@ -0,0 +1,44 @@
{% extends "base.html" %}
{% load static %}
{% block title %}
User:
{{ object.username }}
{% endblock title %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-sm-12">
<h2>
{{ object.username }}
</h2>
{% if object.name %}
<p>{{ object.name }}</p>
{% endif %}
</div>
</div>
{% if object == request.user %}
<!-- Action buttons -->
<div class="row">
<div class="col-sm-12">
<a class="btn btn-primary" href="{% url 'users:update' %}" role="button">My Info</a>
<a class="btn btn-primary"
href="{% url 'account_email' %}"
role="button">E-Mail</a>
<a class="btn btn-primary"
href="{% url 'mfa_index' %}"
role="button">MFA</a>
<!-- Your Stuff: Custom user template urls -->
</div>
</div>
<!-- End Action buttons -->
{% endif %}
</div>
{% endblock content %}

View File

@ -0,0 +1,31 @@
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block title %}
{{ user.username }}
{% endblock title %}
{% block content %}
<h1>
{{ user.username }}
</h1>
<form class="form-horizontal"
method="post"
action="{% url 'users:update' %}">
{% csrf_token %}
{{ form|crispy }}
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</div>
</form>
{% endblock content %}

View File

@ -0,0 +1,48 @@
from __future__ import annotations
import typing
from allauth.account.adapter import DefaultAccountAdapter
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from django.conf import settings
if typing.TYPE_CHECKING:
from allauth.socialaccount.models import SocialLogin
from django.http import HttpRequest
from diarios_oficiais_search_alems.users.models import User
class AccountAdapter(DefaultAccountAdapter):
def is_open_for_signup(self, request: HttpRequest) -> bool:
return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True)
class SocialAccountAdapter(DefaultSocialAccountAdapter):
def is_open_for_signup(
self,
request: HttpRequest,
sociallogin: SocialLogin,
) -> bool:
return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True)
def populate_user(
self,
request: HttpRequest,
sociallogin: SocialLogin,
data: dict[str, typing.Any],
) -> User:
"""
Populates user information from social provider info.
See: https://docs.allauth.org/en/latest/socialaccount/advanced.html#creating-and-populating-user-instances
"""
user = super().populate_user(request, sociallogin, data)
if not user.name:
if name := data.get("name"):
user.name = name
elif first_name := data.get("first_name"):
user.name = first_name
if last_name := data.get("last_name"):
user.name += f" {last_name}"
return user

View File

@ -0,0 +1,40 @@
from allauth.account.decorators import secure_admin_login
from django.conf import settings
from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from django.utils.translation import gettext_lazy as _
from .forms import UserAdminChangeForm
from .forms import UserAdminCreationForm
from .models import User
if settings.DJANGO_ADMIN_FORCE_ALLAUTH:
# Force the `admin` sign in process to go through the `django-allauth` workflow:
# https://docs.allauth.org/en/latest/common/admin.html#admin
admin.autodiscover()
admin.site.login = secure_admin_login(admin.site.login) # type: ignore[method-assign]
@admin.register(User)
class UserAdmin(auth_admin.UserAdmin):
form = UserAdminChangeForm
add_form = UserAdminCreationForm
fieldsets = (
(None, {"fields": ("username", "password")}),
(_("Personal info"), {"fields": ("name", "email")}),
(
_("Permissions"),
{
"fields": (
"is_active",
"is_staff",
"is_superuser",
"groups",
"user_permissions",
),
},
),
(_("Important dates"), {"fields": ("last_login", "date_joined")}),
)
list_display = ["username", "name", "is_superuser"]
search_fields = ["name"]

View File

@ -0,0 +1,13 @@
import contextlib
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class UsersConfig(AppConfig):
name = "diarios_oficiais_search_alems.users"
verbose_name = _("Users")
def ready(self):
with contextlib.suppress(ImportError):
import diarios_oficiais_search_alems.users.signals # noqa: F401

View File

@ -0,0 +1,8 @@
from django.conf import settings
def allauth_settings(request):
"""Expose some settings from django-allauth in templates."""
return {
"ACCOUNT_ALLOW_REGISTRATION": settings.ACCOUNT_ALLOW_REGISTRATION,
}

View File

@ -0,0 +1,40 @@
from allauth.account.forms import SignupForm
from allauth.socialaccount.forms import SignupForm as SocialSignupForm
from django.contrib.auth import forms as admin_forms
from django.utils.translation import gettext_lazy as _
from .models import User
class UserAdminChangeForm(admin_forms.UserChangeForm):
class Meta(admin_forms.UserChangeForm.Meta): # type: ignore[name-defined]
model = User
class UserAdminCreationForm(admin_forms.AdminUserCreationForm):
"""
Form for User Creation in the Admin Area.
To change user signup, see UserSignupForm and UserSocialSignupForm.
"""
class Meta(admin_forms.UserCreationForm.Meta): # type: ignore[name-defined]
model = User
error_messages = {
"username": {"unique": _("This username has already been taken.")},
}
class UserSignupForm(SignupForm):
"""
Form that will be rendered on a user sign up section/screen.
Default fields will be added automatically.
Check UserSocialSignupForm for accounts created from social.
"""
class UserSocialSignupForm(SocialSignupForm):
"""
Renders the form when user has signed up using social accounts.
Default fields will be added automatically.
See UserSignupForm otherwise.
"""

View File

@ -0,0 +1,126 @@
import django.contrib.auth.models
import django.contrib.auth.validators
import django.utils.timezone
from django.db import migrations
from django.db import models
import diarios_oficiais_search_alems.users.models
class Migration(migrations.Migration):
initial = True
dependencies = [
("auth", "0012_alter_user_first_name_max_length"),
]
operations = [
migrations.CreateModel(
name="User",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("password", models.CharField(max_length=128, verbose_name="password")),
(
"last_login",
models.DateTimeField(
blank=True, null=True, verbose_name="last login",
),
),
(
"is_superuser",
models.BooleanField(
default=False,
help_text="Designates that this user has all permissions without explicitly assigning them.",
verbose_name="superuser status",
),
),(
"username",
models.CharField(
error_messages={
"unique": "A user with that username already exists."
},
help_text="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.",
max_length=150,
unique=True,
validators=[
django.contrib.auth.validators.UnicodeUsernameValidator()
],
verbose_name="username",
),
),
(
"email",
models.EmailField(
blank=True, max_length=254, verbose_name="email address",
),
),
(
"is_staff",
models.BooleanField(
default=False,
help_text="Designates whether the user can log into this admin site.",
verbose_name="staff status",
),
),
(
"is_active",
models.BooleanField(
default=True,
help_text="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.",
verbose_name="active",
),
),
(
"date_joined",
models.DateTimeField(
default=django.utils.timezone.now, verbose_name="date joined",
),
),
(
"name",
models.CharField(
blank=True, max_length=255, verbose_name="Name of User",
),
),
(
"groups",
models.ManyToManyField(
blank=True,
help_text="The groups this user belongs to. A user will get all permissions granted to each of their groups.",
related_name="user_set",
related_query_name="user",
to="auth.Group",
verbose_name="groups",
),
),
(
"user_permissions",
models.ManyToManyField(
blank=True,
help_text="Specific permissions for this user.",
related_name="user_set",
related_query_name="user",
to="auth.Permission",
verbose_name="user permissions",
),
),
],
options={
"verbose_name": "user",
"verbose_name_plural": "users",
"abstract": False,
},
managers=[
("objects", django.contrib.auth.models.UserManager()),
],
),
]

View File

@ -0,0 +1,26 @@
from django.contrib.auth.models import AbstractUser
from django.db.models import CharField
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
class User(AbstractUser):
"""
Default custom user model for Diarios Oficiais Search ALEMS.
If adding fields that need to be filled at user signup,
check forms.SignupForm and forms.SocialSignupForms accordingly.
"""
# First and last name do not cover name patterns around the globe
name = CharField(_("Name of User"), blank=True, max_length=255)
first_name = None # type: ignore[assignment]
last_name = None # type: ignore[assignment]
def get_absolute_url(self) -> str:
"""Get URL for user's detail view.
Returns:
str: URL for user detail.
"""
return reverse("users:detail", kwargs={"username": self.username})

View File

@ -0,0 +1,41 @@
from collections.abc import Sequence
from typing import Any
from factory import Faker
from factory import post_generation
from factory.django import DjangoModelFactory
from diarios_oficiais_search_alems.users.models import User
class UserFactory(DjangoModelFactory[User]):
username = Faker("user_name")
email = Faker("email")
name = Faker("name")
@post_generation
def password(self, create: bool, extracted: Sequence[Any], **kwargs): # noqa: FBT001
password = (
extracted
if extracted
else Faker(
"password",
length=42,
special_chars=True,
digits=True,
upper_case=True,
lower_case=True,
).evaluate(None, None, extra={"locale": None})
)
self.set_password(password)
@classmethod
def _after_postgeneration(cls, instance, create, results=None):
"""Save again the instance if creating and at least one hook ran."""
if create and results and not cls._meta.skip_postgeneration_save:
# Some post-generation hooks ran, and may have modified us.
instance.save()
class Meta:
model = User
django_get_or_create = ["username"]

View File

@ -0,0 +1,65 @@
import contextlib
from http import HTTPStatus
from importlib import reload
import pytest
from django.contrib import admin
from django.contrib.auth.models import AnonymousUser
from django.urls import reverse
from pytest_django.asserts import assertRedirects
from diarios_oficiais_search_alems.users.models import User
class TestUserAdmin:
def test_changelist(self, admin_client):
url = reverse("admin:users_user_changelist")
response = admin_client.get(url)
assert response.status_code == HTTPStatus.OK
def test_search(self, admin_client):
url = reverse("admin:users_user_changelist")
response = admin_client.get(url, data={"q": "test"})
assert response.status_code == HTTPStatus.OK
def test_add(self, admin_client):
url = reverse("admin:users_user_add")
response = admin_client.get(url)
assert response.status_code == HTTPStatus.OK
response = admin_client.post(
url,
data={
"username": "test",
"password1": "My_R@ndom-P@ssw0rd",
"password2": "My_R@ndom-P@ssw0rd",
},
)
assert response.status_code == HTTPStatus.FOUND
assert User.objects.filter(username="test").exists()
def test_view_user(self, admin_client):
user = User.objects.get(username="admin")
url = reverse("admin:users_user_change", kwargs={"object_id": user.pk})
response = admin_client.get(url)
assert response.status_code == HTTPStatus.OK
@pytest.fixture
def _force_allauth(self, settings):
settings.DJANGO_ADMIN_FORCE_ALLAUTH = True
# Reload the admin module to apply the setting change
import diarios_oficiais_search_alems.users.admin as users_admin
with contextlib.suppress(admin.sites.AlreadyRegistered): # type: ignore[attr-defined]
reload(users_admin)
@pytest.mark.django_db
@pytest.mark.usefixtures("_force_allauth")
def test_allauth_login(self, rf, settings):
request = rf.get("/fake-url")
request.user = AnonymousUser()
response = admin.site.login(request)
# The `admin` login view should redirect to the `allauth` login view
target_url = reverse(settings.LOGIN_URL) + "?next=" + request.path
assertRedirects(response, target_url, fetch_redirect_response=False)

View File

@ -0,0 +1,35 @@
"""Module for all Form Tests."""
from django.utils.translation import gettext_lazy as _
from diarios_oficiais_search_alems.users.forms import UserAdminCreationForm
from diarios_oficiais_search_alems.users.models import User
class TestUserAdminCreationForm:
"""
Test class for all tests related to the UserAdminCreationForm
"""
def test_username_validation_error_msg(self, user: User):
"""
Tests UserAdminCreation Form's unique validator functions correctly by testing:
1) A new user with an existing username cannot be added.
2) Only 1 error is raised by the UserCreation Form
3) The desired error message is raised
"""
# The user already exists,
# hence cannot be created.
form = UserAdminCreationForm(
{
"username": user.username,
"password1": user.password,
"password2": user.password,
},
)
assert not form.is_valid()
assert len(form.errors) == 1
assert "username" in form.errors
assert form.errors["username"][0] == _("This username has already been taken.")

View File

@ -0,0 +1,5 @@
from diarios_oficiais_search_alems.users.models import User
def test_user_get_absolute_url(user: User):
assert user.get_absolute_url() == f"/users/{user.username}/"

View File

@ -0,0 +1,22 @@
from django.urls import resolve
from django.urls import reverse
from diarios_oficiais_search_alems.users.models import User
def test_detail(user: User):
assert (
reverse("users:detail", kwargs={"username": user.username})
== f"/users/{user.username}/"
)
assert resolve(f"/users/{user.username}/").view_name == "users:detail"
def test_update():
assert reverse("users:update") == "/users/~update/"
assert resolve("/users/~update/").view_name == "users:update"
def test_redirect():
assert reverse("users:redirect") == "/users/~redirect/"
assert resolve("/users/~redirect/").view_name == "users:redirect"

View File

@ -0,0 +1,101 @@
from http import HTTPStatus
import pytest
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.models import AnonymousUser
from django.contrib.messages.middleware import MessageMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
from django.http import HttpRequest
from django.http import HttpResponseRedirect
from django.test import RequestFactory
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from diarios_oficiais_search_alems.users.forms import UserAdminChangeForm
from diarios_oficiais_search_alems.users.models import User
from diarios_oficiais_search_alems.users.tests.factories import UserFactory
from diarios_oficiais_search_alems.users.views import UserRedirectView
from diarios_oficiais_search_alems.users.views import UserUpdateView
from diarios_oficiais_search_alems.users.views import user_detail_view
pytestmark = pytest.mark.django_db
class TestUserUpdateView:
"""
TODO:
extracting view initialization code as class-scoped fixture
would be great if only pytest-django supported non-function-scoped
fixture db access -- this is a work-in-progress for now:
https://github.com/pytest-dev/pytest-django/pull/258
"""
def dummy_get_response(self, request: HttpRequest):
return None
def test_get_success_url(self, user: User, rf: RequestFactory):
view = UserUpdateView()
request = rf.get("/fake-url/")
request.user = user
view.request = request
assert view.get_success_url() == f"/users/{user.username}/"
def test_get_object(self, user: User, rf: RequestFactory):
view = UserUpdateView()
request = rf.get("/fake-url/")
request.user = user
view.request = request
assert view.get_object() == user
def test_form_valid(self, user: User, rf: RequestFactory):
view = UserUpdateView()
request = rf.get("/fake-url/")
# Add the session/message middleware to the request
SessionMiddleware(self.dummy_get_response).process_request(request)
MessageMiddleware(self.dummy_get_response).process_request(request)
request.user = user
view.request = request
# Initialize the form
form = UserAdminChangeForm()
form.cleaned_data = {}
form.instance = user
view.form_valid(form)
messages_sent = [m.message for m in messages.get_messages(request)]
assert messages_sent == [_("Information successfully updated")]
class TestUserRedirectView:
def test_get_redirect_url(self, user: User, rf: RequestFactory):
view = UserRedirectView()
request = rf.get("/fake-url")
request.user = user
view.request = request
assert view.get_redirect_url() == f"/users/{user.username}/"
class TestUserDetailView:
def test_authenticated(self, user: User, rf: RequestFactory):
request = rf.get("/fake-url/")
request.user = UserFactory()
response = user_detail_view(request, username=user.username)
assert response.status_code == HTTPStatus.OK
def test_not_authenticated(self, user: User, rf: RequestFactory):
request = rf.get("/fake-url/")
request.user = AnonymousUser()
response = user_detail_view(request, username=user.username)
login_url = reverse(settings.LOGIN_URL)
assert isinstance(response, HttpResponseRedirect)
assert response.status_code == HTTPStatus.FOUND
assert response.url == f"{login_url}?next=/fake-url/"

View File

@ -0,0 +1,12 @@
from django.urls import path
from .views import user_detail_view
from .views import user_redirect_view
from .views import user_update_view
app_name = "users"
urlpatterns = [
path("~redirect/", view=user_redirect_view, name="redirect"),
path("~update/", view=user_update_view, name="update"),
path("<str:username>/", view=user_detail_view, name="detail"),
]

View File

@ -0,0 +1,46 @@
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.db.models import QuerySet
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.views.generic import DetailView
from django.views.generic import RedirectView
from django.views.generic import UpdateView
from diarios_oficiais_search_alems.users.models import User
class UserDetailView(LoginRequiredMixin, DetailView):
model = User
slug_field = "username"
slug_url_kwarg = "username"
user_detail_view = UserDetailView.as_view()
class UserUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
model = User
fields = ["name"]
success_message = _("Information successfully updated")
def get_success_url(self) -> str:
assert self.request.user.is_authenticated # type guard
return self.request.user.get_absolute_url()
def get_object(self, queryset: QuerySet | None=None) -> User:
assert self.request.user.is_authenticated # type guard
return self.request.user
user_update_view = UserUpdateView.as_view()
class UserRedirectView(LoginRequiredMixin, RedirectView):
permanent = False
def get_redirect_url(self) -> str:
return reverse("users:detail", kwargs={"username": self.request.user.username})
user_redirect_view = UserRedirectView.as_view()

59
docker-compose.local.yml Normal file
View File

@ -0,0 +1,59 @@
version: '3.8'
volumes:
diarios_oficiais_search_alems_local_postgres_data: {}
diarios_oficiais_search_alems_local_postgres_data_backups: {}
staticfiles:
media:
services:
traefik:
image: traefik:v2.5
container_name: traefik
command:
- --api.insecure=true
- --providers.docker=true
- --providers.docker.exposedbydefault=false
- --entrypoints.web.address=:80
ports:
- "80:80"
- "8080:8080" # Dashboard (opcional)
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
django:
build:
context: .
dockerfile: ./compose/local/django/Dockerfile
image: diarios_oficiais_search_alems_local_django
container_name: diarios_oficiais_search_alems_local_django
depends_on:
- postgres
volumes:
- .:/app:z
- staticfiles:/app/staticfiles
- media:/app/media
env_file:
- ./.envs/.local/.django
- ./.envs/.local/.postgres
labels:
- "traefik.enable=true"
- "traefik.http.routers.django.rule=Host(`192.168.235.234`)"
- "traefik.http.routers.django.entrypoints=web"
- "traefik.http.services.django.loadbalancer.server.port=8000"
ports:
- '8000:8000'
command: /start
postgres:
build:
context: .
dockerfile: ./compose/production/postgres/Dockerfile
image: diarios_oficiais_search_alems_production_postgres
container_name: diarios_oficiais_search_alems_local_postgres
volumes:
- diarios_oficiais_search_alems_local_postgres_data:/var/lib/postgresql/data
- diarios_oficiais_search_alems_local_postgres_data_backups:/backups
env_file:
- ./.envs/.local/.postgres

View File

@ -0,0 +1,62 @@
volumes:
production_postgres_data: {}
production_postgres_data_backups: {}
production_traefik: {}
production_django_media: {}
services:
django:
build:
context: .
dockerfile: ./compose/production/django/Dockerfile
image: diarios_oficiais_search_alems_production_django
volumes:
- production_django_media:/app/diarios_oficiais_search_alems/media
depends_on:
- postgres
- redis
env_file:
- ./.envs/.production/.django
- ./.envs/.production/.postgres
command: /start
postgres:
build:
context: .
dockerfile: ./compose/production/postgres/Dockerfile
image: diarios_oficiais_search_alems_production_postgres
volumes:
- production_postgres_data:/var/lib/postgresql/data
- production_postgres_data_backups:/backups
env_file:
- ./.envs/.production/.postgres
traefik:
build:
context: .
dockerfile: ./compose/production/traefik/Dockerfile
image: diarios_oficiais_search_alems_production_traefik
depends_on:
- django
volumes:
- production_traefik:/etc/traefik/acme
ports:
- '0.0.0.0:80:80'
- '0.0.0.0:443:443'
redis:
image: docker.io/redis:6
nginx:
build:
context: .
dockerfile: ./compose/production/nginx/Dockerfile
image: diarios_oficiais_search_alems_production_nginx
depends_on:
- django
volumes:
- production_django_media:/usr/share/nginx/media:ro

32
locale/README.md Normal file
View File

@ -0,0 +1,32 @@
# Translations
Start by configuring the `LANGUAGES` settings in `base.py`, by uncommenting languages you are willing to support. Then, translation strings will be placed in this folder when running:
```bash
docker compose -f docker-compose.local.yml run --rm django python manage.py makemessages --all --no-location
```
This should generate `django.po` (stands for Portable Object) files under each locale `<locale name>/LC_MESSAGES/django.po`. Each translatable string in the codebase is collected with its `msgid` and need to be translated as `msgstr`, for example:
```po
msgid "users"
msgstr "utilisateurs"
```
Once all translations are done, they need to be compiled into `.mo` files (stands for Machine Object), which are the actual binary files used by the application:
```bash
docker compose -f docker-compose.local.yml run --rm django python manage.py compilemessages
```
Note that the `.po` files are NOT used by the application directly, so if the `.mo` files are out of date, the content won't appear as translated even if the `.po` files are up-to-date.
## Production
The production image runs `compilemessages` automatically at build time, so as long as your translated source files (PO) are up-to-date, you're good to go.
## Add a new language
1. Update the [`LANGUAGES` setting](https://docs.djangoproject.com/en/stable/ref/settings/#std-setting-LANGUAGES) to your project's base settings.
2. Create the locale folder for the language next to this file, e.g. `fr_FR` for French. Make sure the case is correct.
3. Run `makemessages` (as instructed above) to generate the PO files for the new language.

View File

@ -0,0 +1,12 @@
# Translations for the Diarios Oficiais Search ALEMS project
# Copyright (C) 2025 Antonio Roberto
# Antonio Roberto <antoniorobertojunior96@gmail.com>, 2025.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: 0.1.0\n"
"Language: en-US\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

View File

@ -0,0 +1,335 @@
# Translations for the Diarios Oficiais Search ALEMS project
# Copyright (C) 2025 Antonio Roberto
# Antonio Roberto <antoniorobertojunior96@gmail.com>, 2025.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: 0.1.0\n"
"Language: fr-FR\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
#: diarios_oficiais_search_alems/templates/account/account_inactive.html:5
#: diarios_oficiais_search_alems/templates/account/account_inactive.html:8
msgid "Account Inactive"
msgstr "Compte inactif"
#: diarios_oficiais_search_alems/templates/account/account_inactive.html:10
msgid "This account is inactive."
msgstr "Ce compte est inactif."
#: diarios_oficiais_search_alems/templates/account/email.html:7
msgid "Account"
msgstr "Compte"
#: diarios_oficiais_search_alems/templates/account/email.html:10
msgid "E-mail Addresses"
msgstr "Adresses e-mail"
#: diarios_oficiais_search_alems/templates/account/email.html:13
msgid "The following e-mail addresses are associated with your account:"
msgstr "Les adresses e-mail suivantes sont associées à votre compte :"
#: diarios_oficiais_search_alems/templates/account/email.html:27
msgid "Verified"
msgstr "Vérifié"
#: diarios_oficiais_search_alems/templates/account/email.html:29
msgid "Unverified"
msgstr "Non vérifié"
#: diarios_oficiais_search_alems/templates/account/email.html:31
msgid "Primary"
msgstr "Primaire"
#: diarios_oficiais_search_alems/templates/account/email.html:37
msgid "Make Primary"
msgstr "Changer Primaire"
#: diarios_oficiais_search_alems/templates/account/email.html:38
msgid "Re-send Verification"
msgstr "Renvoyer vérification"
#: diarios_oficiais_search_alems/templates/account/email.html:39
msgid "Remove"
msgstr "Supprimer"
#: diarios_oficiais_search_alems/templates/account/email.html:46
msgid "Warning:"
msgstr "Avertissement:"
#: diarios_oficiais_search_alems/templates/account/email.html:46
msgid ""
"You currently do not have any e-mail address set up. You should really add "
"an e-mail address so you can receive notifications, reset your password, etc."
msgstr ""
"Vous n'avez actuellement aucune adresse e-mail configurée. Vous devriez ajouter "
"une adresse e-mail pour reçevoir des notifications, réinitialiser votre mot "
"de passe, etc."
#: diarios_oficiais_search_alems/templates/account/email.html:51
msgid "Add E-mail Address"
msgstr "Ajouter une adresse e-mail"
#: diarios_oficiais_search_alems/templates/account/email.html:56
msgid "Add E-mail"
msgstr "Ajouter e-mail"
#: diarios_oficiais_search_alems/templates/account/email.html:66
msgid "Do you really want to remove the selected e-mail address?"
msgstr "Voulez-vous vraiment supprimer l'adresse e-mail sélectionnée ?"
#: diarios_oficiais_search_alems/templates/account/email_confirm.html:6
#: diarios_oficiais_search_alems/templates/account/email_confirm.html:10
msgid "Confirm E-mail Address"
msgstr "Confirmez votre adresse email"
#: diarios_oficiais_search_alems/templates/account/email_confirm.html:16
#, python-format
msgid ""
"Please confirm that <a href=\"mailto:%(email)s\">%(email)s</a> is an e-mail "
"address for user %(user_display)s."
msgstr ""
"Veuillez confirmer que <a href=\"mailto:%(email)s\">%(email)s</a> est un e-mail "
"adresse de l'utilisateur %(user_display)s."
#: diarios_oficiais_search_alems/templates/account/email_confirm.html:20
msgid "Confirm"
msgstr "Confirm"
#: diarios_oficiais_search_alems/templates/account/email_confirm.html:27
#, python-format
msgid ""
"This e-mail confirmation link expired or is invalid. Please <a href="
"\"%(email_url)s\">issue a new e-mail confirmation request</a>."
msgstr ""
"Ce lien de confirmation par e-mail a expiré ou n'est pas valide. Veuillez"
"<a href=\"%(email_url)s\">émettre une nouvelle demande de confirmation "
"par e-mail</a>."
#: diarios_oficiais_search_alems/templates/account/login.html:7
#: diarios_oficiais_search_alems/templates/account/login.html:11
#: diarios_oficiais_search_alems/templates/account/login.html:56
#: diarios_oficiais_search_alems/templates/base.html:72
msgid "Sign In"
msgstr "S'identifier"
#: diarios_oficiais_search_alems/templates/account/login.html:17
msgid "Please sign in with one of your existing third party accounts:"
msgstr "Veuillez vous connecter avec l'un de vos comptes tiers existants :"
#: diarios_oficiais_search_alems/templates/account/login.html:19
#, python-format
msgid ""
"Or, <a href=\"%(signup_url)s\">sign up</a> for a %(site_name)s account and "
"sign in below:"
msgstr ""
"Ou, <a href=\"%(signup_url)s\">créez</a> un compte %(site_name)s et "
"connectez-vous ci-dessous :"
#: diarios_oficiais_search_alems/templates/account/login.html:32
msgid "or"
msgstr "ou"
#: diarios_oficiais_search_alems/templates/account/login.html:41
#, python-format
msgid ""
"If you have not created an account yet, then please <a href=\"%(signup_url)s"
"\">sign up</a> first."
msgstr ""
"Si vous n'avez pas encore créé de compte, veuillez d'abord <a href=\"%(signup_url)s"
"\">vous inscrire</a>."
#: diarios_oficiais_search_alems/templates/account/login.html:55
msgid "Forgot Password?"
msgstr "Mot de passe oublié?"
#: diarios_oficiais_search_alems/templates/account/logout.html:5
#: diarios_oficiais_search_alems/templates/account/logout.html:8
#: diarios_oficiais_search_alems/templates/account/logout.html:17
#: diarios_oficiais_search_alems/templates/base.html:61
msgid "Sign Out"
msgstr "Se déconnecter"
#: diarios_oficiais_search_alems/templates/account/logout.html:10
msgid "Are you sure you want to sign out?"
msgstr "Êtes-vous certain de vouloir vous déconnecter?"
#: diarios_oficiais_search_alems/templates/account/password_change.html:6
#: diarios_oficiais_search_alems/templates/account/password_change.html:9
#: diarios_oficiais_search_alems/templates/account/password_change.html:14
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key.html:5
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key.html:8
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key_done.html:4
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key_done.html:7
msgid "Change Password"
msgstr "Changer le mot de passe"
#: diarios_oficiais_search_alems/templates/account/password_reset.html:7
#: diarios_oficiais_search_alems/templates/account/password_reset.html:11
#: diarios_oficiais_search_alems/templates/account/password_reset_done.html:6
#: diarios_oficiais_search_alems/templates/account/password_reset_done.html:9
msgid "Password Reset"
msgstr "Réinitialisation du mot de passe"
#: diarios_oficiais_search_alems/templates/account/password_reset.html:16
msgid ""
"Forgotten your password? Enter your e-mail address below, and we'll send you "
"an e-mail allowing you to reset it."
msgstr ""
"Mot de passe oublié? Entrez votre adresse e-mail ci-dessous, et nous vous "
"enverrons un e-mail vous permettant de le réinitialiser."
#: diarios_oficiais_search_alems/templates/account/password_reset.html:21
msgid "Reset My Password"
msgstr "Réinitialiser mon mot de passe"
#: diarios_oficiais_search_alems/templates/account/password_reset.html:24
msgid "Please contact us if you have any trouble resetting your password."
msgstr ""
"Veuillez nous contacter si vous rencontrez des difficultés pour réinitialiser"
"votre mot de passe."
#: diarios_oficiais_search_alems/templates/account/password_reset_done.html:15
msgid ""
"We have sent you an e-mail. Please contact us if you do not receive it "
"within a few minutes."
msgstr ""
"Nous vous avons envoyé un e-mail. Veuillez nous contacter si vous ne le "
"recevez pas d'ici quelques minutes."
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key.html:8
msgid "Bad Token"
msgstr "Token Invalide"
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key.html:12
#, python-format
msgid ""
"The password reset link was invalid, possibly because it has already been "
"used. Please request a <a href=\"%(passwd_reset_url)s\">new password reset</"
"a>."
msgstr ""
"Le lien de réinitialisation du mot de passe n'était pas valide, peut-être parce "
"qu'il a déjà été utilisé. Veuillez faire une <a href=\"%(passwd_reset_url)s\"> "
"nouvelle demande de réinitialisation de mot de passe</a>."
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key.html:18
msgid "change password"
msgstr "changer le mot de passe"
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key.html:21
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key_done.html:8
msgid "Your password is now changed."
msgstr "Votre mot de passe est maintenant modifié."
#: diarios_oficiais_search_alems/templates/account/password_set.html:6
#: diarios_oficiais_search_alems/templates/account/password_set.html:9
#: diarios_oficiais_search_alems/templates/account/password_set.html:14
msgid "Set Password"
msgstr "Définir le mot de passe"
#: diarios_oficiais_search_alems/templates/account/signup.html:6
msgid "Signup"
msgstr "S'inscrire"
#: diarios_oficiais_search_alems/templates/account/signup.html:9
#: diarios_oficiais_search_alems/templates/account/signup.html:19
#: diarios_oficiais_search_alems/templates/base.html:67
msgid "Sign Up"
msgstr "S'inscrire"
#: diarios_oficiais_search_alems/templates/account/signup.html:11
#, python-format
msgid ""
"Already have an account? Then please <a href=\"%(login_url)s\">sign in</a>."
msgstr ""
"Vous avez déjà un compte? Alors veuillez <a href=\"%(login_url)s\">vous connecter</a>."
#: diarios_oficiais_search_alems/templates/account/signup_closed.html:5
#: diarios_oficiais_search_alems/templates/account/signup_closed.html:8
msgid "Sign Up Closed"
msgstr "Inscriptions closes"
#: diarios_oficiais_search_alems/templates/account/signup_closed.html:10
msgid "We are sorry, but the sign up is currently closed."
msgstr "Désolé, mais l'inscription est actuellement fermée."
#: diarios_oficiais_search_alems/templates/account/verification_sent.html:5
#: diarios_oficiais_search_alems/templates/account/verification_sent.html:8
#: diarios_oficiais_search_alems/templates/account/verified_email_required.html:5
#: diarios_oficiais_search_alems/templates/account/verified_email_required.html:8
msgid "Verify Your E-mail Address"
msgstr "Vérifiez votre adresse e-mail"
#: diarios_oficiais_search_alems/templates/account/verification_sent.html:10
msgid ""
"We have sent an e-mail to you for verification. Follow the link provided to "
"finalize the signup process. Please contact us if you do not receive it "
"within a few minutes."
msgstr "Nous vous avons envoyé un e-mail pour vérification. Suivez le lien fourni "
"pour finalisez le processus d'inscription. Veuillez nous contacter si vous ne le "
"recevez pas d'ici quelques minutes."
#: diarios_oficiais_search_alems/templates/account/verified_email_required.html:12
msgid ""
"This part of the site requires us to verify that\n"
"you are who you claim to be. For this purpose, we require that you\n"
"verify ownership of your e-mail address. "
msgstr ""
"Cette partie du site nous oblige à vérifier que\n"
"vous êtes qui vous prétendez être. Nous vous demandons donc de\n"
"vérifier la propriété de votre adresse e-mail."
#: diarios_oficiais_search_alems/templates/account/verified_email_required.html:16
msgid ""
"We have sent an e-mail to you for\n"
"verification. Please click on the link inside this e-mail. Please\n"
"contact us if you do not receive it within a few minutes."
msgstr ""
"Nous vous avons envoyé un e-mail pour\n"
"vérification. Veuillez cliquer sur le lien contenu dans cet e-mail. Veuillez nous\n"
"contacter si vous ne le recevez pas d'ici quelques minutes."
#: diarios_oficiais_search_alems/templates/account/verified_email_required.html:20
#, python-format
msgid ""
"<strong>Note:</strong> you can still <a href=\"%(email_url)s\">change your e-"
"mail address</a>."
msgstr ""
"<strong>Remarque :</strong> vous pouvez toujours <a href=\"%(email_url)s\">changer votre e-"
"adresse e-mail</a>."
#: diarios_oficiais_search_alems/templates/base.html:57
msgid "My Profile"
msgstr "Mon Profil"
#: diarios_oficiais_search_alems/users/admin.py:17
msgid "Personal info"
msgstr "Personal info"
#: diarios_oficiais_search_alems/users/admin.py:19
msgid "Permissions"
msgstr "Permissions"
#: diarios_oficiais_search_alems/users/admin.py:30
msgid "Important dates"
msgstr "Dates importantes"
#: diarios_oficiais_search_alems/users/apps.py:7
msgid "Users"
msgstr "Utilisateurs"
#: diarios_oficiais_search_alems/users/forms.py:24
#: diarios_oficiais_search_alems/users/tests/test_forms.py:36
msgid "This username has already been taken."
msgstr "Ce nom d'utilisateur est déjà pris."
#: diarios_oficiais_search_alems/users/models.py:15
msgid "Name of User"
msgstr "Nom de l'utilisateur"
#: diarios_oficiais_search_alems/users/views.py:23
msgid "Information successfully updated"
msgstr "Informations mises à jour avec succès"

View File

@ -0,0 +1,315 @@
# Translations for the Diarios Oficiais Search ALEMS project
# Copyright (C) 2025 Antonio Roberto
# Antonio Roberto <antoniorobertojunior96@gmail.com>, 2025.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: 0.1.0\n"
"Language: pt-BR\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
#: diarios_oficiais_search_alems/templates/account/account_inactive.html:5
#: diarios_oficiais_search_alems/templates/account/account_inactive.html:8
msgid "Account Inactive"
msgstr "Conta Inativa"
#: diarios_oficiais_search_alems/templates/account/account_inactive.html:10
msgid "This account is inactive."
msgstr "Esta conta está inativa."
#: diarios_oficiais_search_alems/templates/account/email.html:7
msgid "Account"
msgstr "Conta"
#: diarios_oficiais_search_alems/templates/account/email.html:10
msgid "E-mail Addresses"
msgstr "Endereços de E-mail"
#: diarios_oficiais_search_alems/templates/account/email.html:13
msgid "The following e-mail addresses are associated with your account:"
msgstr "Os seguintes endereços de e-mail estão associados à sua conta:"
#: diarios_oficiais_search_alems/templates/account/email.html:27
msgid "Verified"
msgstr "Verificado"
#: diarios_oficiais_search_alems/templates/account/email.html:29
msgid "Unverified"
msgstr "Não verificado"
#: diarios_oficiais_search_alems/templates/account/email.html:31
msgid "Primary"
msgstr "Primário"
#: diarios_oficiais_search_alems/templates/account/email.html:37
msgid "Make Primary"
msgstr "Tornar Primário"
#: diarios_oficiais_search_alems/templates/account/email.html:38
msgid "Re-send Verification"
msgstr "Reenviar verificação"
#: diarios_oficiais_search_alems/templates/account/email.html:39
msgid "Remove"
msgstr "Remover"
#: diarios_oficiais_search_alems/templates/account/email.html:46
msgid "Warning:"
msgstr "Aviso:"
#: diarios_oficiais_search_alems/templates/account/email.html:46
msgid ""
"You currently do not have any e-mail address set up. You should really add "
"an e-mail address so you can receive notifications, reset your password, etc."
msgstr ""
"No momento, você não tem nenhum endereço de e-mail configurado. Você "
"realmente deve adicionar um endereço de e-mail para receber notificações, "
"redefinir sua senha etc."
#: diarios_oficiais_search_alems/templates/account/email.html:51
msgid "Add E-mail Address"
msgstr "Adicionar Endereço de E-mail"
#: diarios_oficiais_search_alems/templates/account/email.html:56
msgid "Add E-mail"
msgstr "Adicionar E-mail"
#: diarios_oficiais_search_alems/templates/account/email.html:66
msgid "Do you really want to remove the selected e-mail address?"
msgstr "Você realmente deseja remover o endereço de e-mail selecionado?"
#: diarios_oficiais_search_alems/templates/account/email_confirm.html:6
#: diarios_oficiais_search_alems/templates/account/email_confirm.html:10
msgid "Confirm E-mail Address"
msgstr "Confirme o endereço de e-mail"
#: diarios_oficiais_search_alems/templates/account/email_confirm.html:16
#, python-format
msgid ""
"Please confirm that <a href=\"mailto:%(email)s\">%(email)s</a> is an e-mail "
"address for user %(user_display)s."
msgstr ""
"Confirme se <a href=\"mailto:%(email)s\">%(email)s</a> é um endereço de "
"e-mail do usuário %(user_display)s."
#: diarios_oficiais_search_alems/templates/account/email_confirm.html:20
msgid "Confirm"
msgstr "Confirmar"
#: diarios_oficiais_search_alems/templates/account/email_confirm.html:27
#, python-format
msgid ""
"This e-mail confirmation link expired or is invalid. Please <a href="
"\"%(email_url)s\">issue a new e-mail confirmation request</a>."
msgstr "Este link de confirmação de e-mail expirou ou é inválido. "
"Por favor, <a href=\"%(email_url)s\">emita um novo pedido de confirmação por e-mail</a>."
#: diarios_oficiais_search_alems/templates/account/login.html:7
#: diarios_oficiais_search_alems/templates/account/login.html:11
#: diarios_oficiais_search_alems/templates/account/login.html:56
#: diarios_oficiais_search_alems/templates/base.html:72
msgid "Sign In"
msgstr "Entrar"
#: diarios_oficiais_search_alems/templates/account/login.html:17
msgid "Please sign in with one of your existing third party accounts:"
msgstr "Faça login com uma de suas contas de terceiros existentes:"
#: diarios_oficiais_search_alems/templates/account/login.html:19
#, python-format
msgid ""
"Or, <a href=\"%(signup_url)s\">sign up</a> for a %(site_name)s account and "
"sign in below:"
msgstr "Ou, <a href=\"%(signup_url)s\">cadastre-se</a> para uma conta em %(site_name)s e entre abaixo:"
#: diarios_oficiais_search_alems/templates/account/login.html:32
msgid "or"
msgstr "ou"
#: diarios_oficiais_search_alems/templates/account/login.html:41
#, python-format
msgid ""
"If you have not created an account yet, then please <a href=\"%(signup_url)s"
"\">sign up</a> first."
msgstr "Se você ainda não criou uma conta, <a href=\"%(signup_url)s"
"\">registre-se primeiro</a>."
#: diarios_oficiais_search_alems/templates/account/login.html:55
msgid "Forgot Password?"
msgstr "Esqueceu sua senha?"
#: diarios_oficiais_search_alems/templates/account/logout.html:5
#: diarios_oficiais_search_alems/templates/account/logout.html:8
#: diarios_oficiais_search_alems/templates/account/logout.html:17
#: diarios_oficiais_search_alems/templates/base.html:61
msgid "Sign Out"
msgstr "Sair"
#: diarios_oficiais_search_alems/templates/account/logout.html:10
msgid "Are you sure you want to sign out?"
msgstr "Você tem certeza que deseja sair?"
#: diarios_oficiais_search_alems/templates/account/password_change.html:6
#: diarios_oficiais_search_alems/templates/account/password_change.html:9
#: diarios_oficiais_search_alems/templates/account/password_change.html:14
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key.html:5
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key.html:8
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key_done.html:4
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key_done.html:7
msgid "Change Password"
msgstr "Alterar Senha"
#: diarios_oficiais_search_alems/templates/account/password_reset.html:7
#: diarios_oficiais_search_alems/templates/account/password_reset.html:11
#: diarios_oficiais_search_alems/templates/account/password_reset_done.html:6
#: diarios_oficiais_search_alems/templates/account/password_reset_done.html:9
msgid "Password Reset"
msgstr "Redefinição de senha"
#: diarios_oficiais_search_alems/templates/account/password_reset.html:16
msgid ""
"Forgotten your password? Enter your e-mail address below, and we'll send you "
"an e-mail allowing you to reset it."
msgstr "Esqueceu sua senha? Digite seu endereço de e-mail abaixo e enviaremos um e-mail permitindo que você o redefina."
#: diarios_oficiais_search_alems/templates/account/password_reset.html:21
msgid "Reset My Password"
msgstr "Redefinir minha senha"
#: diarios_oficiais_search_alems/templates/account/password_reset.html:24
msgid "Please contact us if you have any trouble resetting your password."
msgstr "Entre em contato conosco se tiver algum problema para redefinir sua senha."
#: diarios_oficiais_search_alems/templates/account/password_reset_done.html:15
msgid ""
"We have sent you an e-mail. Please contact us if you do not receive it "
"within a few minutes."
msgstr "Enviamos um e-mail para você. Entre em contato conosco se você não recebê-lo dentro de alguns minutos."
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key.html:8
msgid "Bad Token"
msgstr "Token Inválido"
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key.html:12
#, python-format
msgid ""
"The password reset link was invalid, possibly because it has already been "
"used. Please request a <a href=\"%(passwd_reset_url)s\">new password reset</"
"a>."
msgstr "O link de redefinição de senha era inválido, possivelmente porque já foi usado. "
"<a href=\"%(passwd_reset_url)s\">Solicite uma nova redefinição de senha</a>."
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key.html:18
msgid "change password"
msgstr "alterar senha"
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key.html:21
#: diarios_oficiais_search_alems/templates/account/password_reset_from_key_done.html:8
msgid "Your password is now changed."
msgstr "Sua senha agora foi alterada."
#: diarios_oficiais_search_alems/templates/account/password_set.html:6
#: diarios_oficiais_search_alems/templates/account/password_set.html:9
#: diarios_oficiais_search_alems/templates/account/password_set.html:14
msgid "Set Password"
msgstr "Definir Senha"
#: diarios_oficiais_search_alems/templates/account/signup.html:6
msgid "Signup"
msgstr "Cadastro"
#: diarios_oficiais_search_alems/templates/account/signup.html:9
#: diarios_oficiais_search_alems/templates/account/signup.html:19
#: diarios_oficiais_search_alems/templates/base.html:67
msgid "Sign Up"
msgstr "Cadastro"
#: diarios_oficiais_search_alems/templates/account/signup.html:11
#, python-format
msgid ""
"Already have an account? Then please <a href=\"%(login_url)s\">sign in</a>."
msgstr "já tem uma conta? Então, por favor, faça <a href=\"%(login_url)s\">login</a>."
#: diarios_oficiais_search_alems/templates/account/signup_closed.html:5
#: diarios_oficiais_search_alems/templates/account/signup_closed.html:8
msgid "Sign Up Closed"
msgstr "Inscrições encerradas"
#: diarios_oficiais_search_alems/templates/account/signup_closed.html:10
msgid "We are sorry, but the sign up is currently closed."
msgstr "Lamentamos, mas as inscrições estão encerradas no momento."
#: diarios_oficiais_search_alems/templates/account/verification_sent.html:5
#: diarios_oficiais_search_alems/templates/account/verification_sent.html:8
#: diarios_oficiais_search_alems/templates/account/verified_email_required.html:5
#: diarios_oficiais_search_alems/templates/account/verified_email_required.html:8
msgid "Verify Your E-mail Address"
msgstr "Verifique seu endereço de e-mail"
#: diarios_oficiais_search_alems/templates/account/verification_sent.html:10
msgid ""
"We have sent an e-mail to you for verification. Follow the link provided to "
"finalize the signup process. Please contact us if you do not receive it "
"within a few minutes."
msgstr "Enviamos um e-mail para você para verificação. Siga o link fornecido para finalizar o processo de inscrição. Entre em contato conosco se você não recebê-lo dentro de alguns minutos."
#: diarios_oficiais_search_alems/templates/account/verified_email_required.html:12
msgid ""
"This part of the site requires us to verify that\n"
"you are who you claim to be. For this purpose, we require that you\n"
"verify ownership of your e-mail address. "
msgstr "Esta parte do site exige que verifiquemos se você é quem afirma ser.\n"
"Para esse fim, exigimos que você verifique a propriedade\n"
"do seu endereço de e-mail."
#: diarios_oficiais_search_alems/templates/account/verified_email_required.html:16
msgid ""
"We have sent an e-mail to you for\n"
"verification. Please click on the link inside this e-mail. Please\n"
"contact us if you do not receive it within a few minutes."
msgstr "Enviamos um e-mail para você para verificação.\n"
"Por favor, clique no link dentro deste e-mail.\n"
"Entre em contato conosco se você não recebê-lo dentro de alguns minutos."
#: diarios_oficiais_search_alems/templates/account/verified_email_required.html:20
#, python-format
msgid ""
"<strong>Note:</strong> you can still <a href=\"%(email_url)s\">change your e-"
"mail address</a>."
msgstr "<strong>Nota</strong>: você ainda pode <a href=\"%(email_url)s\">alterar seu endereço de e-mail</a>."
#: diarios_oficiais_search_alems/templates/base.html:57
msgid "My Profile"
msgstr "Meu perfil"
#: diarios_oficiais_search_alems/users/admin.py:17
msgid "Personal info"
msgstr "Informação pessoal"
#: diarios_oficiais_search_alems/users/admin.py:19
msgid "Permissions"
msgstr "Permissões"
#: diarios_oficiais_search_alems/users/admin.py:30
msgid "Important dates"
msgstr "Datas importantes"
#: diarios_oficiais_search_alems/users/apps.py:7
msgid "Users"
msgstr "Usuários"
#: diarios_oficiais_search_alems/users/forms.py:24
#: diarios_oficiais_search_alems/users/tests/test_forms.py:36
msgid "This username has already been taken."
msgstr "Este nome de usuário já foi usado."
#: diarios_oficiais_search_alems/users/models.py:15
msgid "Name of User"
msgstr "Nome do Usuário"
#: diarios_oficiais_search_alems/users/views.py:23
msgid "Information successfully updated"
msgstr "Informação atualizada com sucesso"

30
manage.py Executable file
View File

@ -0,0 +1,30 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
from pathlib import Path
def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError( # noqa: TRY003
"Couldn't import Django. Are you sure it's installed and " # noqa: EM101
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?",
) from exc
# This allows easy placement of apps within the interior
# diarios_oficiais_search_alems directory.
current_path = Path(__file__).parent.resolve()
sys.path.append(str(current_path / "diarios_oficiais_search_alems"))
execute_from_command_line(sys.argv)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,25 @@
from collections.abc import Sequence
from pathlib import Path
BASE_DIR = Path(__file__).parent.resolve()
PRODUCTION_DOTENVS_DIR = BASE_DIR / ".envs" / ".production"
PRODUCTION_DOTENV_FILES = [
PRODUCTION_DOTENVS_DIR / ".django",
PRODUCTION_DOTENVS_DIR / ".postgres",
]
DOTENV_FILE = BASE_DIR / ".env"
def merge(
output_file: Path,
files_to_merge: Sequence[Path],
) -> None:
merged_content = ""
for merge_file in files_to_merge:
merged_content += merge_file.read_text()
merged_content += "\n"
output_file.write_text(merged_content)
if __name__ == "__main__":
merge(DOTENV_FILE, PRODUCTION_DOTENV_FILES)

136
pyproject.toml Normal file
View File

@ -0,0 +1,136 @@
# ==== pytest ====
[tool.pytest.ini_options]
minversion = "6.0"
addopts = "--ds=config.settings.test --reuse-db --import-mode=importlib"
python_files = [
"tests.py",
"test_*.py",
]
# ==== Coverage ====
[tool.coverage.run]
include = ["diarios_oficiais_search_alems/**"]
omit = ["*/migrations/*", "*/tests/*"]
plugins = ["django_coverage_plugin"]
# ==== mypy ====
[tool.mypy]
python_version = "3.12"
check_untyped_defs = true
ignore_missing_imports = true
warn_unused_ignores = true
warn_redundant_casts = true
warn_unused_configs = true
plugins = [
"mypy_django_plugin.main",
]
[[tool.mypy.overrides]]
# Django migrations should not produce any errors:
module = "*.migrations.*"
ignore_errors = true
[tool.django-stubs]
django_settings_module = "config.settings.test"
# ==== djLint ====
[tool.djlint]
blank_line_after_tag = "load,extends"
close_void_tags = true
format_css = true
format_js = true
# TODO: remove T002 when fixed https://github.com/djlint/djLint/issues/687
ignore = "H006,H030,H031,T002"
include = "H017,H035"
indent = 2
max_line_length = 119
profile = "django"
[tool.djlint.css]
indent_size = 2
[tool.djlint.js]
indent_size = 2
[tool.ruff]
target-version = "py312"
# Exclude a variety of commonly ignored directories.
extend-exclude = [
"*/migrations/*.py",
"staticfiles/*",
]
[tool.ruff.lint]
select = [
"F",
"E",
"W",
"C90",
"I",
"N",
"UP",
"YTT",
# "ANN", # flake8-annotations: we should support this in the future but 100+ errors atm
"ASYNC",
"S",
"BLE",
"FBT",
"B",
"A",
"COM",
"C4",
"DTZ",
"T10",
"DJ",
"EM",
"EXE",
"FA",
'ISC',
"ICN",
"G",
'INP',
'PIE',
"T20",
'PYI',
'PT',
"Q",
"RSE",
"RET",
"SLF",
"SLOT",
"SIM",
"TID",
"TC",
"INT",
# "ARG", # Unused function argument
"PTH",
"ERA",
"PD",
"PGH",
"PL",
"TRY",
"FLY",
# "NPY",
# "AIR",
"PERF",
# "FURB",
# "LOG",
"RUF",
]
ignore = [
"S101", # Use of assert detected https://docs.astral.sh/ruff/rules/assert/
"RUF012", # Mutable class attributes should be annotated with `typing.ClassVar`
"SIM102", # sometimes it's better to nest
"UP038", # Checks for uses of isinstance/issubclass that take a tuple
# of types for comparison.
# Deactivated because it can make the code slow:
# https://github.com/astral-sh/ruff/issues/7871
]
# The fixes in extend-unsafe-fixes will require
# provide the `--unsafe-fixes` flag when fixing.
extend-unsafe-fixes = [
"UP038",
]
[tool.ruff.lint.isort]
force-single-line = true

20
requirements/base.txt Normal file
View File

@ -0,0 +1,20 @@
python-slugify==8.0.4 # https://github.com/un33k/python-slugify
Pillow==11.2.1 # pyup: != 11.2.0 # https://github.com/python-pillow/Pillow
rcssmin==1.1.2 # https://github.com/ndparker/rcssmin
argon2-cffi==25.1.0 # https://github.com/hynek/argon2_cffi
whitenoise==6.9.0 # https://github.com/evansd/whitenoise
redis==6.2.0 # https://github.com/redis/redis-py
hiredis==3.2.1 # https://github.com/redis/hiredis-py
uvicorn[standard]==0.34.3 # https://github.com/encode/uvicorn
uvicorn-worker==0.3.0 # https://github.com/Kludex/uvicorn-worker
# Django
# ------------------------------------------------------------------------------
django==5.1.11 # pyup: < 5.2 # https://www.djangoproject.com/
django-environ==0.12.0 # https://github.com/joke2k/django-environ
django-model-utils==5.0.0 # https://github.com/jazzband/django-model-utils
django-allauth[mfa]==65.9.0 # https://github.com/pennersr/django-allauth
django-crispy-forms==2.4 # https://github.com/django-crispy-forms/django-crispy-forms
crispy-bootstrap5==2025.6 # https://github.com/django-crispy-forms/crispy-bootstrap5
django-compressor==4.5.1 # https://github.com/django-compressor/django-compressor
django-redis==5.4.0 # https://github.com/jazzband/django-redis

Some files were not shown because too many files have changed in this diff Show More