Pular para o conteúdo principal

Backend - Stack Tecnológico

O backend do Módulo Empreendedorismo é construído com Django e Django REST Framework, seguindo boas práticas de desenvolvimento Python.

Tecnologias Principais

TecnologiaVersãoFunção
Python3.11+Linguagem de programação
Django5.xFramework web
Django REST Framework3.xAPI REST
PostgreSQL16Banco de dados
Redis7Cache e message broker
Celery5.xProcessamento assíncrono
MinIO-Armazenamento S3-compatible

Dependências

requirements.txt
# Framework
Django>=5.0
djangorestframework>=3.14
django-cors-headers>=4.3

# Autenticação
djangorestframework-simplejwt>=5.3

# Database
psycopg2-binary>=2.9

# Task Queue
celery>=5.3
redis>=5.0

# Storage
django-storages>=1.14
boto3>=1.34

# Documentation
drf-spectacular>=0.27

# Utils
python-dotenv>=1.0
Pillow>=10.2
gunicorn>=21.2

Estrutura de Aplicações

backend/
├── apps/
│ ├── accounts/ # Autenticação e usuários
│ ├── entrepreneurs/ # Empreendedores
│ ├── structuring_agents/ # Agentes estruturadores
│ ├── business_plans/ # Planos de negócio
│ ├── managers/ # Gestores
│ ├── notifications/ # Sistema de emails
│ └── reports/ # Relatórios
├── core/ # Configurações Django
│ ├── settings.py
│ ├── urls.py
│ ├── celery.py
│ └── storage_backends.py
├── templates/ # Templates de email
├── manage.py
└── requirements.txt

Configurações Principais

Django Settings

core/settings.py
# Custom User Model
AUTH_USER_MODEL = 'accounts.User'

# Internationalization
LANGUAGE_CODE = 'pt-br'
TIME_ZONE = 'America/Sao_Paulo'

# REST Framework
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}

# JWT Settings
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(hours=1),
'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
'ROTATE_REFRESH_TOKENS': True,
}

Celery Configuration

core/celery.py
from celery import Celery

app = Celery('core')
app.config_from_object('django.conf:settings', namespace='CELERY')

# Filas configuradas
task_queues = {
'default': {}, # Tarefas gerais
'emails': {}, # Envio de emails
'reports': {}, # Geração de relatórios
}

# Beat Schedule (tarefas agendadas)
beat_schedule = {
'process-account-deletion-requests': {
'task': 'accounts.process_account_deletion_requests',
'schedule': crontab(hour=0, minute=0), # Diariamente
}
}

MinIO Storage

core/storage_backends.py
from storages.backends.s3boto3 import S3Boto3Storage

class MinIOStorage(S3Boto3Storage):
bucket_name = 'media'
file_overwrite = False

Padrões de Código

ViewSets

from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from .models import BusinessPlan
from .serializers import BusinessPlanSerializer
from .permissions import CanViewBusinessPlan

class BusinessPlanViewSet(viewsets.ModelViewSet):
queryset = BusinessPlan.objects.all()
serializer_class = BusinessPlanSerializer
permission_classes = [IsAuthenticated, CanViewBusinessPlan]

def get_queryset(self):
return self.queryset.filter(entrepreneur__user=self.request.user)

Serializers

from rest_framework import serializers
from .models import BusinessPlan

class BusinessPlanSerializer(serializers.ModelSerializer):
class Meta:
model = BusinessPlan
fields = '__all__'
read_only_fields = ['id', 'created_at', 'updated_at']

def validate(self, data):
# Validações customizadas
return data

Permissions

from rest_framework.permissions import BasePermission

class CanViewBusinessPlan(BasePermission):
def has_object_permission(self, request, view, obj):
# Empreendedor pode ver apenas seus planos
if hasattr(request.user, 'entrepreneur'):
return obj.entrepreneur.user == request.user
# Agente pode ver planos em revisão
if hasattr(request.user, 'structuringagent'):
return obj.status in ['UNDER_REVIEW', 'IN_MENTORSHIP']
return False

Comandos de Gerenciamento

# Criar superusuário
python manage.py createsuperuser

# Executar migrations
python manage.py migrate

# Seed de dados
python manage.py seed
python manage.py seed_all

# Configurar MinIO
python manage.py setup_minio

# Executar servidor de desenvolvimento
python manage.py runserver

# Executar Celery worker
celery -A core worker -l info -Q default,reports

# Executar Celery Beat
celery -A core beat -l info

Documentação da API

A documentação da API é gerada automaticamente com drf-spectacular:

  • Swagger UI: http://localhost:8000/api/docs/
  • ReDoc: http://localhost:8000/api/redoc/
  • OpenAPI Schema: http://localhost:8000/api/schema/