Commit 46c90874 authored by Nikos Pappas's avatar Nikos Pappas
Browse files

first commit

parents
DEBUG=True
DJANGO_WARN_LEVEL=DEBUG
DJANGO_SECRET_KEY=CHANGEME
DJANGO_TIME_ZONE='Europe/Athens'
EMD_EL_BASE_URL='https://reg-diavlos.gov.gr/'
# .gitignore for nationalRegistry project
# Static files
staticfiles/
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# Installer logs
pip-log.txt
# Translations
*.mo
*.pot
# Django stuff:
*.log
db.sqlite3
### JetBrains
.idea/*
.idea
\ No newline at end of file
# Development
This is a guide on how to start developing. We assume a Linux environment. You need the following tools preinstalled:
- python 3.8+
## Configuration
All configuration values are loaded from the `.env`.
# National Registry
Test project for a registry of evidences etc. used in [National Services Registry](https://reg-diavlos.gov.gr)
## Structure
The repository's stack is a django web application.
- `users` : A django app that hosts users info
- `evidences` : The evidences app that holds all info about evidences
- `utils` : Utils to fetch json structured evidences from National Service Registry
- `static` : CSS and JS
- `locale` : Translations
## Development
See dedicated file `Development.md` on how to start developing locally
from django.contrib import admin
from import_export import resources
from .models import Evidence
from import_export.admin import ImportExportModelAdmin
class EvidenceResource(resources.ModelResource):
class Meta:
model = Evidence
import_id_fields = ('title',)
exclude = ('id', 'updated_date',)
skip_unchanged = True
fields = (
'title',
)
class EvidenceAdmin(ImportExportModelAdmin):
resource_class = EvidenceResource
ordering = ('title', )
admin.site.register(Evidence, EvidenceAdmin)
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class EvidencesConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'evidences'
verbose_name = _('Δικαιολογητικα')
# Generated by Django 3.2.5 on 2022-01-08 00:11
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Evidence',
fields=[
('title', models.TextField(help_text='Evidence title')),
('mw_uuid', models.UUIDField(default=uuid.uuid4, editable=False, help_text='Evidence uuid', primary_key=True, serialize=False)),
('mw_id', models.CharField(help_text='Evidence id', max_length=255)),
],
options={
'verbose_name': 'Δικαιολογητικό',
'verbose_name_plural': 'Δικαιολογητικά',
},
),
]
from django.db import models
import uuid
from django.utils.translation import ugettext_lazy as _
class Evidence(models.Model):
title = models.TextField(help_text=_('Evidence title'))
mw_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, help_text=_('Evidence uuid'))
mw_id = models.CharField(max_length=255, help_text=_('Evidence id'))
class Meta:
verbose_name = 'Δικαιολογητικό'
verbose_name_plural = 'Δικαιολογητικά'
def __str__(self):
return self.title
from rest_framework import serializers
from .models import Evidence
class EvidenceSerializer(serializers.ModelSerializer):
class Meta:
model = Evidence
fields = ('title', 'mw_uuid', 'mw_id')
\ No newline at end of file
from django.test import TestCase
# Create your tests here.
from django.urls import include, path
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'evidences', views.EvidenceViewSet)
urlpatterns = [
path('get_evidences_from_emd/', views.get_evidences_from_emd, name='get_evidences_from_emd'),
path('', include(router.urls)),
]
\ No newline at end of file
from django.contrib import admin
from rest_framework import viewsets
from rest_framework import status
from rest_framework.response import Response
# App specific imports
from .models import Evidence
from .serializers import EvidenceSerializer
from utils import get_evidences_from_mw
admin.autodiscover()
class EvidenceViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows evidences to be viewed or edited.
"""
queryset = Evidence.objects.all().order_by('title')
serializer_class = EvidenceSerializer
def get_evidences_from_emd(request):
evidences_json = get_evidences_from_mw.fetch_evidences()
if evidences_json is None:
return Response({}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
return Response(evidences_json, status=status.HTTP_200_OK)
# 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 npappas@admin.grnet.gr, 2021.
#
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2022-01-08 01:08+0200\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"
#: nationalRegistry/settings.py:107
msgid "English"
msgstr "Αγγλικά"
#: nationalRegistry/settings.py:108
msgid "Greek"
msgstr "Ελληνικά"
#: templates/admin/import_export/import.html:11
msgid "Import"
msgstr "Εισαγωγή"
#: templates/admin/import_export/import.html:20
msgid ""
"Below is a preview of data to be imported. If you are satisfied with the "
"results, click 'Confirm import'"
msgstr ""
#: templates/admin/import_export/import.html:23
msgid "Confirm import"
msgstr ""
#: templates/admin/import_export/import.html:39
msgid "This importer will import the following fields: "
msgstr ""
#: templates/admin/import_export/import.html:61
msgid "Submit"
msgstr ""
#: templates/admin/import_export/import.html:72
#: templates/admin/import_export/import.html:101
msgid "Errors"
msgstr ""
#: templates/admin/import_export/import.html:83
msgid "Line number"
msgstr ""
#: templates/admin/import_export/import.html:93
msgid "Some rows failed to validate"
msgstr ""
#: templates/admin/import_export/import.html:95
msgid ""
"Please correct these errors in your data where possible, then reupload it "
"using the form above."
msgstr ""
#: templates/admin/import_export/import.html:100
msgid "Row"
msgstr ""
#: templates/admin/import_export/import.html:127
msgid "Non field specific"
msgstr ""
#: templates/admin/import_export/import.html:148
msgid "Preview"
msgstr ""
#: templates/admin/import_export/import.html:163
msgid "New"
msgstr ""
#: templates/admin/import_export/import.html:165
msgid "Skipped"
msgstr ""
#: templates/admin/import_export/import.html:167
msgid "Delete"
msgstr ""
#: templates/admin/import_export/import.html:169
msgid "Update"
msgstr ""
#: users/apps.py:9 users/models.py:15
msgid "Users"
msgstr "Χρήστες"
#: users/models.py:8
msgid "AFM"
msgstr "ΑΦΜ"
#: users/models.py:11
msgid "Set True if user is allowed to enter admin interface"
msgstr ""
#: users/models.py:14
msgid "User"
msgstr "Χρήστης"
#!/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', 'nationalRegistry.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()
"""
ASGI config for nationalRegistry 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', 'nationalRegistry.settings')
application = get_asgi_application()
"""
Django settings for nationalRegistry project.
Author: Nikos Pappas
Email: npappas@admin.grnet.gr
"""
from pathlib import Path
from django.utils.translation import ugettext_lazy as _
import environ
import os
env = environ.Env(
DEBUG=(bool, False),
DJANGO_TIME_ZONE=(str, 'Europe/Athens'),
DJANGO_WARN_LEVEL=(str, 'DEBUG')
)
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
SITE_ROOT = os.path.dirname(os.path.realpath(__name__))
# Take environment variables from .env file
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))
SECRET_KEY = env('DJANGO_SECRET_KEY')
DEBUG = env('DEBUG')
ALLOWED_HOSTS = ['*'] # Allow any hosts
# APPEND_SLASH = False # Disable the necessity of ending '/' in urls
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3rd party apps
'rest_framework', # DRF
'drf_spectacular', # Swagger - openAPI 3.0
'import_export', # Easy import-exporting data to/from models
# registry apps
'users',
'evidences',
]
AUTH_USER_MODEL = 'users.user' # Extended User model
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 = 'nationalRegistry.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 = 'nationalRegistry.wsgi.application'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
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
LOCALE_PATHS = (os.path.join(SITE_ROOT, 'locale'),)
LANGUAGE_CODE = 'el'
LANGUAGES = (
('en', _('English')),
('el', _('Greek'))
)
TIME_ZONE = env('DJANGO_TIME_ZONE')
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# Default primary key field type
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Logging
LOGGING = {
'version': 1, # The version number of our log
'disable_existing_loggers': False, # Disable django internal loggers
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': BASE_DIR / 'debug.log',
},
},
'loggers': {
'': {
'handlers': ['file', 'console'], # Logs to both console and file
'level': env('DJANGO_WARN_LEVEL'),
'propagate': True,
},
'asyncio': {
'level': 'WARNING',
},
},
}
# Rest framework settings
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', # schema
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": 50,
}
# Swagger settings
SPECTACULAR_SETTINGS = {
'TITLE': 'Registry API',
'DESCRIPTION': 'National Registry API for evidences',
'VERSION': '1.0.0',
'FILTER': 'true',
# OTHER SETTINGS
}
"""nationalRegistry URL Configuration"""
from django.contrib import admin
from django.urls import path, include
from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView
from .settings import DEBUG
# Default urls
urlpatterns = [
path('admin/', admin.site.urls),
]
if DEBUG:
urlpatterns += [
path("api-auth/", include("rest_framework.urls", namespace="rest_framework")),
]
# OpenAPI 3
urlpatterns += [
# Schema download
path('docs/schema/', SpectacularAPIView.as_view(), name="schema"),
# Optional UI
path('docs/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),
path('docs/schema/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'),
]
# App based urls
urlpatterns += [
path('api/', include('evidences.urls')),
path('users/', include('users.urls')),
]
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment