This commit is contained in:
relikd
2024-07-25 00:09:23 +02:00
commit d0dd4e7925
58 changed files with 1920 additions and 0 deletions

22
backend/Dockerfile Executable file
View File

@@ -0,0 +1,22 @@
FROM python:3.11-alpine
EXPOSE 8000
# install base system
RUN apk add --no-cache gcc libc-dev linux-headers
RUN pip install --upgrade pip
RUN pip install uvicorn gunicorn
# install requirements
WORKDIR /django_project
COPY ./requirements.txt .
RUN pip install -r requirements.txt
# then scripts (likely wont change often)
ENV PATH="/scripts:/py/bin:$PATH"
COPY --chmod=700 ./scripts /scripts
# finally copy app (likely will invalidate cache)
COPY . .
CMD ["run.sh"]

0
backend/app/__init__.py Normal file
View File

41
backend/app/admin.py Normal file
View File

@@ -0,0 +1,41 @@
from django.contrib import admin
from django.contrib.auth.models import Group # , User
from app.models import City, Place
# admin.site.register(Place, )
#############################
# Django defaults
#############################
admin.site.site_header = 'Leerstand-Verwaltung' # top-most title
admin.site.index_title = 'Leerstand' # title at root
admin.site.site_title = 'Leerstand-Verwaltung' # suffix to <title>
admin.site.unregister(Group)
# admin.site.unregister(User)
#############################
# App adjustments
#############################
@admin.register(City)
class CityAdmin(admin.ModelAdmin):
list_display = ['name', 'place_count', 'center', 'zoom']
def get_readonly_fields(self, request, obj=None):
return ['name'] if obj else []
@admin.display(description='Orte')
def place_count(self, instance: 'City'):
return instance.places.count()
@admin.register(Place)
class PlaceAdmin(admin.ModelAdmin):
list_display = ['address', 'city', 'since', 'until', 'created', 'updated']
list_filter = ['city']
search_fields = ['address', 'description']
ordering = ['-updated']

6
backend/app/apps.py Normal file
View File

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

29
backend/app/fields.py Normal file
View File

@@ -0,0 +1,29 @@
from django import forms
from django.core.validators import RegexValidator
from django.db import models
VALID_MONTH_ERR = 'Bitte gültiges Datum im Format YYYY oder YYYY-MM angeben.'
MONTH_FORMAT = r'^(19|20)[0-9]{2}(-(0[1-9]|1[0-2]))?$'
class MonthPicker(forms.widgets.Input):
input_type = 'text'
def get_context(self, name, value, attrs):
if attrs:
attrs.setdefault('placeholder', 'YYYY-MM')
context = super().get_context(name, value, attrs)
# context['widget']['type'] = 'month'
return context
class MonthField(models.CharField):
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 7
super().__init__(*args, **kwargs)
self.validators.append(RegexValidator(MONTH_FORMAT, VALID_MONTH_ERR))
def formfield(self, **kwargs):
kwargs['widget'] = MonthPicker
return super().formfield(**kwargs)

View File

View File

@@ -0,0 +1,10 @@
[
{
"model": "app.city",
"fields": {
"name": "Berlin",
"center": "52.52, 13.40",
"zoom": 12
}
}
]

View File

@@ -0,0 +1,54 @@
# Generated by Django 4.2.13 on 2024-07-24 22:47
import app.fields
import app.models.place
import common.form.img_with_preview
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import map_location.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='City',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='Name')),
('center', map_location.fields.LocationField(verbose_name='Zentrum')),
('zoom', models.IntegerField(validators=[django.core.validators.MinValueValidator(4), django.core.validators.MaxValueValidator(18)], verbose_name='Zoom')),
],
options={
'verbose_name': 'Stadt',
'verbose_name_plural': 'Städte',
'ordering': ['name'],
},
),
migrations.CreateModel(
name='Place',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True, verbose_name='Erstellt')),
('updated', models.DateTimeField(auto_now=True, verbose_name='Geändert')),
('address', models.CharField(max_length=100, verbose_name='Adresse')),
('img', common.form.img_with_preview.ThumbnailImageField(blank=True, null=True, upload_to=app.models.place.overwrite_img_upload, verbose_name='Bild')),
('since', app.fields.MonthField(blank=True, max_length=7, null=True, verbose_name='Seit')),
('until', app.fields.MonthField(blank=True, max_length=7, null=True, verbose_name='Bis')),
('description', models.TextField(blank=True, null=True, verbose_name='Beschreibung')),
('location', map_location.fields.LocationField(blank=True, null=True, verbose_name='Position')),
('city', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='places', to='app.city', verbose_name='Stadt')),
],
options={
'verbose_name': 'Gebäude',
'verbose_name_plural': 'Gebäude',
'ordering': ['address'],
},
),
]

View File

View File

@@ -0,0 +1,2 @@
from .city import City # noqa: F401
from .place import Place # noqa: F401

View File

@@ -0,0 +1,85 @@
from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.db.models.signals import post_delete
from django.dispatch import receiver
from django.template.defaultfilters import slugify
import json
import shutil
from pathlib import Path
from map_location.fields import LocationField
import typing
if typing.TYPE_CHECKING:
from app.models.place import Place
class City(models.Model):
name = models.CharField('Name', max_length=100)
center = LocationField('Zentrum', options={
'markerZoom': 12,
})
zoom = models.IntegerField('Zoom', validators=[
MinValueValidator(4), MaxValueValidator(18)])
places: 'models.QuerySet[Place]'
class Meta:
verbose_name = 'Stadt'
verbose_name_plural = 'Städte'
ordering = ['name']
def __str__(self) -> str:
return self.name
@property
def slug(self):
return slugify(self.name)
@property
def data_path(self) -> Path:
return settings.MEDIA_ROOT / str(self.pk)
@property
def data_url(self) -> str:
return f'{self.pk}'
def save(self, *args, **kwargs):
rv = super().save(*args, **kwargs)
City.update_cities_json()
return rv
def asJson(self) -> 'dict[str, str|list[float]|int|None]':
return {
'id': self.pk,
'slug': self.slug,
'name': self.name,
'zoom': self.zoom,
'loc': [round(self.center.lat, 6),
round(self.center.long, 6)] if self.center else None,
}
def update_json(self):
rv = []
for place in self.places.all():
if not place.location or not place.isVacant:
continue
rv.append(place.asJson())
self.data_path.mkdir(parents=True, exist_ok=True)
with open(self.data_path / 'data.json', 'w') as fp:
json.dump(rv, fp)
@staticmethod
def update_cities_json():
cities_json = settings.MEDIA_ROOT / 'cities.json'
with open(cities_json, 'w') as fp:
json.dump([city.asJson() for city in City.objects.all()], fp)
@receiver(post_delete, sender=City)
def on_delete_City(sender, instance: 'City', using, **kwargs):
if instance.data_path.exists():
shutil.rmtree(instance.data_path, ignore_errors=True)
City.update_cities_json()

View File

@@ -0,0 +1,86 @@
from django.db import models
from django.db.models.signals import post_delete
from django.dispatch import receiver
import os
from datetime import date
from map_location.fields import LocationField
from app.fields import MonthField
from common.form.img_with_preview import ThumbnailImageField
import typing
if typing.TYPE_CHECKING:
from app.models.city import City
def overwrite_img_upload(instance: 'Place', filename: str):
id = instance.pk or (Place.objects.count() + 1)
path = instance.city.data_path / f'{id}.jpg'
if path.is_file():
os.remove(path)
return f'{instance.city.data_url}/{id}.jpg'
class Place(models.Model):
created = models.DateTimeField('Erstellt', auto_now_add=True)
updated = models.DateTimeField('Geändert', auto_now=True)
city: 'models.ForeignKey[City]' = models.ForeignKey(
'City', on_delete=models.CASCADE, related_name='places',
verbose_name='Stadt')
address = models.CharField('Adresse', max_length=100)
img = ThumbnailImageField('Bild', blank=True, null=True,
upload_to=overwrite_img_upload) # type: ignore
since = MonthField('Seit', blank=True, null=True)
until = MonthField('Bis', blank=True, null=True)
description = models.TextField('Beschreibung', blank=True, null=True)
location = LocationField('Position', blank=True, null=True, options={
'map': {
'center': [52.52, 13.40],
'zoom': 12,
},
})
class Meta:
verbose_name = 'Gebäude'
verbose_name_plural = 'Gebäude'
ordering = ['address']
def __str__(self) -> str:
return self.address
@property
def isVacant(self):
if not self.until:
return True
now = date.today()
year = int(self.until[:4])
if year > now.year:
return True
return year == now.year and int((self.until + '-12')[5:7]) >= now.month
def save(self, *args, **kwargs):
rv = super().save(*args, **kwargs)
self.city.update_json()
return rv
def asJson(self) -> 'dict[str, str|list[float]|None]':
return {
'id': self.pk,
'since': self.since,
'until': self.until,
'addr': self.address,
'desc': self.description,
'img': self.img.url if self.img else None,
'loc': [round(self.location.lat, 6),
round(self.location.long, 6)] if self.location else None,
}
@receiver(post_delete, sender=Place)
def on_delete_Place(sender, instance: 'Place', using, **kwargs):
instance.city.update_json()

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

View File

@@ -0,0 +1,55 @@
from django.conf import settings
from django.core.files.uploadedfile import UploadedFile
from django.db import models
from django.forms import widgets
from PIL import Image, ImageOps
def makeThumnail(data: UploadedFile, size: 'tuple[int, int]'):
with Image.open(data) as img:
ImageOps.exif_transpose(img, in_place=True)
img.thumbnail(size)
if img.mode != 'RGB':
img = img.convert('RGB')
data.seek(0)
data.truncate()
img.save(data, 'jpeg')
class ImageFileWidget(widgets.ClearableFileInput):
template_name = 'forms/img-with-preview.html'
def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs)
context['MEDIA_URL'] = settings.MEDIA_URL
return context
class ThumbnailImageField(models.ImageField):
__del_image_on_save = False
def formfield(self, **kwargs):
kwargs['widget'] = ImageFileWidget
return super().formfield(**kwargs)
def save_form_data(self, instance, data):
if data is False:
self.__del_image_on_save = True
if isinstance(data, UploadedFile):
makeThumnail(data, (800, 600)) # only on create
# on update: django.db.models.fields.files.ImageFieldFile
super().save_form_data(instance, data)
def pre_save(self, model_instance, add):
if self.__del_image_on_save:
self.__del_image_on_save = False
self.deletePreviousImage(model_instance)
return super().pre_save(model_instance, add)
def deletePreviousImage(self, instance: models.Model):
if not instance.pk:
return
prev = instance.__class__.objects.get(pk=instance.pk)
imgField = getattr(prev, self.attname)
imgField.delete(save=False)

View File

@@ -0,0 +1,14 @@
<div>
{% if widget.is_initial %}
<img src="{{MEDIA_URL}}{{widget.value}}" style="max-width: 150px; max-height: 150px; margin: 8px;" />
{% if not widget.required %}
<span class="clearable-file-input">
<input type="checkbox" name="{{ widget.checkbox_name }}" id="{{ widget.checkbox_id }}"{% if widget.attrs.disabled %} disabled{% endif %}>
<label for="{{ widget.checkbox_id }}">{{ widget.clear_checkbox_label }}</label>
</span>
{% endif %}
<br>
<span>{{ widget.input_text }}:</span>
{% endif %}
<input type="{{ widget.type }}" name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}>
</div>

View File

16
backend/config/asgi.py Normal file
View File

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

148
backend/config/settings.py Normal file
View File

@@ -0,0 +1,148 @@
"""
Django settings for project.
Generated by 'django-admin startproject' using Django 4.2.13.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
import os
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/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'insecure-$a^nh$d!tgut43^91@')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = SECRET_KEY.startswith('insecure') or \
os.environ.get('DEBUG', '0').lower() not in ['false', 'no', '0']
ALLOWED_HOSTS = []
ALLOWED_HOSTS.extend(
filter(
None,
os.environ.get('ALLOWED_HOSTS', '*').split(','),
)
)
CSRF_TRUSTED_ORIGINS = ['https://' + x for x in ALLOWED_HOSTS]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'common',
'map_location',
'app',
]
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 = 'config.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [], # BASE_DIR / 'templates'
'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 = 'config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db' / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.2/topics/i18n/
LANGUAGE_CODE = 'de'
TIME_ZONE = 'Europe/Berlin'
USE_I18N = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Custom
ADMIN_URL = os.environ.get('ADMIN_URL', 'admin/').rstrip('/') + '/'
STATIC_ROOT = BASE_DIR / 'static'
MEDIA_URL = 'data/'
MEDIA_ROOT = BASE_DIR / 'data'
# STATIC_ROOT.mkdir(exist_ok=True)
MEDIA_ROOT.mkdir(exist_ok=True)
(BASE_DIR / 'db').mkdir(exist_ok=True)

25
backend/config/urls.py Normal file
View File

@@ -0,0 +1,25 @@
"""
URL configuration for project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.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
urlpatterns = [
path(settings.ADMIN_URL, admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

16
backend/config/wsgi.py Normal file
View File

@@ -0,0 +1,16 @@
"""
WSGI config for 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/4.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
application = get_wsgi_application()

31
backend/docker-compose.yml Executable file
View File

@@ -0,0 +1,31 @@
services:
app:
container_name: leerstand
build:
context: .
# dockerfile: .
pull_policy: build
ports:
- 127.0.0.1:8098:8000
image: leerstand:latest
working_dir: /django_project
environment:
DJANGO_SECRET_KEY: ${DJANGO_SECRET_KEY}
ALLOWED_HOSTS: ${ALLOWED_HOSTS}
ADMIN_URL: ${ADMIN_URL}
DEBUG: ${DEBUG:-0}
volumes:
- volume-leerstand:/django_project/db
- /srv/http/leerstand-data:/django_project/data
- /srv/http/leerstand-static:/django_project/static
restart: unless-stopped
networks:
- network-leerstand
volumes:
volume-leerstand:
name: leerstand
networks:
network-leerstand:
name: leerstand

22
backend/manage.py Executable 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', 'config.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()

3
backend/requirements.txt Normal file
View File

@@ -0,0 +1,3 @@
Django==4.2.14
pillow==10.4.0
django-map-location==0.9.2

6
backend/scripts/run.sh Executable file
View File

@@ -0,0 +1,6 @@
#!/bin/sh
python manage.py collectstatic --noinput
python manage.py migrate
# python -m uvicorn --port 8000 config.asgi:application
python -m gunicorn -b 0.0.0.0:8000 -k uvicorn.workers.UvicornWorker config.asgi:application