File: util.py

package info (click to toggle)
trac-xmlrpc 1.2.0%2Bsvn18657-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 296 kB
  • sloc: python: 3,024; javascript: 26; makefile: 3
file content (86 lines) | stat: -rw-r--r-- 2,243 bytes parent folder | download
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# -*- coding: utf-8 -*-
"""
License: BSD

(c) 2005-2008 ::: Alec Thomas (alec@swapoff.org)
(c) 2009-2013 ::: www.CodeResort.com - BV Network AS (simon-code@bvnetwork.no)
"""

import functools
import inspect
import sys

from trac.util.translation import dgettext, domain_functions


# Supported Python versions:
PY24 = sys.version_info[:2] == (2, 4)
PY25 = sys.version_info[:2] == (2, 5)
PY26 = sys.version_info[:2] == (2, 6)
PY27 = sys.version_info[:2] == (2, 7)
PY3 = sys.version_info[0] > 2


if sys.version_info[0] == 2:
    unicode = unicode
    basestring = basestring
    unichr = unichr
    iteritems = lambda d: d.iteritems()
    from itertools import izip
    import xmlrpclib
else:
    unicode = str
    basestring = str
    unichr = chr
    iteritems = lambda d: d.items()
    izip = zip
    from xmlrpc import client as xmlrpclib


i18n_domain = 'tracrpc'
add_domain, ngettext, tag_ = domain_functions(
    i18n_domain, ('add_domain', 'ngettext', 'tag_'))

# XXX Use directly `dgettext` instead of `gettext` returned from
# `domain_functions` because translation doesn't work caused by multiple
# white-spaces in msgid are replaced by single space.
_ = gettext = functools.partial(dgettext, i18n_domain)


try:
    from trac.util.translation import cleandoc_
except ImportError:
    cleandoc_ = lambda message: inspect.cleandoc(message).strip()


getargspec = inspect.getfullargspec \
             if hasattr(inspect, 'getfullargspec') else \
             inspect.getargspec


try:
    from trac.web.chrome import web_context
except ImportError:
    from trac.mimeview.api import Context
    web_context = Context.from_request
    del Context


def accepts_mimetype(req, mimetype):
    if isinstance(mimetype, basestring):
        mimetype = (mimetype,)
    accept = req.get_header('Accept')
    if accept is None:
        # Don't make judgements if no MIME type expected and method is GET
        return req.method == 'GET'
    else:
        accept = accept.split(',')
        return any(x.strip().startswith(y) for x in accept for y in mimetype)


def to_b(value):
    if isinstance(value, unicode):
        return value.encode('utf-8')
    if isinstance(value, bytes):
        return value
    raise TypeError(str(type(value)))