python: simplify server configuration

This commit is contained in:
vanyauhalin
2023-07-13 16:17:29 +04:00
parent 4ea0760803
commit 988da27e3f
6 changed files with 83 additions and 184 deletions

View File

@ -1,21 +1,87 @@
#!/usr/bin/env python from os import environ
"""Django's command-line utility for administrative tasks.""" from pathlib import Path
import os from sys import argv
import sys from uuid import uuid1
from django import setup
from django.conf import settings
from django.core.management import execute_from_command_line
from django.core.management.commands.runserver import Command as RunServer
from django.conf.urls.static import static
from django.urls import path
from src.common import string
from src.views import actions, index
def debug():
env = environ.get('DEBUG')
return string.boolean(env, True)
def main(): def address():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings') if settings.DEBUG:
try: return RunServer.default_addr
from django.core.management import execute_from_command_line return '0.0.0.0'
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)
def port():
env = environ.get('PORT')
if env:
return int(env)
return RunServer.default_port
def configuration():
file = Path(__file__)
base_dir = file.parent
static_root = base_dir.joinpath('static')
static_url = f'{static_root.name}/'
return {
'ALLOWED_HOSTS': [
'*'
],
'BASE_DIR': f'{base_dir}',
'DEBUG': debug(),
'MIDDLEWARE': [
'src.utils.historyManager.CorsHeaderMiddleware'
],
'ROOT_URLCONF': __name__,
'SECRET_KEY': uuid1(),
'STATIC_ROOT': f'{static_root}',
'STATIC_URL': static_url,
'TEMPLATES': [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
'templates'
]
}
]
}
def routers():
main = [
path('', index.default),
path('convert', actions.convert),
path('create', actions.createNew),
path('csv', actions.csv),
path('download', actions.download),
path('downloadhistory', actions.downloadhistory),
path('edit', actions.edit),
path('files', actions.files),
path('reference', actions.reference),
path('remove', actions.remove),
path('rename', actions.rename),
path('saveas', actions.saveAs),
path('track', actions.track),
path('upload', actions.upload)
]
main += static(
settings.STATIC_URL,
document_root=settings.STATIC_ROOT
)
return main
settings.configure(**configuration())
urlpatterns = routers()
RunServer.default_addr = address()
RunServer.default_port = port()
setup()
if __name__ == '__main__': if __name__ == '__main__':
main() execute_from_command_line(argv)

View File

@ -1,109 +0,0 @@
"""
Django settings for example project.
Generated by 'django-admin startproject' using Django 2.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
import mimetypes
from src.configuration import ConfigurationManager
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '7a5qnm_bv)iskjhx%4cbwwdmjev03%zewm=3@4s*uz)el#ds5o'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = [
'*'
]
X_FRAME_OPTIONS = 'ALLOWALL'
XS_SHARING_ALLOWED_METHODS = ['GET']
# Application definition
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.sessions',
]
MIDDLEWARE = [
'src.utils.historyManager.CorsHeaderMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'src.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [ 'templates' ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
],
},
},
]
WSGI_APPLICATION = 'src.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = []
# Internationalization
# https://docs.djangoproject.com/en/3.1/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.1/howto/static-files/
mimetypes.add_type("text/javascript", ".js", True)
STATIC_ROOT = ''
STATIC_URL = '/static/'
config_manager = ConfigurationManager()
STATICFILES_DIRS = (
os.path.join('static'),
os.path.join('assets/sample'),
f'{config_manager.storage_path()}'
)

View File

@ -1,41 +0,0 @@
"""
(c) Copyright Ascensio System SIA 2023
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django.urls import path, re_path
from src.views import index, actions
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('', index.default),
path('upload', actions.upload),
path('download', actions.download),
path('downloadhistory', actions.downloadhistory),
path('convert', actions.convert),
path('create', actions.createNew),
path('edit', actions.edit),
path('track', actions.track),
path('remove', actions.remove),
path('csv', actions.csv),
path('files', actions.files),
path('saveas', actions.saveAs),
path('rename', actions.rename),
path('reference', actions.reference)
]
urlpatterns += staticfiles_urlpatterns()

View File

@ -26,8 +26,8 @@ import time
import urllib.parse import urllib.parse
import magic import magic
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, FileResponse from django.http import HttpResponse, HttpResponseRedirect, FileResponse
from src import settings
from src.configuration import ConfigurationManager from src.configuration import ConfigurationManager
from . import fileUtils, historyManager from . import fileUtils, historyManager

View File

@ -22,7 +22,6 @@ import json
from . import users, fileUtils from . import users, fileUtils
from datetime import datetime from datetime import datetime
from src import settings
from src.configuration import ConfigurationManager from src.configuration import ConfigurationManager
from src.utils import docManager from src.utils import docManager
from src.utils import jwtManager from src.utils import jwtManager

View File

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