瀏覽代碼

Module parameters centralised in parameter.py

make_mycreole_indenpendent_from_patt
Dirk Alders 3 週之前
父節點
當前提交
68e89f85a1
共有 5 個檔案被更改,包括 93 行新增55 行删除
  1. 9
    3
      README.md
  2. 2
    4
      __init__.py
  3. 11
    19
      context.py
  4. 66
    0
      parameter.py
  5. 5
    29
      views.py

+ 9
- 3
README.md 查看文件

@@ -12,11 +12,16 @@ Add the following line to the list ```INSTALLED_APPS```:
12 12
 'mycreole.apps.MycreoleConfig',
13 13
 ``` 
14 14
 
15
+### Parameter
16
+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```.
17
+
18
+#### MYCREOLE_ROOT
15 19
 Define the folder, where the attachments are stored with the following line:
16 20
 ```
17 21
 MYCREOLE_ROOT = os.path.join(BASE_DIR, 'data', 'pages')
18 22
 ```
19 23
 
24
+#### MYCREOLE_ATTACHMENT_ACCESS
20 25
 Define the methods to grant or deny the access to the attachments by:
21 26
 ```
22 27
 MYCREOLE_ATTACHMENT_ACCESS = {
@@ -25,6 +30,7 @@ MYCREOLE_ATTACHMENT_ACCESS = {
25 30
 }
26 31
 ```
27 32
 
33
+#### MYCREOLE_BAR
28 34
 Define the methods to extend the navigationbar and menubar by this statement:
29 35
 ```
30 36
 MYCREOLE_BAR = {
@@ -48,13 +54,13 @@ def help_on_creole(request):
48 54
     attachment_path = os.path.join(settings.MYCREOLE_ROOT, 'creole_help_page')
49 55
     html = mycreole.render(request, creole.help.MYCREOLE_HELP, self.attachment_path)
50 56
 ```
51
-
52 57
 ### Usage of next_achor
53
-TBD
58
+Defines the additional html anchor, which will be used after an upload.
54 59
 
55 60
 ### Usage of macros
56 61
 You can give a dictonary as macros parameter to the render method, to define your own macros. Here an example of such a dict:
57 62
 ```
58 63
 macros={
59 64
     'mymacro': method_to_be_called,
60
-}
65
+}
66
+```

+ 2
- 4
__init__.py 查看文件

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

+ 11
- 19
context.py 查看文件

@@ -5,6 +5,7 @@ import logging
5 5
 import importlib
6 6
 
7 7
 from mycreole import url_upload
8
+from mycreole import parameter
8 9
 from themes import color_icon_url
9 10
 
10 11
 try:
@@ -17,26 +18,17 @@ NEW_ATTACHMENT_UID = 'new_attachment'
17 18
 
18 19
 
19 20
 def context_adaption(context, request, title, rel_path, **kwargs):
20
-    def get_method(import_string):
21
-        class_data = import_string.split(".")
22
-        module_path = ".".join(class_data[:-1])
23
-        class_str = class_data[-1]
24
-        #
25
-        module = importlib.import_module(module_path)
26
-        return getattr(module, class_str)
27
-
28
-    def log_warning(method_name, e):
29
-        logger.warning('Could not import %s method for extending bars: %s - %s', method_name, type(e).__name__, e)
30
-
31 21
     context.set_additional_title(title)
32
-    for key in ["menubar", "navibar"]:
33
-        try:
34
-            method_name = settings.MYCREOLE_BAR[key]
35
-        except (AttributeError, KeyError) as e:
36
-            log_warning(key, e)
37
-        else:
38
-            method = get_method(method_name)
39
-            method(context, request, caller_name="attachments")
22
+    add_bar = parameter.get(parameter.MYCREOLE_BAR)
23
+    next = kwargs.get('next')
24
+    for key in add_bar:
25
+        method = add_bar[key]
26
+        if method is not None:
27
+            if next.find("/", 2) != -1:
28
+                rp = next[next.find("/", 2) + 1:]
29
+            else:
30
+                rp = None
31
+            method(context, request, caller_name="attachments", rel_path=rp)
40 32
     add_new(request, context[context.ACTIONBAR], rel_path, kwargs.get('next'))
41 33
     for key in kwargs:
42 34
         context[key] = kwargs[key]

+ 66
- 0
parameter.py 查看文件

@@ -0,0 +1,66 @@
1
+import config
2
+from django.conf import settings
3
+import importlib
4
+import os
5
+
6
+MYCREOLE_ATTACHMENT_ACCESS = "MYCREOLE_ATTACHMENT_ACCESS"
7
+ACCESS_READ = 'read'
8
+ACCESS_MODIFY = 'modify'
9
+MYCREOLE_BAR = "MYCREOLE_BAR"
10
+BAR_MENUBAR = "menubar"
11
+BAR_NAVIBAR = "navibar"
12
+MYCREOLE_ROOT = "MYCREOLE_ROOT"
13
+
14
+
15
+def no_access(*args, **kwargs):
16
+    return False
17
+
18
+
19
+DEFAULTS = {
20
+    MYCREOLE_ATTACHMENT_ACCESS: {
21
+        ACCESS_READ: 'mycreole.parameter.no_access',
22
+        ACCESS_MODIFY: 'mycreole.parameter.no_access',
23
+    },
24
+    MYCREOLE_BAR: {
25
+        BAR_MENUBAR: None,
26
+        BAR_NAVIBAR: None,
27
+    },
28
+    MYCREOLE_ROOT: os.path.join(settings.BASE_DIR, 'data', 'mycreole'),
29
+}
30
+
31
+
32
+def __get_object_by_name__(object_name):
33
+    class_data = object_name.split(".")
34
+    module_path = ".".join(class_data[:-1])
35
+    class_str = class_data[-1]
36
+    #
37
+    module = importlib.import_module(module_path)
38
+    return getattr(module, class_str)
39
+
40
+
41
+def get(key):
42
+    # take data from config, settings or defaults
43
+    try:
44
+        data = getattr(config, key)
45
+    except AttributeError:
46
+        try:
47
+            data = getattr(settings, key)
48
+        except AttributeError:
49
+            data = DEFAULTS.get(key)
50
+    # adapt the data
51
+    if key in [MYCREOLE_BAR, MYCREOLE_ATTACHMENT_ACCESS]:
52
+        # Change given string to object
53
+        rv = {}
54
+        for skey in DEFAULTS[key]:
55
+            # take the value from data or the default
56
+            if skey in data:
57
+                value = data[skey]
58
+            else:
59
+                value = DEFAULTS[key][skey]
60
+            # take the object or None
61
+            if value is not None:
62
+                rv[skey] = __get_object_by_name__(value)
63
+            else:
64
+                rv[skey] = None
65
+        return rv
66
+    return data

+ 5
- 29
views.py 查看文件

@@ -9,6 +9,7 @@ from mycreole import url_upload, url_attachment, url_delete
9 9
 import logging
10 10
 import mycreole
11 11
 import os
12
+from mycreole import parameter
12 13
 import stringtools
13 14
 import themes
14 15
 from django.contrib import messages
@@ -20,15 +21,6 @@ except ImportError:
20 21
 logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
21 22
 
22 23
 
23
-def get_method(import_string):
24
-    class_data = import_string.split(".")
25
-    module_path = ".".join(class_data[:-1])
26
-    class_str = class_data[-1]
27
-    #
28
-    module = importlib.import_module(module_path)
29
-    return getattr(module, class_str)
30
-
31
-
32 24
 def get_next(request):
33 25
     if not request.POST:
34 26
         return request.GET.get('next', '/')
@@ -37,25 +29,9 @@ def get_next(request):
37 29
 
38 30
 
39 31
 def access(access_type, request, rel_path):
40
-    def log_warning(access_type, e):
41
-        logger.warning('Could not import %s_access method for checking access rights: %s - %s', access_type, type(e).__name__, e)
42
-
43
-    try:
44
-        method_name = settings.MYCREOLE_ATTACHMENT_ACCESS[access_type]
45
-    except (AttributeError, KeyError) as e:
46
-        log_warning(access_type, e)
47
-        return False
48
-    else:
49
-        if method_name in [True, None]:
50
-            return True
51
-        elif method_name is False:
52
-            return False
53
-        else:
54
-            try:
55
-                return get_method(method_name)(request, rel_path)
56
-            except AttributeError as e:
57
-                log_warning(access_type, e)
58
-                return False
32
+    access = parameter.get(parameter.MYCREOLE_ATTACHMENT_ACCESS)
33
+    method = access[access_type]
34
+    return method(request, rel_path)
59 35
 
60 36
 
61 37
 def mycreole_attachment(request, rel_path):
@@ -93,7 +69,7 @@ def mycreole_upload(request, rel_path):
93 69
             try:
94 70
                 os.makedirs(os.path.dirname(full_path), exist_ok=True)
95 71
             except PermissionError:
96
-                raise PermissionError("Ensure that we have access to MYCREOLE_ROOT=%s" % repr(settings.MYCREOLE_ROOT))
72
+                raise PermissionError("Ensure that we have access to MYCREOLE_ROOT=%s" % repr(parameter.get(parameter.MYCREOLE_ROOT)))
97 73
             else:
98 74
                 with open(full_path, 'wb') as fh:
99 75
                     fh.write(request.FILES['file'].read())

Loading…
取消
儲存