Add documentation and source

Added documentation, source and extra files.
This commit is contained in:
2025-07-02 20:26:50 +02:00
parent 4fc1d36a10
commit e3ebf6bf4f
295 changed files with 24986 additions and 0 deletions

31
source/advanced/.idea/Advanced.iml generated Normal file
View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="FacetManager">
<facet type="django" name="Django">
<configuration>
<option name="rootFolder" value="$MODULE_DIR$" />
<option name="settingsModule" value="advanced/settings.py" />
<option name="manageScript" value="manage.py" />
<option name="environment" value="&lt;map/&gt;" />
<option name="doNotUseTestRunner" value="false" />
<option name="trackFilePattern" value="" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/.idea" />
<excludeFolder url="file://$MODULE_DIR$/jupyter/.ipynb_checkpoints" />
</content>
<orderEntry type="jdk" jdkName="Python 3 (training)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="GOOGLE" />
<option name="myDocStringFormat" value="Google" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Django" />
</component>
</module>

View File

@ -0,0 +1,12 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="GrazieInspection" enabled="false" level="TYPO" enabled_by_default="false" />
<inspection_tool class="LanguageDetectionInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false">
<option name="processCode" value="true" />
<option name="processLiterals" value="true" />
<option name="processComments" value="true" />
</inspection_tool>
</profile>
</component>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

8
source/advanced/.idea/modules.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/advanced.iml" filepath="$PROJECT_DIR$/.idea/advanced.iml" />
</modules>
</component>
</project>

11
source/advanced/.idea/workspace.xml generated Normal file
View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showExcludedFiles" value="false" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">
<property name="settings.editor.selected.configurable" value="configurable.group.tools" />
</component>
</project>

View File

View File

@ -0,0 +1,16 @@
"""
ASGI config for advanced 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/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'advanced.settings')
application = get_asgi_application()

View File

@ -0,0 +1,139 @@
"""
Django settings for advanced project.
Generated by 'django-admin startproject' using Django 3.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-4f#(qt450m(73!m#q%6jhl*t@0_%xn4$)ing$)-2qey-^bv*xy"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django_extensions",
"various",
]
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",
"django.middleware.locale.LocaleMiddleware",
]
ROOT_URLCONF = "advanced.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 = "advanced.wsgi.application"
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "database.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/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",
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = "/static/"
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
# Email configuration
# Set a backend in console for demonstration purposes.
# The correct backend should be SMTP in production.
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
# Media configuration
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"

View File

@ -0,0 +1,26 @@
"""advanced URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
from various.views import view_file_download
urlpatterns = [
path("admin/", admin.site.urls),
path("download", view_file_download, name="download"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

View File

@ -0,0 +1,16 @@
"""
WSGI config for advanced project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'advanced.settings')
application = get_wsgi_application()

Binary file not shown.

View File

@ -0,0 +1,81 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"id": "fc76bc88",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Content-Type: text/plain; charset=\"utf-8\"\n",
"MIME-Version: 1.0\n",
"Content-Transfer-Encoding: 7bit\n",
"Subject: Title\n",
"From: noreply@example.aa\n",
"To: noreply@example.aa\n",
"Date: Fri, 16 Apr 2021 22:44:20 -0000\n",
"Message-ID: <161861306067.29777.1833249302107691814@manjaro>\n",
"\n",
"Body of the email.\n",
"-------------------------------------------------------------------------------\n"
]
},
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Simple example to send a text email\n",
"from django.core.mail import send_mail\n",
"send_mail(\"Title\", \"Body of the email.\", \"noreply@example.aa\", [\"noreply@example.aa\"])"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "badac700",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Maggle\n"
]
}
],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Django Shell-Plus",
"language": "python",
"name": "django_extensions"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

22
source/advanced/manage.py Normal file
View File

@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'advanced.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

View File

@ -0,0 +1,9 @@
from django.apps import AppConfig
class VariousConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "various"
default_app_config = "various.VariousConfig"

View File

@ -0,0 +1 @@
from .room import *

View File

@ -0,0 +1,51 @@
from django.contrib import admin
from django.db import models
from django.db.models import F
from django.http import HttpRequest
from django.utils.translation import gettext_lazy as _
from various.models import Room
@admin.register(Room)
class RoomAdmin(admin.ModelAdmin):
"""
Admin configuration for rooms.
"""
list_display = ["id", "name", "length", "width", "height", "get_volume_display"]
list_editable = ["name", "length", "width", "height"]
actions = ["action_fix_minimum"]
def get_queryset(self, request):
"""
Change queryset to add a computed field for volume.
Args:
request: HTTP
"""
return super().get_queryset(request).annotate(volume=F("width") * F("length") * F("height"))
def get_volume_display(self, obj: Room) -> str:
return f"{obj.get_volume()} cm³"
get_volume_display.short_description = _("area")
get_volume_display.admin_order_field = "volume"
def action_fix_minimum(self, request: HttpRequest, queryset: models.QuerySet):
"""
Change room dimensions to have at least 1cm in every axis.
Args:
request: HTTP request.
queryset: selected rooms.
"""
for room in queryset: # type: Room
room.width = max(1, room.width)
room.length = max(1, room.length)
room.height = max(1, room.height)
room.save()
self.message_user(request, _("The selected rooms have been updated."))

View File

@ -0,0 +1,59 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2021-04-18 11:30+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \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"
#: various/admin/room.py:34
msgid "area"
msgstr "aire"
#: various/admin/room.py:51
msgid "The selected rooms have been updated."
msgstr "Les salles sélectionnées ont été mises à jour."
#: various/models/room.py:11
msgid "name"
msgstr "nom"
#: various/models/room.py:12
msgid "description"
msgstr "description"
#: various/models/room.py:13 various/models/room.py:14
#: various/models/room.py:15
msgid "centimeters"
msgstr "centimètres"
#: various/models/room.py:13
msgid "width"
msgstr "largeur"
#: various/models/room.py:14
msgid "length"
msgstr "longueur"
#: various/models/room.py:15
msgid "height"
msgstr "hauteur"
#: various/models/room.py:18
msgid "room"
msgstr "salle"
#: various/models/room.py:19
msgid "rooms"
msgstr "salles"

View File

@ -0,0 +1,29 @@
# Generated by Django 3.2 on 2021-04-18 11:28
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Room',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=32, unique=True, verbose_name='name')),
('description', models.TextField(blank=True, verbose_name='description')),
('width', models.PositiveIntegerField(default=0, help_text='centimeters', verbose_name='width')),
('length', models.PositiveIntegerField(default=0, help_text='centimeters', verbose_name='length')),
('height', models.PositiveIntegerField(default=0, help_text='centimeters', verbose_name='height')),
],
options={
'verbose_name': 'room',
'verbose_name_plural': 'rooms',
},
),
]

View File

@ -0,0 +1 @@
from .room import *

View File

@ -0,0 +1,49 @@
from django.db import models
from django.utils.translation import gettext_lazy as _
class Room(models.Model):
"""
Room definition.
"""
name = models.CharField(max_length=32, blank=False, unique=True, verbose_name=_("name"))
description = models.TextField(blank=True, verbose_name=_("description"))
width = models.PositiveIntegerField(default=0, help_text=_("centimeters"), verbose_name=_("width"))
length = models.PositiveIntegerField(default=0, help_text=_("centimeters"), verbose_name=_("length"))
height = models.PositiveIntegerField(default=0, help_text=_("centimeters"), verbose_name=_("height"))
class Meta:
verbose_name = _("room")
verbose_name_plural = _("rooms")
def get_area(self) -> int:
"""
Get the area of the room.
Returns:
Area of the room in square centimeters.
"""
return self.width * self.length
def get_volume(self) -> int:
"""
Get the volume of the room.
Returns:
Volume of the room in cube centimeters.
"""
return self.width * self.length * self.height
def is_empty(self) -> bool:
"""
Tell if the room is empty (has no volume).
Returns:
Whether the room has no volume (zero).
"""
return self.width * self.length * self.height == 0

View File

@ -0,0 +1 @@
from .room import *

View File

@ -0,0 +1,55 @@
from django import test
from various.models import Room
class RoomTestCase(test.TestCase):
"""
Basic test case for rooms.
This method is executed before every `test_` function.
To run those automatic tests, in a terminal, just run
`./manage.py test`
"""
def setUp(self) -> None:
self.room1 = Room(name="Kitchen", width=260, length=320, height=250) # basic
self.room2 = Room(name="Fake", width=0, length=320, height=250) # a 2D object
@classmethod
def setUpClass(cls):
"""Cette méthode est exécutée une seule fois avant ous les tests."""
pass
@classmethod
def tearDownClass(cls):
pass
def tearDown(self) -> None:
"""
End unit test.
Is executed after every `test_` method.
"""
def test_base_room(self):
"""
Basic test using the fixture set up in the `setUp` method.
"""
self.assertEqual(self.room2.get_volume(), 0)
self.assertEqual(self.room1.get_area(), 83200)
def test_dummy_page(self):
"""
Test the Django test client.
Used to test that pages of the projet answer properly.
"""
client = test.Client()
response = client.get("/admin/")
self.assertNotEqual(response.status_code, 404)

View File

@ -0,0 +1,21 @@
from django.core.files.storage import DefaultStorage
from django.http import HttpRequest, HttpResponse
def view_file_download(request: HttpRequest) -> HttpResponse:
"""
Serve a media file like a download.
Args:
request: HTTP request.
Returns:
Media file as an attachment to download.
"""
storage = DefaultStorage() # Objet capable de manipuler des fichiers média
with storage.open("django-upload.jpg", "rb") as file: # relative to MEDIA_ROOT
response = HttpResponse(file, content_type="image/jpeg")
# Use list notation to set headers
response["Content-Disposition"] = "attachment; filename=django-upload.jpg"
return response