File: compat.py

package info (click to toggle)
python-django-extensions 4.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,812 kB
  • sloc: python: 18,601; javascript: 7,354; makefile: 108; xml: 17
file content (68 lines) | stat: -rw-r--r-- 1,929 bytes parent folder | download | duplicates (2)
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
# -*- coding: utf-8 -*-
from io import BytesIO

import csv
import codecs
import importlib

from django.conf import settings


#
# Django compatibility
#
def load_tag_library(libname):
    """
    Load a templatetag library on multiple Django versions.

    Returns None if the library isn't loaded.
    """
    from django.template.backends.django import get_installed_libraries
    from django.template.library import InvalidTemplateLibrary

    try:
        lib = get_installed_libraries()[libname]
        lib = importlib.import_module(lib).register
        return lib
    except (InvalidTemplateLibrary, KeyError):
        return None


def get_template_setting(template_key, default=None):
    """Read template settings"""
    templates_var = getattr(settings, "TEMPLATES", None)
    if templates_var:
        for tdict in templates_var:
            if template_key in tdict:
                return tdict[template_key]
    return default


class UnicodeWriter:
    """
    CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    We are using this custom UnicodeWriter for python versions 2.x
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        self.queue = BytesIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)