6 Ревизии

Автор SHA1 Съобщение Дата
  Dirk Alders 997594e371 Logger creation simplified преди 2 месеца
  Dirk Alders e093c48e91 Added kwargs to extern navigation method, instead of passing a modified rel_path преди 2 месеца
  Dirk Alders 68e89f85a1 Module parameters centralised in parameter.py преди 2 месеца
  Dirk Alders 2adbd0da7d README filled with helpfull information преди 2 месеца
  Dirk Alders 2abea3c4ae Added the possibility to pass a macro filter to the render methods преди 3 месеца
  Dirk Alders 8a2da2b843 Make mycreole independent from patt преди 3 месеца
променени са 6 файла, в които са добавени 161 реда и са изтрити 55 реда
  1. 67
    1
      README.md
  2. 7
    9
      __init__.py
  3. 11
    9
      context.py
  4. 4
    2
      help.py
  5. 66
    0
      parameter.py
  6. 6
    34
      views.py

+ 67
- 1
README.md Целия файл

@@ -1,3 +1,69 @@
1 1
 # mycreole
2 2
 
3
-Django Library Mycreole
3
+With the django library mycreole, you are abel to use the creole language to create html output in your django application.
4
+
5
+## Requirements
6
+You need to ensure that python-mycreole is available in your python environment.
7
+
8
+## Integration
9
+
10
+Clone the library in your django application.
11
+
12
+### Configurations in your settings.py
13
+Add the following line to the list ```INSTALLED_APPS```:
14
+```
15
+'mycreole.apps.MycreoleConfig',
16
+``` 
17
+
18
+### Parameter
19
+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```.
20
+
21
+#### MYCREOLE_ROOT
22
+Define the folder, where the attachments are stored with the following line:
23
+```
24
+MYCREOLE_ROOT = os.path.join(BASE_DIR, 'data', 'pages')
25
+```
26
+
27
+#### MYCREOLE_ATTACHMENT_ACCESS
28
+Define the methods to grant or deny the access to the attachments by:
29
+```
30
+MYCREOLE_ATTACHMENT_ACCESS = {
31
+    'read': 'pages.access.read_attachment',
32
+    'modify': 'pages.access.modify_attachment',
33
+}
34
+```
35
+
36
+#### MYCREOLE_BAR
37
+Define the methods to extend the navigationbar and menubar by this statement:
38
+```
39
+MYCREOLE_BAR = {
40
+    'navibar': 'pages.context.navigationbar',
41
+    'menubar': 'pages.context.menubar',
42
+}
43
+```
44
+
45
+## Usage
46
+### Creole help page
47
+In this example, you see a method in ```views.py``` which returns a creole help page:
48
+
49
+```
50
+from django.conf import settings
51
+from django.http import HttpResponse
52
+import mycreole
53
+import os
54
+
55
+
56
+def help_on_creole(request):
57
+    attachment_path = os.path.join(settings.MYCREOLE_ROOT, 'creole_help_page')
58
+    html = mycreole.render(request, creole.help.MYCREOLE_HELP, self.attachment_path)
59
+```
60
+### Usage of next_achor
61
+Defines the additional html anchor, which will be used after an upload.
62
+
63
+### Usage of macros
64
+You can give a dictonary as macros parameter to the render method, to define your own macros. Here an example of such a dict:
65
+```
66
+macros={
67
+    'mymacro': method_to_be_called,
68
+}
69
+```

+ 7
- 9
__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):
@@ -22,11 +20,11 @@ def mycreole_help_pagecontent():
22 20
     return creole.creole2html(MYCREOLE_HELP)
23 21
 
24 22
 
25
-def render_simple(text):
26
-    return creole.creole2html(text)
23
+def render_simple(text, macros=None):
24
+    return creole.creole2html(text, macros=macros)
27 25
 
28 26
 
29
-def render(request, text, attachment_target_path, next_anchor=''):
27
+def render(request, text, attachment_target_path, next_anchor='', macros=None):
30 28
     def get_attachment_name(text, state):
31 29
         end_idx = text.index(']]' if state == '[' else '}}')
32 30
         try:
@@ -84,9 +82,9 @@ def render(request, text, attachment_target_path, next_anchor=''):
84 82
                 else:
85 83
                     render_txt += '[[%s|Upload]]' % url_upload(request, rel_path, next_anchor)
86 84
                     text = text[text.index(']]' if state == '[' else '}}') + 2:]
87
-        return creole.creole2html(render_txt)
85
+        return creole.creole2html(render_txt, macros=macros)
88 86
     except:
89
-        return creole.creole2html(text)
87
+        return creole.creole2html(text, macros=macros)
90 88
 
91 89
 
92 90
 def url_delete(request, rel_path, next_anchor=''):

+ 11
- 9
context.py Целия файл

@@ -1,23 +1,25 @@
1
+from django.conf import settings
1 2
 from django.utils.translation import gettext as _
3
+
2 4
 import logging
5
+import importlib
6
+
3 7
 from mycreole import url_upload
4
-from users.context import menubar as user_menubar
5
-from patt.context import navigationbar
8
+from mycreole import parameter
6 9
 from themes import color_icon_url
7 10
 
8
-try:
9
-    from config import APP_NAME as ROOT_LOGGER_NAME
10
-except ImportError:
11
-    ROOT_LOGGER_NAME = 'root'
12
-logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
11
+logger = logging.getLogger(settings.ROOT_LOGGER_NAME).getChild(__name__)
13 12
 
14 13
 NEW_ATTACHMENT_UID = 'new_attachment'
15 14
 
16 15
 
17 16
 def context_adaption(context, request, title, rel_path, **kwargs):
18 17
     context.set_additional_title(title)
19
-    user_menubar(context[context.MENUBAR], request)
20
-    navigationbar(context, request)
18
+    add_bar = parameter.get(parameter.MYCREOLE_BAR)
19
+    for key in add_bar:
20
+        method = add_bar[key]
21
+        if method is not None:
22
+            method(context, request, caller_name="mycreole-attachments", **kwargs)
21 23
     add_new(request, context[context.ACTIONBAR], rel_path, kwargs.get('next'))
22 24
     for key in kwargs:
23 25
         context[key] = kwargs[key]

+ 4
- 2
help.py Целия файл

@@ -1,7 +1,7 @@
1 1
 MYCREOLE_HELP = """\
2 2
 = Creole Markup
3 3
 
4
-The Fields //"Description"// and //"Name"// of Tasks and Projects are interpreted as creole. \
4
+Some Fields are interpreted as creole. \
5 5
 See http://www.wikicreole.org for more details.
6 6
 
7 7
 == Text Markup
@@ -12,6 +12,8 @@ See http://www.wikicreole.org for more details.
12 12
 | Underline | {{{__text__}}} | __text__ |
13 13
 | Raw Link | {{{https://python.org}}} | https://python.org |
14 14
 | Text Link | {{{[[https://python.org|Python]]}}} | [[https://python.org|Python]] |
15
+
16
+== Additional syntax
15 17
 | Image | {{{ {{/media/theme/logo.png|logo}}     }}} | {{/media/theme/logo.png|logo}} |
16 18
 | Attachment Text Link | {{{[[attachment:file.ext|Python]]}}} |  |
17 19
 | Attachment Image | {{{ {{attachment:logo.png|logo}}     }}} |  |
@@ -115,4 +117,4 @@ results in:
115 117
 {{{
116 118
 unprocessde data! <div>
117 119
 }}}
118
-"""
120
+"""

+ 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

+ 6
- 34
views.py Целия файл

@@ -9,24 +9,12 @@ 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
15 16
 
16
-try:
17
-    from config import APP_NAME as ROOT_LOGGER_NAME
18
-except ImportError:
19
-    ROOT_LOGGER_NAME = 'root'
20
-logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
21
-
22
-
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)
17
+logger = logging.getLogger(settings.ROOT_LOGGER_NAME).getChild(__name__)
30 18
 
31 19
 
32 20
 def get_next(request):
@@ -37,25 +25,9 @@ def get_next(request):
37 25
 
38 26
 
39 27
 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
28
+    access = parameter.get(parameter.MYCREOLE_ATTACHMENT_ACCESS)
29
+    method = access[access_type]
30
+    return method(request, rel_path)
59 31
 
60 32
 
61 33
 def mycreole_attachment(request, rel_path):
@@ -93,7 +65,7 @@ def mycreole_upload(request, rel_path):
93 65
             try:
94 66
                 os.makedirs(os.path.dirname(full_path), exist_ok=True)
95 67
             except PermissionError:
96
-                raise PermissionError("Ensure that we have access to MYCREOLE_ROOT=%s" % repr(settings.MYCREOLE_ROOT))
68
+                raise PermissionError("Ensure that we have access to MYCREOLE_ROOT=%s" % repr(parameter.get(parameter.MYCREOLE_ROOT)))
97 69
             else:
98 70
                 with open(full_path, 'wb') as fh:
99 71
                     fh.write(request.FILES['file'].read())

Loading…
Отказ
Запис