Debian Codegraph @

django_downloadview/utils.py

raw
1 """Utility functions that may be implemented in external packages."""
2
3 import re
4
5 charset_pattern = re.compile(r"charset=(?P<charset>.+)$", re.I | re.U)
6
7
8 def content_type_to_charset(content_type):
9 """Return charset part of content-type header.
10
11 >>> from django_downloadview.utils import content_type_to_charset
12 >>> content_type_to_charset('text/html; charset=utf-8')
13 'utf-8'
14
15 """
16 match = re.search(charset_pattern, content_type)
17 if match:
18 return match.group("charset")
19
20
21 def url_basename(url, content_type):
22 """Return best-guess basename from URL and content-type.
23
24 >>> from django_downloadview.utils import url_basename
25
26 If URL contains extension, it is kept as-is.
27
28 >>> print(url_basename(u'/path/to/somefile.rst', 'text/plain'))
29 somefile.rst
30
31 """
32 return url.split("/")[-1]
33
34
35 def import_member(import_string):
36 """Import one member of Python module by path.
37
38 >>> import os.path
39 >>> imported = import_member('os.path.supports_unicode_filenames')
40 >>> os.path.supports_unicode_filenames is imported
41 True
42
43 """
44 module_name, factory_name = str(import_string).rsplit(".", 1)
45 module = __import__(module_name, globals(), locals(), [factory_name], 0)
46 return getattr(module, factory_name)