refactor codigo

This commit is contained in:
juanjo
2026-04-11 13:00:25 +02:00
parent 9e1c176ff9
commit c5f1b4e131
8 changed files with 144 additions and 16 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
*.pyc

5
apps/common/apps.py Normal file
View File

@@ -0,0 +1,5 @@
from django.apps import AppConfig
class CommonConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apps.common'

View File

@@ -1,5 +1,5 @@
from django.db import connection
from common.utils import clean_sql_string, clean_sql_int
from apps.common.utils import clean_sql_string, clean_sql_int
def getData(params):
"""
@@ -39,9 +39,9 @@ def setData(params):
WHERE p.categoria_id = c.id AND p.id = %s
"""
# Fecha en formato Año-Día-Mes (Y-d-m)
# Fecha en formato YYYY-MM-DD para SQL
import datetime
fecha_hoy = datetime.datetime.now().strftime('%Y-%d-%m')
fecha_hoy = datetime.datetime.now().strftime('%Y-%m-%d')
parameter_dict = [
clean_sql_string(params.get('nombre')),

5
apps/promociones/apps.py Normal file
View File

@@ -0,0 +1,5 @@
from django.apps import AppConfig
class PromocionesConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apps.promociones'

View File

@@ -1,13 +1,69 @@
from dotenv import load_dotenv
import os
from pathlib import Path
# Cargar variables desde el archivo .env
load_dotenv()
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = os.getenv('DEBUG') == 'True'
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Configuración de base de datos usando las variables
SECRET_KEY = os.getenv('SECRET_KEY', 'django-insecure-change-me-for-production')
DEBUG = os.getenv('DEBUG', 'True').lower() == 'true'
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'apps.promociones',
'apps.common',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'core.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'core.wsgi.application'
# Para desarrollo local: SQLite
if DEBUG:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
else:
# Producción: PostgreSQL desde .env
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
@@ -18,3 +74,32 @@ DATABASES = {
'PORT': os.getenv('DB_PORT'),
}
}
# Internationalization
LANGUAGE_CODE = 'es-es'
TIME_ZONE = 'Europe/Madrid'
USE_I18N = True
USE_TZ = True
# Static files
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Logging básico
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'': {
'handlers': ['console'],
'level': 'INFO',
},
},
}

View File

@@ -2,5 +2,5 @@ from django.urls import path, include
urlpatterns = [
# Redirigimos todas las peticiones de /api/promociones/ a nuestra app
path('api/promociones/', include('promociones.urls')),
path('api/promociones/', include('apps.promociones.urls')),
]

BIN
db.sqlite3 Normal file

Binary file not shown.

32
init_db.py Normal file
View File

@@ -0,0 +1,32 @@
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
import django
django.setup()
from django.db import connection
with connection.cursor() as cursor:
cursor.execute("""
CREATE TABLE IF NOT EXISTS promociones (
id INTEGER PRIMARY KEY AUTOINCREMENT,
nombre VARCHAR(255),
fecha_inicio DATE,
descripcion TEXT,
activo BOOLEAN DEFAULT 1,
categoria_id INTEGER
)
""")
cursor.execute("""
INSERT OR IGNORE INTO promociones (id, nombre, fecha_inicio, descripcion, activo, categoria_id)
VALUES (1, 'Promo Test', '2026-04-11', 'Descripcion de prueba', 1, 1)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS categorias (
id INTEGER PRIMARY KEY AUTOINCREMENT,
nombre VARCHAR(255)
)
""")
cursor.execute("""
INSERT OR IGNORE INTO categorias (id, nombre)
VALUES (1, 'Categoria Test')
""")
connection.commit()
print('Tablas y datos de prueba creados exitosamente en db.sqlite3')