Module parameters centralised in parameter.py

This commit is contained in:
Dirk Alders 2024-10-07 00:37:31 +02:00
parent 2adbd0da7d
commit 68e89f85a1
5 changed files with 93 additions and 55 deletions

View File

@ -12,11 +12,16 @@ Add the following line to the list ```INSTALLED_APPS```:
'mycreole.apps.MycreoleConfig',
```
### Parameter
All parameters can be added in the django ```settings.py``` or in a ```config.py``` in the root django folder. The definitions in the ```config.py``` will be used before the definitions in ```settings.py```.
#### MYCREOLE_ROOT
Define the folder, where the attachments are stored with the following line:
```
MYCREOLE_ROOT = os.path.join(BASE_DIR, 'data', 'pages')
```
#### MYCREOLE_ATTACHMENT_ACCESS
Define the methods to grant or deny the access to the attachments by:
```
MYCREOLE_ATTACHMENT_ACCESS = {
@ -25,6 +30,7 @@ MYCREOLE_ATTACHMENT_ACCESS = {
}
```
#### MYCREOLE_BAR
Define the methods to extend the navigationbar and menubar by this statement:
```
MYCREOLE_BAR = {
@ -48,13 +54,13 @@ def help_on_creole(request):
attachment_path = os.path.join(settings.MYCREOLE_ROOT, 'creole_help_page')
html = mycreole.render(request, creole.help.MYCREOLE_HELP, self.attachment_path)
```
### Usage of next_achor
TBD
Defines the additional html anchor, which will be used after an upload.
### Usage of macros
You can give a dictonary as macros parameter to the render method, to define your own macros. Here an example of such a dict:
```
macros={
'mymacro': method_to_be_called,
}
}
```

View File

@ -4,14 +4,12 @@ from django.urls.base import reverse
from .help import MYCREOLE_HELP
import importlib
import os
from mycreole import parameter
import shutil
def get_full_path(rel_path):
try:
return os.path.join(settings.MYCREOLE_ROOT, *rel_path.split('/'))
except AttributeError:
raise AttributeError("You need to define a root directory for mycreole in settings.py: MYCREOLE_ROOT")
return os.path.join(parameter.get(parameter.MYCREOLE_ROOT), *rel_path.split('/'))
def delete_attachment_target_path(attachment_target_path):

View File

@ -5,6 +5,7 @@ import logging
import importlib
from mycreole import url_upload
from mycreole import parameter
from themes import color_icon_url
try:
@ -17,26 +18,17 @@ NEW_ATTACHMENT_UID = 'new_attachment'
def context_adaption(context, request, title, rel_path, **kwargs):
def get_method(import_string):
class_data = import_string.split(".")
module_path = ".".join(class_data[:-1])
class_str = class_data[-1]
#
module = importlib.import_module(module_path)
return getattr(module, class_str)
def log_warning(method_name, e):
logger.warning('Could not import %s method for extending bars: %s - %s', method_name, type(e).__name__, e)
context.set_additional_title(title)
for key in ["menubar", "navibar"]:
try:
method_name = settings.MYCREOLE_BAR[key]
except (AttributeError, KeyError) as e:
log_warning(key, e)
else:
method = get_method(method_name)
method(context, request, caller_name="attachments")
add_bar = parameter.get(parameter.MYCREOLE_BAR)
next = kwargs.get('next')
for key in add_bar:
method = add_bar[key]
if method is not None:
if next.find("/", 2) != -1:
rp = next[next.find("/", 2) + 1:]
else:
rp = None
method(context, request, caller_name="attachments", rel_path=rp)
add_new(request, context[context.ACTIONBAR], rel_path, kwargs.get('next'))
for key in kwargs:
context[key] = kwargs[key]

66
parameter.py Normal file
View File

@ -0,0 +1,66 @@
import config
from django.conf import settings
import importlib
import os
MYCREOLE_ATTACHMENT_ACCESS = "MYCREOLE_ATTACHMENT_ACCESS"
ACCESS_READ = 'read'
ACCESS_MODIFY = 'modify'
MYCREOLE_BAR = "MYCREOLE_BAR"
BAR_MENUBAR = "menubar"
BAR_NAVIBAR = "navibar"
MYCREOLE_ROOT = "MYCREOLE_ROOT"
def no_access(*args, **kwargs):
return False
DEFAULTS = {
MYCREOLE_ATTACHMENT_ACCESS: {
ACCESS_READ: 'mycreole.parameter.no_access',
ACCESS_MODIFY: 'mycreole.parameter.no_access',
},
MYCREOLE_BAR: {
BAR_MENUBAR: None,
BAR_NAVIBAR: None,
},
MYCREOLE_ROOT: os.path.join(settings.BASE_DIR, 'data', 'mycreole'),
}
def __get_object_by_name__(object_name):
class_data = object_name.split(".")
module_path = ".".join(class_data[:-1])
class_str = class_data[-1]
#
module = importlib.import_module(module_path)
return getattr(module, class_str)
def get(key):
# take data from config, settings or defaults
try:
data = getattr(config, key)
except AttributeError:
try:
data = getattr(settings, key)
except AttributeError:
data = DEFAULTS.get(key)
# adapt the data
if key in [MYCREOLE_BAR, MYCREOLE_ATTACHMENT_ACCESS]:
# Change given string to object
rv = {}
for skey in DEFAULTS[key]:
# take the value from data or the default
if skey in data:
value = data[skey]
else:
value = DEFAULTS[key][skey]
# take the object or None
if value is not None:
rv[skey] = __get_object_by_name__(value)
else:
rv[skey] = None
return rv
return data

View File

@ -9,6 +9,7 @@ from mycreole import url_upload, url_attachment, url_delete
import logging
import mycreole
import os
from mycreole import parameter
import stringtools
import themes
from django.contrib import messages
@ -20,15 +21,6 @@ except ImportError:
logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
def get_method(import_string):
class_data = import_string.split(".")
module_path = ".".join(class_data[:-1])
class_str = class_data[-1]
#
module = importlib.import_module(module_path)
return getattr(module, class_str)
def get_next(request):
if not request.POST:
return request.GET.get('next', '/')
@ -37,25 +29,9 @@ def get_next(request):
def access(access_type, request, rel_path):
def log_warning(access_type, e):
logger.warning('Could not import %s_access method for checking access rights: %s - %s', access_type, type(e).__name__, e)
try:
method_name = settings.MYCREOLE_ATTACHMENT_ACCESS[access_type]
except (AttributeError, KeyError) as e:
log_warning(access_type, e)
return False
else:
if method_name in [True, None]:
return True
elif method_name is False:
return False
else:
try:
return get_method(method_name)(request, rel_path)
except AttributeError as e:
log_warning(access_type, e)
return False
access = parameter.get(parameter.MYCREOLE_ATTACHMENT_ACCESS)
method = access[access_type]
return method(request, rel_path)
def mycreole_attachment(request, rel_path):
@ -93,7 +69,7 @@ def mycreole_upload(request, rel_path):
try:
os.makedirs(os.path.dirname(full_path), exist_ok=True)
except PermissionError:
raise PermissionError("Ensure that we have access to MYCREOLE_ROOT=%s" % repr(settings.MYCREOLE_ROOT))
raise PermissionError("Ensure that we have access to MYCREOLE_ROOT=%s" % repr(parameter.get(parameter.MYCREOLE_ROOT)))
else:
with open(full_path, 'wb') as fh:
fh.write(request.FILES['file'].read())