File: settings.py

package info (click to toggle)
flask-api 0.6.4%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 316 kB
  • ctags: 329
  • sloc: python: 1,284; sh: 21; makefile: 10
file content (57 lines) | stat: -rw-r--r-- 1,771 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from flask._compat import string_types
import importlib


def perform_imports(val, setting_name):
    """
    If the given setting is a string import notation,
    then perform the necessary import or imports.
    """
    if isinstance(val, string_types):
        return import_from_string(val, setting_name)
    elif isinstance(val, (list, tuple)):
        return [perform_imports(item, setting_name) for item in val]
    return val


def import_from_string(val, setting_name):
    """
    Attempt to import a class from a string representation.
    """
    try:
        # Nod to tastypie's use of importlib.
        parts = val.split('.')
        module_path, class_name = '.'.join(parts[:-1]), parts[-1]
        module = importlib.import_module(module_path)
        return getattr(module, class_name)
    except ImportError as exc:
        format = "Could not import '%s' for API setting '%s'. %s."
        msg = format % (val, setting_name, exc)
        raise ImportError(msg)


class APISettings(object):
    def __init__(self, user_config=None):
        self.user_config = user_config or {}

    @property
    def DEFAULT_PARSERS(self):
        default = [
            'flask_api.parsers.JSONParser',
            'flask_api.parsers.URLEncodedParser',
            'flask_api.parsers.MultiPartParser'
        ]
        val = self.user_config.get('DEFAULT_PARSERS', default)
        return perform_imports(val, 'DEFAULT_PARSERS')

    @property
    def DEFAULT_RENDERERS(self):
        default = [
            'flask_api.renderers.JSONRenderer',
            'flask_api.renderers.BrowsableAPIRenderer'
        ]
        val = self.user_config.get('DEFAULT_RENDERERS', default)
        return perform_imports(val, 'DEFAULT_RENDERERS')


default_settings = APISettings()