Compare commits

...

5 Commits

10 changed files with 356 additions and 276 deletions

17
Dockerfile Normal file
View File

@ -0,0 +1,17 @@
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y libpq-dev python3 python3-poetry nginx
COPY shimatta_kenkyusho /app/shimatta_kenkyusho
COPY poetry.lock /app/
COPY pyproject.toml /app/
RUN systemctl enable nginx
ARG UNAME=django
ARG UID=1000
ARG GID=1000
RUN groupadd -g $GID -o $UNAME
RUN useradd -m -u $UID -g $GID -o -s /bin/bash $UNAME
USER $UNAME
WORKDIR "/app"
RUN poetry install

226
poetry.lock generated Normal file
View File

@ -0,0 +1,226 @@
[[package]]
name = "annotated-types"
version = "0.5.0"
description = "Reusable constraint types to use with typing.Annotated"
category = "main"
optional = false
python-versions = ">=3.7"
[[package]]
name = "asgiref"
version = "3.7.2"
description = "ASGI specs, helper code, and adapters"
category = "main"
optional = false
python-versions = ">=3.7"
[package.dependencies]
typing-extensions = {version = ">=4", markers = "python_version < \"3.11\""}
[package.extras]
tests = ["pytest", "pytest-asyncio", "mypy (>=0.800)"]
[[package]]
name = "crispy-bootstrap5"
version = "0.7"
description = "Bootstrap5 template pack for django-crispy-forms"
category = "main"
optional = false
python-versions = ">=3.7"
[package.dependencies]
django = ">=3.2"
django-crispy-forms = ">=1.13.0"
[package.extras]
test = ["pytest", "pytest-django"]
[[package]]
name = "django"
version = "4.2.5"
description = "A high-level Python web framework that encourages rapid development and clean, pragmatic design."
category = "main"
optional = false
python-versions = ">=3.8"
[package.dependencies]
asgiref = ">=3.6.0,<4"
sqlparse = ">=0.3.1"
tzdata = {version = "*", markers = "sys_platform == \"win32\""}
[package.extras]
argon2 = ["argon2-cffi (>=19.1.0)"]
bcrypt = ["bcrypt"]
[[package]]
name = "django-crispy-forms"
version = "2.0"
description = "Best way to have Django DRY forms"
category = "main"
optional = false
python-versions = ">=3.7"
[package.dependencies]
django = ">=3.2"
[[package]]
name = "django-filter"
version = "23.2"
description = "Django-filter is a reusable Django application for allowing users to filter querysets dynamically."
category = "main"
optional = false
python-versions = ">=3.7"
[package.dependencies]
Django = ">=3.2"
[[package]]
name = "django-qr-code"
version = "3.1.1"
description = "An application that provides tools for displaying QR codes on your Django site."
category = "main"
optional = false
python-versions = ">=3.7"
[package.dependencies]
django = ">=3.2"
pydantic = "*"
pytz = "*"
segno = ">=1.5"
[[package]]
name = "djangorestframework"
version = "3.14.0"
description = "Web APIs for Django, made easy."
category = "main"
optional = false
python-versions = ">=3.6"
[package.dependencies]
django = ">=3.0"
pytz = "*"
[[package]]
name = "pillow"
version = "9.5.0"
description = "Python Imaging Library (Fork)"
category = "main"
optional = false
python-versions = ">=3.7"
[package.extras]
docs = ["furo", "olefile", "sphinx (>=2.4)", "sphinx-copybutton", "sphinx-inline-tabs", "sphinx-removed-in", "sphinxext-opengraph"]
tests = ["check-manifest", "coverage", "defusedxml", "markdown2", "olefile", "packaging", "pyroma", "pytest", "pytest-cov", "pytest-timeout"]
[[package]]
name = "psycopg2"
version = "2.9.7"
description = "psycopg2 - Python-PostgreSQL Database Adapter"
category = "main"
optional = false
python-versions = ">=3.6"
[[package]]
name = "pydantic"
version = "2.3.0"
description = "Data validation using Python type hints"
category = "main"
optional = false
python-versions = ">=3.7"
[package.dependencies]
annotated-types = ">=0.4.0"
pydantic-core = "2.6.3"
typing-extensions = ">=4.6.1"
[package.extras]
email = ["email-validator (>=2.0.0)"]
[[package]]
name = "pydantic-core"
version = "2.6.3"
description = ""
category = "main"
optional = false
python-versions = ">=3.7"
[package.dependencies]
typing-extensions = ">=4.6.0,<4.7.0 || >4.7.0"
[[package]]
name = "pytz"
version = "2023.3"
description = "World timezone definitions, modern and historical"
category = "main"
optional = false
python-versions = "*"
[[package]]
name = "segno"
version = "1.5.2"
description = "QR Code and Micro QR Code generator for Python 2 and Python 3"
category = "main"
optional = false
python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,>=2.7"
[[package]]
name = "sqlparse"
version = "0.4.4"
description = "A non-validating SQL parser."
category = "main"
optional = false
python-versions = ">=3.5"
[package.extras]
dev = ["flake8", "build"]
doc = ["sphinx"]
test = ["pytest", "pytest-cov"]
[[package]]
name = "typing-extensions"
version = "4.7.1"
description = "Backported and Experimental Type Hints for Python 3.7+"
category = "main"
optional = false
python-versions = ">=3.7"
[[package]]
name = "tzdata"
version = "2023.3"
description = "Provider of IANA time zone data"
category = "main"
optional = false
python-versions = ">=2"
[[package]]
name = "uwsgi"
version = "2.0.22"
description = "The uWSGI server"
category = "main"
optional = false
python-versions = "*"
[metadata]
lock-version = "1.1"
python-versions = "^3.10"
content-hash = "6e065bbdff5da7659973fa67491d6093c83b8e57d4e8dde6968ee846d382bf65"
[metadata.files]
annotated-types = []
asgiref = []
crispy-bootstrap5 = []
django = []
django-crispy-forms = []
django-filter = []
django-qr-code = []
djangorestframework = []
pillow = []
psycopg2 = []
pydantic = []
pydantic-core = []
pytz = []
segno = []
sqlparse = []
typing-extensions = []
tzdata = []
uwsgi = []

23
pyproject.toml Normal file
View File

@ -0,0 +1,23 @@
[tool.poetry]
name = "shimatta-kenkyusho"
version = "0.1.0"
description = "Shimatta Lab Inventory System"
authors = ["Mario Hüttel <mario.huettel@gmx.net>"]
license = "GPLv2"
[tool.poetry.dependencies]
python = "^3.10"
Django = "~4.2.5"
django-qr-code = "^3.1.1"
djangorestframework = "^3.14.0"
django-filter = "^23.2"
psycopg2 = "^2.9.7"
Pillow = "^9.3.0"
django-crispy-forms = "^2.0"
crispy-bootstrap5 = "^0.7"
uwsgi = "^2.0.22"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

View File

@ -1,25 +0,0 @@
asgiref==3.4.1
astroid==2.6.5
crispy-bootstrap5==0.6
Django==3.2.5
django-crispy-forms==1.13.0
django-filter==2.4.0
django-qr-code==2.2.0
django-rest-framework==0.1.0
django-tex==1.1.9.post1
djangorestframework==3.12.4
isort==5.9.3
Jinja2==3.0.1
lazy-object-proxy==1.6.0
MarkupSafe==2.0.1
mccabe==0.6.1
Pillow==8.3.1
psycopg2==2.9.1
pylint==2.9.6
pytz==2021.1
qrcode==7.2
segno==1.3.3
six==1.16.0
sqlparse==0.4.1
toml==0.10.2
wrapt==1.12.1

View File

@ -1,7 +1,6 @@
from django.urls import include, path
from django.urls import include, path, re_path
from rest_framework import routers
from .views import *
from django.conf.urls import url
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
@ -17,6 +16,6 @@ router.register(r'parts/component-param-types', PartsComponentParameterTypeViewS
urlpatterns = [
path('', include(router.urls)),
url(r'^token-auth/', ObtainExpiringAuthToken.as_view()),
url(r'^token-logout/', TokenLogout.as_view()),
re_path(r'^token-auth/', ObtainExpiringAuthToken.as_view()),
re_path(r'^token-logout/', TokenLogout.as_view()),
]

View File

@ -223,7 +223,6 @@ class ComponentView(LoginRequiredMixin, KeepSearchParamMixin, BaseTemplateMixin,
search_fragments = search_string.strip().split()
for search in search_fragments:
queryset = queryset.filter(Q(name__icontains = search) | Q(manufacturer__name__icontains = search) | Q(package__name__icontains = search))
return queryset
def get_component_queryset_from_advanced_search(self, cleaned_data):

View File

@ -8,6 +8,23 @@ 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/
Development mode is selected by setting env variable
- DJANGO_DEV_MODE
The following environment variables have to be set for Production Mode but might be optional for dev mode:
- DJANGO_SECRET_KEY
- DJANGO_ALLOWED_HOST
- DJANGO_STATIC_ROOT
- DJANGO_MEDIA_URL
- DJANGO_MEDIA_ROOT
- DJANGO_POSTGRESQL_SOCKET
The following can be set
- DJANGO_SECURE_HSTS_SECONDS (defaults to 120)
"""
from pathlib import Path
@ -16,17 +33,34 @@ import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
def get_env_value(env_variable, default=None):
try:
return os.environ[env_variable]
except KeyError:
if default is not None:
return default
error_msg = 'Set the {} environment variable'.format(env_variable)
raise Exception(error_msg)
RUNS_IN_DEV_MODE = True if get_env_value('DJANGO_DEV_MODE', default=False) != False else False
# 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-vq_@ue3ul@&4bz7wkcpf3pjrwf8o$7g!z-rw$ftr-$)7l3*m=^'
SECRET_KEY=''
if RUNS_IN_DEV_MODE:
SECRET_KEY = get_env_value('DJANGO_SECRET_KEY',
default='django-insecure-vq_@ue3ul@&4bz7wkcpf3pjrwf8o$7g!z-rw$ftr-$)7l3*m=^')
else:
SECRET_KEY = get_env_value('DJANGO_SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
DEBUG = True if RUNS_IN_DEV_MODE else False
ALLOWED_HOSTS = ['localhost']
if not RUNS_IN_DEV_MODE:
ALLOWED_HOSTS = ['localhost', get_env_value('DJANGO_ALLOWED_HOST')]
# Application definition
@ -96,10 +130,34 @@ WSGI_APPLICATION = 'shimatta_kenkyusho.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
DATABASES = {}
if RUNS_IN_DEV_MODE:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
else:
b_pw = ''
try:
db_pw = get_env_value('DJANGO_POSTGRESQL_PW')
except:
pass
db_user = ''
try:
db_user = get_env_value('DJANGO_POSTGRESQL_USER')
except:
pass
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'shimatta_kenkyusho',
'USER': db_user,
'PASSWORD': db_pw,
'HOST': get_env_value('DJANGO_POSTGRESQL_SOCKET'),
}
}
@ -167,12 +225,17 @@ STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = None
if not RUNS_IN_DEV_MODE:
STATIC_ROOT = get_env_value('DJANGO_STATIC_ROOT')
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = get_env_value('DJANGO_MEDIA_URL', default='/media/')
MEDIA_ROOT = get_env_value('DJANGO_MEDIA_ROOT', default=os.path.join(BASE_DIR, "media"))
LOGIN_URL = '/login'
LOGIN_REDIRECT_URL = '/'
@ -182,4 +245,17 @@ SHIMATTA_KENKYUSHO_TITLE = 'しまった・研究所'
CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5"
CRISPY_TEMPLATE_PACK = "bootstrap5"
CRISPY_TEMPLATE_PACK = "bootstrap5"
# Production only settings
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = get_env_value('DJANGO_SECURE_HSTS_SECONDS', default=120)
if RUNS_IN_DEV_MODE:
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
SECURE_SSL_REDIRECT = False

View File

@ -1,234 +0,0 @@
"""
Django settings for shimatta_kenkyusho project.
Generated by 'django-admin startproject' using Django 3.2.5.
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/
The following environment variables have to be set:
- DJANGO_SECRET_KEY
- DJANGO_ALLOWED_HOST
- DJANGO_STATIC_ROOT
- DJANGO_MEDIA_URL
- DJANGO_MEDIA_ROOT
- DJANGO_POSTGRESQL_SOCKET
The following can be set
- DJANGO_SECURE_HSTS_SECONDS (defaults to 120)
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
def get_env_value(env_variable, default=None):
try:
return os.environ[env_variable]
except KeyError:
if default is not None:
return default
error_msg = 'Set the {} environment variable'.format(env_variable)
raise Exception(error_msg)
# 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 = get_env_value('DJANGO_SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['localhost', get_env_value('DJANGO_ALLOWED_HOST')]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'parts.apps.PartsConfig',
'api.apps.ApiConfig',
'rest_framework.authtoken',
'django_filters',
'qr_code',
'rest_framework',
'crispy_forms',
'crispy_bootstrap5',
'django.forms',
]
FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
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 = 'shimatta_kenkyusho.urls'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
'qr-code': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'qr-code-cache',
'TIMEOUT': 3600
}
}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(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 = 'shimatta_kenkyusho.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
db_pw = ''
try:
db_pw = get_env_value('DJANGO_POSTGRESQL_PW')
except:
pass
db_user = ''
try:
db_user = get_env_value('DJANGO_POSTGRESQL_USER')
except:
pass
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'shimatta_kenkyusho',
'USER': db_user,
'PASSWORD': db_pw,
'HOST': get_env_value('DJANGO_POSTGRESQL_SOCKET'),
}
}
# 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',
},
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'api.ExpiringAuthToken.ExpiringTokenAuthentication',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 10,
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
],
'DEFAULT_THROTTLE_RATES': {
'anon': '100/hour',
'user': '2000/hour'
}
}
REST_FRAMEWORK_TOKEN_EXPIRE_HOURS = 4
# 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/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = get_env_value('DJANGO_STATIC_ROOT')
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
MEDIA_URL = get_env_value('DJANGO_MEDIA_URL')
MEDIA_ROOT = get_env_value('DJANGO_MEDIA_ROOT')
LOGIN_URL = '/login'
LOGIN_REDIRECT_URL = '/'
SHIMATTA_KENKYUSHO_TITLE = 'しまった・研究所'
CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5"
CRISPY_TEMPLATE_PACK = "bootstrap5"
# Production only settings
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = get_env_value('DJANGO_SECURE_HSTS_SECONDS', default=120)

View File

@ -14,14 +14,13 @@ Including another URLconf
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from django.urls import path, include, re_path
from django.conf.urls.static import static
from django.conf import settings
from parts import views as parts_views
urlpatterns = [
url(r'^admin/login/', parts_views.login_view),
re_path(r'^admin/login/', parts_views.login_view),
path('admin/', admin.site.urls),
path('api/v1/', include('api.urls'), name='api-root'),
path('', include('parts.urls')),

View File

@ -11,6 +11,6 @@ import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shimatta_kenkyusho.settings_production')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shimatta_kenkyusho.settings')
application = get_wsgi_application()