work on databse model
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 3s

This commit is contained in:
pierre geeraert
2026-06-11 22:12:00 +01:00
parent 883e028cae
commit d3061eddaf
22 changed files with 275 additions and 43 deletions
+3
View File
@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.
+9
View File
@@ -1,3 +1,4 @@
from django.apps import AppConfig
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render
@@ -6,6 +7,14 @@ import psycopg2
from apps.cloudmanager.db_interaction import DB_generation,Check_server_supposed_XXX,Give_current_weekday,Give_current_hour
class CloudmanagerConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apps.cloudmanager'
label = 'cloudmanager'
def coucou(request):
return HttpResponse('<h1>Hello cmm!</h1>')
def hello(request):
list_schedule = ['schedule1','schedule2']
list_servers_up = [['wiki', 'wikijs', 2], ['book', 'bookstack-db', 1]]
@@ -0,0 +1,28 @@
# Generated by Django 4.2.29 on 2026-06-11 19:35
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CmmData',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('namespace', models.CharField(max_length=100)),
('schedule_day', models.CharField(max_length=100)),
('schedule_hour', models.CharField(max_length=100)),
('replicas', models.IntegerField()),
],
options={
'db_table': 'cloudmanager',
},
),
]
+12
View File
@@ -0,0 +1,12 @@
from django.db import models
class CmmData(models.Model):
name = models.CharField(max_length=100)
namespace = models.CharField(max_length=100)
schedule_day = models.CharField(max_length=100)
schedule_hour = models.CharField(max_length=100)
replicas = models.IntegerField()
class Meta:
db_table = 'cloudmanager'
+3
View File
@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.
+18 -27
View File
@@ -1,33 +1,24 @@
from django.http import HttpResponse
from django.views.decorators.http import require_POST
#from django.contrib.auth.decorators import login_required # optional but recommended
def trigger_my_action(request):
# 1. Run your Django module/function
result = "1"
print('here')
# 2. Return ONLY the HTML fragment you want to show on the page
# This will replace the content inside the "hx-target" div
return HttpResponse("Done!")
# IMPORT AT THE TOP HERE: This is completely safe!
from apps.cloudmanager.models import CmmData
def coucou(request):
# 1. Prepare the data inside the function
data = CmmData(
name="test",
namespace="testspace",
schedule_hour="1",
schedule_day="deux",
replicas=3
)
#@login_required
@require_POST
def change_schedule(request):
# HTMX sends these via standard POST data
schedule_id = request.POST.get('schedule_id')
server_name = request.POST.get('server_name')
# 2. This line actually pushes the data into your cloudmanager_db!
data.save()
if not schedule_id or not server_name:
return HttpResponse("<span style='color: red;'>Missing parameters.</span>", status=400)
return HttpResponse('<h1>Hello cmm! Data saved successfully!</h1>')
try:
# --- Your Core Logic Here ---
# e.g., Server.objects.filter(name=server_name).update(schedule_id=schedule_id)
print(f"Updating {server_name} to schedule profile {schedule_id}")
# Return a success message that will instantly inject into the server's status div
return HttpResponse("<span style='color: green;'>✓ Updated successfully!</span>")
except Exception as e:
return HttpResponse(f"<span style='color: red;'>Error: {str(e)}</span>", status=500)
def display(request):
data = CmmData.objects.all()
print(data[0].namespace)
return HttpResponse(data)
+28
View File
@@ -0,0 +1,28 @@
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render
import os
import psycopg2
from apps.cloudmanager.db_interaction import DB_generation,Check_server_supposed_XXX,Give_current_weekday,Give_current_hour
def hello(request):
list_schedule = ['schedule1','schedule2']
list_servers_up = [['wiki', 'wikijs', 2], ['book', 'bookstack-db', 1]]
return render(request, 'cloudmanager/index.html', {'list_schedule':list_schedule,'list_servers_up':list_servers_up})
def redirect(request):
db_host = os.environ.get('DB_HOST')
db_port = os.environ.get('DB_PORT')
db_user = os.environ.get('DB_USERNAME')
db_password = os.environ.get('DB_PASSWORD')
db_name = os.environ.get('CUSTOM_DB_DATABASE',os.environ.get('DB_DATABASE'))
generated_db = DB_generation(db_host, db_port, db_user, db_password,db_name)
##operation:
## Server(s) supposed to be UP
list_servers_up = Check_server_supposed_XXX(generated_db, "up", Give_current_hour(),Give_current_weekday())
print(list_servers_up)
return render(request, 'cloudmanager/cmm_blank_page.html', {'list_servers_up':list_servers_up})
@@ -0,0 +1,33 @@
from django.http import HttpResponse
from django.views.decorators.http import require_POST
#from django.contrib.auth.decorators import login_required # optional but recommended
def trigger_my_action(request):
# 1. Run your Django module/function
result = "1"
print('here')
# 2. Return ONLY the HTML fragment you want to show on the page
# This will replace the content inside the "hx-target" div
return HttpResponse("Done!")
#@login_required
@require_POST
def change_schedule(request):
# HTMX sends these via standard POST data
schedule_id = request.POST.get('schedule_id')
server_name = request.POST.get('server_name')
if not schedule_id or not server_name:
return HttpResponse("<span style='color: red;'>Missing parameters.</span>", status=400)
try:
# --- Your Core Logic Here ---
# e.g., Server.objects.filter(name=server_name).update(schedule_id=schedule_id)
print(f"Updating {server_name} to schedule profile {schedule_id}")
# Return a success message that will instantly inject into the server's status div
return HttpResponse("<span style='color: green;'>✓ Updated successfully!</span>")
except Exception as e:
return HttpResponse(f"<span style='color: red;'>Error: {str(e)}</span>", status=500)
+5
View File
@@ -11,6 +11,11 @@ import psycopg2
import random
import mimetypes
class RandomSimpsonsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apps.random_simpsons'
label = 'simpsons'
def DB_generation(host_in,port_in,user_in,password_in,db_in):
#db = pymysql.connect(host=host_in, port=port_in, user=user_in, passwd=password_in,db=db_in)
db = psycopg2.connect(host=host_in, port=port_in, user=user_in, password=password_in,database=db_in)
@@ -0,0 +1,27 @@
# Generated by Django 4.2.29 on 2026-06-11 19:50
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='SimpsonsData',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('season', models.IntegerField()),
('episode', models.IntegerField()),
('url', models.CharField(max_length=100)),
('seen', models.CharField(max_length=100)),
],
options={
'db_table': 'simpsons',
},
),
]
@@ -0,0 +1,18 @@
# Generated by Django 4.2.29 on 2026-06-11 20:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('simpsons', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='simpsonsdata',
name='seen',
field=models.BooleanField(),
),
]
+8 -1
View File
@@ -1,3 +1,10 @@
from django.db import models
# Create your models here.
class SimpsonsData(models.Model):
season = models.IntegerField()
episode = models.IntegerField()
url = models.CharField(max_length=100)
seen = models.BooleanField()
class Meta:
db_table = 'simpsons'
Binary file not shown.
+46
View File
@@ -0,0 +1,46 @@
# routers.py
class ProjectDatabaseRouter:
"""
A router to control all database operations on models in the
simpsons and cloudmanager applications.
"""
def db_for_read(self, model, **hints):
"""Attempts to read simpsons and cloudmanager models go to their specific dbs."""
if model._meta.app_label == 'simpsons':
return 'simpsons_db'
if model._meta.app_label == 'cloudmanager':
return 'cloudmanager_db'
return 'default'
def db_for_write(self, model, **hints):
"""Attempts to write simpsons and cloudmanager models go to their specific dbs."""
if model._meta.app_label == 'simpsons':
return 'simpsons_db'
if model._meta.app_label == 'cloudmanager':
return 'cloudmanager_db'
return 'default'
def allow_relation(self, obj1, obj2, **hints):
"""Allow relations if both models are in the same database."""
# Prevents accidental foreign key relationships across different physical DBs
if (
obj1._meta.app_label in ['simpsons', 'cloudmanager'] or
obj2._meta.app_label in ['simpsons', 'cloudmanager']
):
return obj1._meta.app_label == obj2._meta.app_label
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""Ensure the app's models only show up in the designated database."""
if app_label == 'simpsons':
return db == 'simpsons_db'
if app_label == 'cloudmanager':
return db == 'cloudmanager_db'
# Ensure default Django apps (auth, sessions, etc.) don't migrate into simpsons/cloudmanager
if db in ['simpsons_db', 'cloudmanager_db']:
return False
return None
+26 -5
View File
@@ -40,7 +40,8 @@ INSTALLED_APPS = [
'django.contrib.staticfiles',
'bootstrap5',
'django_hosts',
'apps.cloudmanager',
'apps.cloudmanager.apps.CloudmanagerConfig',
'apps.random_simpsons.apps.RandomSimpsonsConfig',
]
MIDDLEWARE = [
@@ -87,11 +88,31 @@ WSGI_APPLICATION = 'django_code.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'django',
'USER': os.environ.get('DB_USERNAME'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'HOST': os.environ.get('DB_HOST'),
'PORT': os.environ.get('DB_PORT'),
},
'cloudmanager_db': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'cloudmanager',
'USER': os.environ.get('DB_USERNAME'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'HOST': os.environ.get('DB_HOST'),
'PORT': os.environ.get('DB_PORT'),
},
'simpsons_db': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'simpsons',
'USER': os.environ.get('DB_USERNAME'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'HOST': os.environ.get('DB_HOST'),
'PORT': os.environ.get('DB_PORT'),
},
}
}
DATABASE_ROUTERS = ['django_code.routers.ProjectDatabaseRouter']
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
+7 -6
View File
@@ -16,7 +16,7 @@ Including another URLconf
"""
from django.contrib import admin
from django.urls import path
from apps.cloudmanager import (credentials,db_interaction)
#from apps.cloudmanager import (credentials,db_interaction)
from apps.cloudmanager import apps as cloudmanager_apps
from apps.cloudmanager import views as cloudmanager_views
from apps.random_simpsons import apps as random_simpsons
@@ -82,10 +82,11 @@ urlpatterns = [
################### cloudmanager ###################
path('cmm/', cloudmanager_apps.redirect),
path('cmm/hello', cloudmanager_apps.hello),
path('cmm/print', cloudmanager_apps.print),
path('cmm/run-action/', cloudmanager_views.trigger_my_action, name='run_my_action_url'),
path('change-schedule/', cloudmanager_views.change_schedule, name='change_schedule'),
path('cmm/main/', db_interaction.main),
path('cmm/hello', cloudmanager_apps.hello, name='hello'),
path('cmm/coucou', cloudmanager_views.coucou, name='coucou'),
path('cmm/display', cloudmanager_views.display, name='display'),
#path('cmm/run-action/', cloudmanager_views.trigger_my_action, name='run_my_action_url'),
#path('change-schedule/', cloudmanager_views.change_schedule, name='change_schedule'),
#path('cmm/main/', db_interaction.main),
]
@@ -239,7 +239,7 @@
<!-- Triggers a POST request to '/run-my-module/' without reloading -->
<!-- When clicked, 'Run Module' changes to 'Done!' -->
<button hx-post="{% url 'run_my_action_url' %}"
<!-- <button hx-post=" url 'run_my_action_url' " -->
hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'>
Run Module
</button>
@@ -274,7 +274,7 @@
{% endfor %}
</select>
<button class="btn-price" style="margin-top: 10px; width: 100%;"
hx-post="{% url 'change_schedule' %}"
hx-post="{}"
hx-include="#schedule-{{ forloop.counter }}"
hx-vals='{"server_name": "{{ server.1 }}"}'
hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'