diff --git a/.env b/.env new file mode 100644 index 0000000000000000000000000000000000000000..1d7417281327d15536bf3ce8ed4b323b0ae8996d --- /dev/null +++ b/.env @@ -0,0 +1,41 @@ +# Geral +COMPOSE_PROJECT_NAME=encurtador +PYTHONUNBUFFERED=1 +PYTHONDONTWRITEBYTECODE=1 + +# Django +DJANGO_SETTINGS_MODULE=linkshortner.settings # ajuste conforme seu projeto +DJANGO_SECRET_KEY=@Gqjmxb7kyq2I9K9rFN46WAE98x# +DJANGO_DEBUG=1 +DJANGO_ALLOWED_HOSTS=* +DJANGO_PORT=8000 + +# Timezone/locale +DJANGO_TIME_ZONE=America/Sao_Paulo +DJANGO_LANGUAGE_CODE=pt-br + +# postgres +POSTGRES_DB=encurtador +POSTGRES_USER=encurtador +POSTGRES_PASSWORD=encurtador +POSTGRES_HOST=db +POSTGRES_PORT=5432 + +# Django DB URL (útil p/ dj-database-url ou similar) +DATABASE_URL=postgres://encurtador:encurtador@db:5432/encurtador + +# Superuser opcional (criado no entrypoint se todos estiverem setados) +DJANGO_SUPERUSER_USERNAME=admin +DJANGO_SUPERUSER_EMAIL=admin@example.com +DJANGO_SUPERUSER_PASSWORD=admin123 + +# DRF +DRF_DEFAULT_PAGE_SIZE=20 + +# Swagger/OpenAPI +DOCS_ENABLED=True + +#libera acesso a api por origns pré-definidas. aqui vamos deixar em False e liberar apenas localhost:8001, porque esta em desenvolvimento. +CORS_ALLOW_ALL=False +CORS_ALLOWED_ORIGINS=http://localhost:8001,http://127.0.0.1:8001 +CSRF_TRUSTED_ORIGINS=http://localhost:8001,http://127.0.0.1:8001 \ No newline at end of file diff --git a/.gitignore b/.gitignore index 934d06989706437b62823a97acc9e83db774bdd9..0bb56b3449e7560606f932815cb04f9ab66e0b2f 100644 --- a/.gitignore +++ b/.gitignore @@ -132,7 +132,7 @@ celerybeat.pid *.sage.py # Environments -.env + .venv env/ venv/ diff --git a/README.md b/README.md index daafdde818e36942fb0afd1f9387fd64880eb09a..9a001de598abbf6305068f42b6fb84203db45991 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,14 @@ -# link-shortner - - - -## Getting started - -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: - -``` -cd existing_repo -git remote add origin https://git.rarolabs.com.br/raphael.mansur/link-shortner.git -git branch -M main -git push -uf origin main -``` - -## Integrate with your tools - -- [ ] [Set up project integrations](https://git.rarolabs.com.br/raphael.mansur/link-shortner/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +linkshortner/ +├─ linkshortner/ # código Django/DRF +│ ├─ core/settings.py +│ ├─ core/urls.py +│ └─ manage.py +├─ docker/ +│ ├─ app.Dockerfile +│ └─ wait-for-db.sh +├─ docker-compose.yml +├─ requirements.txt +└─ .env + + alias pm='python linkshortner manage.py' + alias dce='docker compose exec' \ No newline at end of file diff --git a/compose.yaml b/compose.yaml index 95cb3447c0c3ca405d393cf6f600676bff5e8eb0..0ff5282f00f1f76285cb8815603d02217de0d95d 100644 --- a/compose.yaml +++ b/compose.yaml @@ -23,7 +23,7 @@ services: app: build: context: . - dockerfile: docker/app/Dockerfile + dockerfile: docker/Dockerfile container_name: ${COMPOSE_PROJECT_NAME}-app depends_on: db: @@ -31,7 +31,7 @@ services: env_file: .env working_dir: /code volumes: - - ./app:/code + - ./linkshortner:/code ports: - "8001:8000" command: ["/entrypoint.sh"] diff --git a/docker/Dockerfile b/docker/Dockerfile index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..79616b1e39b3c745e9844c743e8f2b6cc6b473c4 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -0,0 +1,42 @@ +# docker/app/Dockerfile +FROM python:3.12-alpine + +# Dependências do sistema (Alpine) +# - libpq e headers para Postgres +# - build-base para eventuais compilações (evite em prod; aqui facilita dev) +RUN apk add --no-cache \ + bash \ + curl \ + libpq \ + postgresql-client \ + tzdata && \ + apk add --no-cache --virtual .build-deps \ + build-base \ + musl-dev \ + postgresql-dev + +# Diretório de trabalho +WORKDIR /code + +# Evita __pycache__, output imediato +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + +# Copie seus requirements (sem expor seu código) +COPY linkshortner/requirements.txt /tmp/requirements.txt + +# Instale dependências Python (ex.: Django, DRF, psycopg2-binary, gunicorn etc.) +RUN pip install --no-cache-dir -r /tmp/requirements.txt && \ + apk del .build-deps + +# Copie o entrypoint +COPY docker/entrypoint.sh /entrypoint.sh +RUN chmod +x /entrypoint.sh + +# Copie seu projeto +COPY linkshortner/ /code/ + +# Exponha a porta interna do Django +EXPOSE 8000 + +ENTRYPOINT ["/entrypoint.sh"] diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..f96be533736b4b965a85f2526c36edcf50e4b0e0 --- /dev/null +++ b/docker/entrypoint.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +set -e + +echo ">> Aguardando Postgres em ${POSTGRES_HOST}:${POSTGRES_PORT}..." +until pg_isready -h "${POSTGRES_HOST}" -p "${POSTGRES_PORT}" -U "${POSTGRES_USER}" >/dev/null 2>&1; do + sleep 1 +done +echo ">> Postgres disponível." + +# Migrações +echo ">> Executando migrações..." +python manage.py migrate --noinput + +# Criação opcional do superuser (se variáveis estiverem setadas) +if [ -n "$DJANGO_SUPERUSER_USERNAME" ] && [ -n "$DJANGO_SUPERUSER_EMAIL" ] && [ -n "$DJANGO_SUPERUSER_PASSWORD" ]; then + echo ">> Garantindo superuser..." + python manage.py shell <<'PYCODE' +import os +from django.contrib.auth import get_user_model +User = get_user_model() +u, created = User.objects.get_or_create( + username=os.environ["DJANGO_SUPERUSER_USERNAME"], + defaults={"email": os.environ["DJANGO_SUPERUSER_EMAIL"]} +) +if created: + u.set_password(os.environ["DJANGO_SUPERUSER_PASSWORD"]) + u.is_superuser = True + u.is_staff = True + u.save() +PYCODE +fi + +# Coleta de estáticos (opcional; útil se usar admin e servir em prod com nginx) +# python manage.py collectstatic --noinput + +# Servidor de aplicação +# Para desenvolvimento (autoreload): +echo ">> DEBUG: DJANGO_PORT=$DJANGO_PORT" +echo ">> Iniciando servidor Django (dev) em 0.0.0.0:${DJANGO_PORT}..." +exec python manage.py runserver 0.0.0.0:${DJANGO_PORT} + +# Para produção, troque a última linha por algo como: +# exec gunicorn seu_projeto.wsgi:application --bind 0.0.0.0:${DJANGO_PORT} --workers 3 diff --git a/linkshortner/core/__init__.py b/linkshortner/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/linkshortner/core/admin.py b/linkshortner/core/admin.py new file mode 100644 index 0000000000000000000000000000000000000000..8c38f3f3dad51e4585f3984282c2a4bec5349c1e --- /dev/null +++ b/linkshortner/core/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/linkshortner/core/apps.py b/linkshortner/core/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..8115ae60bc647249211ecbd4bbf6aa65478e9b5c --- /dev/null +++ b/linkshortner/core/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class CoreConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'core' diff --git a/linkshortner/core/migrations/__init__.py b/linkshortner/core/migrations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/linkshortner/core/models.py b/linkshortner/core/models.py new file mode 100644 index 0000000000000000000000000000000000000000..71a836239075aa6e6e4ecb700e9c42c95c022d91 --- /dev/null +++ b/linkshortner/core/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/linkshortner/core/tests.py b/linkshortner/core/tests.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce503c2dd97ba78597f6ff6e4393132753573f6 --- /dev/null +++ b/linkshortner/core/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/linkshortner/core/views.py b/linkshortner/core/views.py new file mode 100644 index 0000000000000000000000000000000000000000..91ea44a218fbd2f408430959283f0419c921093e --- /dev/null +++ b/linkshortner/core/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/linkshortner/linkshortner/settings.py b/linkshortner/linkshortner/settings.py index 47fdb9dfee16088e3312d01be006594373dbeb27..df7510b86d39ea6d9617dc2d72ea9007ec29b867 100644 --- a/linkshortner/linkshortner/settings.py +++ b/linkshortner/linkshortner/settings.py @@ -9,7 +9,8 @@ https://docs.djangoproject.com/en/5.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.2/ref/settings/ """ - +import os +import dj_database_url from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. @@ -37,6 +38,7 @@ INSTALLED_APPS = [ 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', + 'core', ] MIDDLEWARE = [ @@ -73,10 +75,12 @@ WSGI_APPLICATION = 'linkshortner.wsgi.application' # https://docs.djangoproject.com/en/5.2/ref/settings/#databases DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.sqlite3', - 'NAME': BASE_DIR / 'db.sqlite3', - } + "default": dj_database_url.parse( + os.environ.get("DATABASE_URL", ""), # vem do .env/Docker + conn_max_age=600, + ssl_require=False, + ) + } @@ -102,9 +106,9 @@ AUTH_PASSWORD_VALIDATORS = [ # Internationalization # https://docs.djangoproject.com/en/5.2/topics/i18n/ -LANGUAGE_CODE = 'en-us' +LANGUAGE_CODE = 'pt-br' -TIME_ZONE = 'UTC' +TIME_ZONE = 'America/Sao_Paulo' USE_I18N = True diff --git a/linkshortner/requirements.txt b/linkshortner/requirements.txt index 79b2a2b8e4f58626356a5706f2eb7e516b57f91f..b94149e1d199251b586c97d0480676cfa9a0679e 100644 --- a/linkshortner/requirements.txt +++ b/linkshortner/requirements.txt @@ -1,4 +1,17 @@ -Django>=5.0,<6.0 -djangorestframework>=3.15 -psycopg2-binary>=2.9 -gunicorn>=22.0 \ No newline at end of file +asgiref==3.9.2 +certifi==2025.8.3 +charset-normalizer==3.4.3 +Django==5.2.6 +docker==7.1.0 +idna==3.10 +requests==2.32.5 +sqlparse==0.5.3 +typing_extensions==4.15.0 +urllib3==2.5.0 +djangorestframework +djangorestframework-simplejwt +django-filter +drf-spectacular +django-cors-headers +psycopg[binary] +python-dotenv \ No newline at end of file