micawber 0.6.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- examples/__init__.py +0 -0
- examples/django_ex/__init__.py +0 -0
- examples/django_ex/manage.py +14 -0
- examples/django_ex/settings.py +86 -0
- examples/django_ex/urls.py +5 -0
- examples/django_ex/views.py +14 -0
- micawber/__init__.py +17 -0
- micawber/cache.py +61 -0
- micawber/compat.py +263 -0
- micawber/contrib/__init__.py +0 -0
- micawber/contrib/mcdjango/__init__.py +92 -0
- micawber/contrib/mcdjango/mcdjango_tests/__init__.py +0 -0
- micawber/contrib/mcdjango/mcdjango_tests/models.py +0 -0
- micawber/contrib/mcdjango/mcdjango_tests/tests.py +119 -0
- micawber/contrib/mcdjango/models.py +0 -0
- micawber/contrib/mcdjango/providers.py +15 -0
- micawber/contrib/mcdjango/templates/micawber/link.html +1 -0
- micawber/contrib/mcdjango/templates/micawber/photo.html +1 -0
- micawber/contrib/mcdjango/templates/micawber/rich.html +1 -0
- micawber/contrib/mcdjango/templates/micawber/video.html +1 -0
- micawber/contrib/mcdjango/templatetags/__init__.py +0 -0
- micawber/contrib/mcdjango/templatetags/micawber_tags.py +1 -0
- micawber/contrib/mcflask.py +30 -0
- micawber/contrib/providers.py +62 -0
- micawber/exceptions.py +8 -0
- micawber/parsers.py +202 -0
- micawber/providers.py +320 -0
- micawber/test_utils.py +91 -0
- micawber/tests.py +355 -0
- micawber-0.6.0.dist-info/METADATA +74 -0
- micawber-0.6.0.dist-info/RECORD +34 -0
- micawber-0.6.0.dist-info/WHEEL +5 -0
- micawber-0.6.0.dist-info/licenses/LICENSE +19 -0
- micawber-0.6.0.dist-info/top_level.txt +2 -0
examples/__init__.py
ADDED
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
from django.core.management import execute_manager
|
|
3
|
+
import imp
|
|
4
|
+
try:
|
|
5
|
+
imp.find_module('settings') # Assumed to be in the same directory.
|
|
6
|
+
except ImportError:
|
|
7
|
+
import sys
|
|
8
|
+
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
|
|
9
|
+
sys.exit(1)
|
|
10
|
+
|
|
11
|
+
import settings
|
|
12
|
+
|
|
13
|
+
if __name__ == "__main__":
|
|
14
|
+
execute_manager(settings)
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
#### MICAWBER SETTINGS
|
|
4
|
+
|
|
5
|
+
# add a template filter called "oembed_no_urlize" that will not automatically
|
|
6
|
+
# convert URLs to clickable links in the event a provider is not found for
|
|
7
|
+
# the given url
|
|
8
|
+
MICAWBER_TEMPLATE_EXTENSIONS = [
|
|
9
|
+
('oembed_no_urlize', {'urlize_all': False}),
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
# by default, micawber will use the "bootstrap_basic" providers, but should you
|
|
13
|
+
# wish to use embedly you can try out the second example. You can also provide
|
|
14
|
+
# your own ProviderRegistry with a path to a module and either a callable or
|
|
15
|
+
# ProviderRegistry instance
|
|
16
|
+
MICAWBER_PROVIDERS = 'micawber.contrib.mcdjango.providers.bootstrap_basic'
|
|
17
|
+
#MICAWBER_PROVIDERS = 'micawber.contrib.mcdjango.providers.bootstrap_embedly'
|
|
18
|
+
|
|
19
|
+
# if you are using embed.ly you can specify an API key that will be used with
|
|
20
|
+
# the bootstrap_embedly provider setting
|
|
21
|
+
# MICAWBER_EMBEDLY_KEY = 'foofoo'
|
|
22
|
+
|
|
23
|
+
# since template filters are limited to a single optional parameter, you can
|
|
24
|
+
# specify defaults, such as a maxwidth you prefer to use or an api key
|
|
25
|
+
#MICAWBER_DEFAULT_SETTINGS = {
|
|
26
|
+
# 'key': 'your-embedly-api-key',
|
|
27
|
+
# 'maxwidth': 600,
|
|
28
|
+
# 'maxheight': 600,
|
|
29
|
+
#}
|
|
30
|
+
|
|
31
|
+
#### END MICAWBER SETTINGS
|
|
32
|
+
|
|
33
|
+
CURRENT_DIR = os.path.dirname(__file__)
|
|
34
|
+
|
|
35
|
+
DEBUG = True
|
|
36
|
+
TEMPLATE_DEBUG = DEBUG
|
|
37
|
+
|
|
38
|
+
DATABASES = {
|
|
39
|
+
'default': {
|
|
40
|
+
'ENGINE': 'django.db.backends.sqlite3',
|
|
41
|
+
'NAME': 'django_ex.db',
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
SITE_ID = 1
|
|
46
|
+
|
|
47
|
+
SECRET_KEY = 'fapfapfap'
|
|
48
|
+
|
|
49
|
+
STATIC_URL = '/static/'
|
|
50
|
+
STATICFILES_DIRS = (
|
|
51
|
+
os.path.join(CURRENT_DIR, 'static'),
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
STATICFILES_FINDERS = (
|
|
55
|
+
'django.contrib.staticfiles.finders.FileSystemFinder',
|
|
56
|
+
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
TEMPLATE_LOADERS = (
|
|
61
|
+
'django.template.loaders.filesystem.Loader',
|
|
62
|
+
'django.template.loaders.app_directories.Loader',
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
MIDDLEWARE_CLASSES = (
|
|
66
|
+
'django.middleware.common.CommonMiddleware',
|
|
67
|
+
'django.contrib.sessions.middleware.SessionMiddleware',
|
|
68
|
+
'django.middleware.csrf.CsrfViewMiddleware',
|
|
69
|
+
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
|
70
|
+
'django.contrib.messages.middleware.MessageMiddleware',
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
ROOT_URLCONF = 'django_ex.urls'
|
|
74
|
+
|
|
75
|
+
TEMPLATE_DIRS = (
|
|
76
|
+
os.path.join(CURRENT_DIR, 'templates'),
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
INSTALLED_APPS = (
|
|
80
|
+
'django.contrib.auth',
|
|
81
|
+
'django.contrib.contenttypes',
|
|
82
|
+
'django.contrib.sessions',
|
|
83
|
+
'django.contrib.sites',
|
|
84
|
+
'django.contrib.staticfiles',
|
|
85
|
+
'micawber.contrib.mcdjango',
|
|
86
|
+
)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from django.shortcuts import render_to_response
|
|
2
|
+
|
|
3
|
+
def example_view(request):
|
|
4
|
+
text = request.GET.get('text', 'http://www.youtube.com/watch?v=nda_OSWeyn8')
|
|
5
|
+
html = request.GET.get('html', """
|
|
6
|
+
<p>This is a test</p>
|
|
7
|
+
<p>http://www.youtube.com/watch?v=nda_OSWeyn8</p>
|
|
8
|
+
<p>This will get rendered as a link: http://www.youtube.com/watch?v=nda_OSWeyn8</p>
|
|
9
|
+
<p>This will not be modified: <a href="http://www.google.com/">http://www.youtube.com/watch?v=nda_OSWeyn8</a></p>
|
|
10
|
+
""")
|
|
11
|
+
return render_to_response('example.html', dict(
|
|
12
|
+
text=text,
|
|
13
|
+
html=html,
|
|
14
|
+
))
|
micawber/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
__version__ = '0.6.0'
|
|
2
|
+
|
|
3
|
+
from micawber.cache import Cache
|
|
4
|
+
from micawber.cache import PickleCache
|
|
5
|
+
from micawber.exceptions import ProviderException
|
|
6
|
+
from micawber.exceptions import InvalidResponseException
|
|
7
|
+
from micawber.parsers import extract
|
|
8
|
+
from micawber.parsers import extract_html
|
|
9
|
+
from micawber.parsers import parse_text
|
|
10
|
+
from micawber.parsers import parse_text_full
|
|
11
|
+
from micawber.parsers import parse_html
|
|
12
|
+
from micawber.providers import Provider
|
|
13
|
+
from micawber.providers import ProviderRegistry
|
|
14
|
+
from micawber.providers import bootstrap_basic
|
|
15
|
+
from micawber.providers import bootstrap_embedly
|
|
16
|
+
from micawber.providers import bootstrap_noembed
|
|
17
|
+
from micawber.providers import bootstrap_oembed
|
micawber/cache.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
from __future__ import with_statement
|
|
2
|
+
import os
|
|
3
|
+
import pickle
|
|
4
|
+
try:
|
|
5
|
+
from redis import Redis
|
|
6
|
+
except ImportError:
|
|
7
|
+
Redis = None
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Cache(object):
|
|
11
|
+
def __init__(self):
|
|
12
|
+
self._cache = {}
|
|
13
|
+
|
|
14
|
+
def get(self, k):
|
|
15
|
+
return self._cache.get(k)
|
|
16
|
+
|
|
17
|
+
def set(self, k, v):
|
|
18
|
+
self._cache[k] = v
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class PickleCache(Cache):
|
|
22
|
+
def __init__(self, filename='cache.db'):
|
|
23
|
+
self.filename = filename
|
|
24
|
+
self._cache = self.load()
|
|
25
|
+
|
|
26
|
+
def load(self):
|
|
27
|
+
if os.path.exists(self.filename):
|
|
28
|
+
with open(self.filename, 'rb') as fh:
|
|
29
|
+
return pickle.load(fh)
|
|
30
|
+
return {}
|
|
31
|
+
|
|
32
|
+
def save(self):
|
|
33
|
+
with open(self.filename, 'wb') as fh:
|
|
34
|
+
pickle.dump(self._cache, fh)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
if Redis:
|
|
38
|
+
class RedisCache(Cache):
|
|
39
|
+
"""
|
|
40
|
+
:param str namespace: key prefix.
|
|
41
|
+
:param int timeout: expiration timeout in seconds
|
|
42
|
+
"""
|
|
43
|
+
def __init__(self, namespace='micawber', timeout=None, **conn):
|
|
44
|
+
self.namespace = namespace
|
|
45
|
+
self.timeout = timeout
|
|
46
|
+
self.conn = Redis(**conn)
|
|
47
|
+
|
|
48
|
+
def key_fn(self, k):
|
|
49
|
+
return '%s.%s' % (self.namespace, k)
|
|
50
|
+
|
|
51
|
+
def get(self, k):
|
|
52
|
+
cached = self.conn.get(self.key_fn(k))
|
|
53
|
+
if cached:
|
|
54
|
+
return pickle.loads(cached)
|
|
55
|
+
|
|
56
|
+
def set(self, k, v):
|
|
57
|
+
ck, cv = self.key_fn(k), pickle.dumps(v)
|
|
58
|
+
if self.timeout is not None:
|
|
59
|
+
self.conn.setex(ck, cv, self.timeout)
|
|
60
|
+
else:
|
|
61
|
+
self.conn.set(ck, cv)
|
micawber/compat.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
|
|
3
|
+
PY3 = sys.version_info >= (3,)
|
|
4
|
+
|
|
5
|
+
if PY3:
|
|
6
|
+
from urllib.request import Request, urlopen, URLError, HTTPError
|
|
7
|
+
from urllib.parse import urlencode
|
|
8
|
+
text_type = str
|
|
9
|
+
string_types = str,
|
|
10
|
+
def get_charset(response):
|
|
11
|
+
return response.headers.get_param('charset')
|
|
12
|
+
else:
|
|
13
|
+
from urllib2 import Request, urlopen, URLError, HTTPError
|
|
14
|
+
from urllib import urlencode
|
|
15
|
+
text_type = unicode
|
|
16
|
+
string_types = basestring,
|
|
17
|
+
def get_charset(response):
|
|
18
|
+
return response.headers.getparam('charset')
|
|
19
|
+
|
|
20
|
+
try:
|
|
21
|
+
from collections import OrderedDict
|
|
22
|
+
except ImportError:
|
|
23
|
+
try:
|
|
24
|
+
from _abcoll import KeysView, ValuesView, ItemsView
|
|
25
|
+
except ImportError:
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
class OrderedDict(dict):
|
|
29
|
+
'Dictionary that remembers insertion order'
|
|
30
|
+
# An inherited dict maps keys to values.
|
|
31
|
+
# The inherited dict provides __getitem__, __len__, __contains__, and get.
|
|
32
|
+
# The remaining methods are order-aware.
|
|
33
|
+
# Big-O running times for all methods are the same as for regular dictionaries.
|
|
34
|
+
|
|
35
|
+
# The internal self.__map dictionary maps keys to links in a doubly linked list.
|
|
36
|
+
# The circular doubly linked list starts and ends with a sentinel element.
|
|
37
|
+
# The sentinel element never gets deleted (this simplifies the algorithm).
|
|
38
|
+
# Each link is stored as a list of length three: [PREV, NEXT, KEY].
|
|
39
|
+
|
|
40
|
+
def __init__(self, *args, **kwds):
|
|
41
|
+
'''Initialize an ordered dictionary. Signature is the same as for
|
|
42
|
+
regular dictionaries, but keyword arguments are not recommended
|
|
43
|
+
because their insertion order is arbitrary.
|
|
44
|
+
|
|
45
|
+
'''
|
|
46
|
+
if len(args) > 1:
|
|
47
|
+
raise TypeError('expected at most 1 arguments, got %d' % len(args))
|
|
48
|
+
try:
|
|
49
|
+
self.__root
|
|
50
|
+
except AttributeError:
|
|
51
|
+
self.__root = root = [] # sentinel node
|
|
52
|
+
root[:] = [root, root, None]
|
|
53
|
+
self.__map = {}
|
|
54
|
+
self.__update(*args, **kwds)
|
|
55
|
+
|
|
56
|
+
def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
|
|
57
|
+
'od.__setitem__(i, y) <==> od[i]=y'
|
|
58
|
+
# Setting a new item creates a new link which goes at the end of the linked
|
|
59
|
+
# list, and the inherited dictionary is updated with the new key/value pair.
|
|
60
|
+
if key not in self:
|
|
61
|
+
root = self.__root
|
|
62
|
+
last = root[0]
|
|
63
|
+
last[1] = root[0] = self.__map[key] = [last, root, key]
|
|
64
|
+
dict_setitem(self, key, value)
|
|
65
|
+
|
|
66
|
+
def __delitem__(self, key, dict_delitem=dict.__delitem__):
|
|
67
|
+
'od.__delitem__(y) <==> del od[y]'
|
|
68
|
+
# Deleting an existing item uses self.__map to find the link which is
|
|
69
|
+
# then removed by updating the links in the predecessor and successor nodes.
|
|
70
|
+
dict_delitem(self, key)
|
|
71
|
+
link_prev, link_next, key = self.__map.pop(key)
|
|
72
|
+
link_prev[1] = link_next
|
|
73
|
+
link_next[0] = link_prev
|
|
74
|
+
|
|
75
|
+
def __iter__(self):
|
|
76
|
+
'od.__iter__() <==> iter(od)'
|
|
77
|
+
root = self.__root
|
|
78
|
+
curr = root[1]
|
|
79
|
+
while curr is not root:
|
|
80
|
+
yield curr[2]
|
|
81
|
+
curr = curr[1]
|
|
82
|
+
|
|
83
|
+
def __reversed__(self):
|
|
84
|
+
'od.__reversed__() <==> reversed(od)'
|
|
85
|
+
root = self.__root
|
|
86
|
+
curr = root[0]
|
|
87
|
+
while curr is not root:
|
|
88
|
+
yield curr[2]
|
|
89
|
+
curr = curr[0]
|
|
90
|
+
|
|
91
|
+
def clear(self):
|
|
92
|
+
'od.clear() -> None. Remove all items from od.'
|
|
93
|
+
try:
|
|
94
|
+
for node in self.__map.itervalues():
|
|
95
|
+
del node[:]
|
|
96
|
+
root = self.__root
|
|
97
|
+
root[:] = [root, root, None]
|
|
98
|
+
self.__map.clear()
|
|
99
|
+
except AttributeError:
|
|
100
|
+
pass
|
|
101
|
+
dict.clear(self)
|
|
102
|
+
|
|
103
|
+
def popitem(self, last=True):
|
|
104
|
+
'''od.popitem() -> (k, v), return and remove a (key, value) pair.
|
|
105
|
+
Pairs are returned in LIFO order if last is true or FIFO order if false.
|
|
106
|
+
|
|
107
|
+
'''
|
|
108
|
+
if not self:
|
|
109
|
+
raise KeyError('dictionary is empty')
|
|
110
|
+
root = self.__root
|
|
111
|
+
if last:
|
|
112
|
+
link = root[0]
|
|
113
|
+
link_prev = link[0]
|
|
114
|
+
link_prev[1] = root
|
|
115
|
+
root[0] = link_prev
|
|
116
|
+
else:
|
|
117
|
+
link = root[1]
|
|
118
|
+
link_next = link[1]
|
|
119
|
+
root[1] = link_next
|
|
120
|
+
link_next[0] = root
|
|
121
|
+
key = link[2]
|
|
122
|
+
del self.__map[key]
|
|
123
|
+
value = dict.pop(self, key)
|
|
124
|
+
return key, value
|
|
125
|
+
|
|
126
|
+
# -- the following methods do not depend on the internal structure --
|
|
127
|
+
|
|
128
|
+
def keys(self):
|
|
129
|
+
'od.keys() -> list of keys in od'
|
|
130
|
+
return list(self)
|
|
131
|
+
|
|
132
|
+
def values(self):
|
|
133
|
+
'od.values() -> list of values in od'
|
|
134
|
+
return [self[key] for key in self]
|
|
135
|
+
|
|
136
|
+
def items(self):
|
|
137
|
+
'od.items() -> list of (key, value) pairs in od'
|
|
138
|
+
return [(key, self[key]) for key in self]
|
|
139
|
+
|
|
140
|
+
def iterkeys(self):
|
|
141
|
+
'od.iterkeys() -> an iterator over the keys in od'
|
|
142
|
+
return iter(self)
|
|
143
|
+
|
|
144
|
+
def itervalues(self):
|
|
145
|
+
'od.itervalues -> an iterator over the values in od'
|
|
146
|
+
for k in self:
|
|
147
|
+
yield self[k]
|
|
148
|
+
|
|
149
|
+
def iteritems(self):
|
|
150
|
+
'od.iteritems -> an iterator over the (key, value) items in od'
|
|
151
|
+
for k in self:
|
|
152
|
+
yield (k, self[k])
|
|
153
|
+
|
|
154
|
+
def update(*args, **kwds):
|
|
155
|
+
'''od.update(E, **F) -> None. Update od from dict/iterable E and F.
|
|
156
|
+
|
|
157
|
+
If E is a dict instance, does: for k in E: od[k] = E[k]
|
|
158
|
+
If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
|
|
159
|
+
Or if E is an iterable of items, does: for k, v in E: od[k] = v
|
|
160
|
+
In either case, this is followed by: for k, v in F.items(): od[k] = v
|
|
161
|
+
|
|
162
|
+
'''
|
|
163
|
+
if len(args) > 2:
|
|
164
|
+
raise TypeError('update() takes at most 2 positional '
|
|
165
|
+
'arguments (%d given)' % (len(args),))
|
|
166
|
+
elif not args:
|
|
167
|
+
raise TypeError('update() takes at least 1 argument (0 given)')
|
|
168
|
+
self = args[0]
|
|
169
|
+
# Make progressively weaker assumptions about "other"
|
|
170
|
+
other = ()
|
|
171
|
+
if len(args) == 2:
|
|
172
|
+
other = args[1]
|
|
173
|
+
if isinstance(other, dict):
|
|
174
|
+
for key in other:
|
|
175
|
+
self[key] = other[key]
|
|
176
|
+
elif hasattr(other, 'keys'):
|
|
177
|
+
for key in other.keys():
|
|
178
|
+
self[key] = other[key]
|
|
179
|
+
else:
|
|
180
|
+
for key, value in other:
|
|
181
|
+
self[key] = value
|
|
182
|
+
for key, value in kwds.items():
|
|
183
|
+
self[key] = value
|
|
184
|
+
|
|
185
|
+
__update = update # let subclasses override update without breaking __init__
|
|
186
|
+
|
|
187
|
+
__marker = object()
|
|
188
|
+
|
|
189
|
+
def pop(self, key, default=__marker):
|
|
190
|
+
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
|
191
|
+
If key is not found, d is returned if given, otherwise KeyError is raised.
|
|
192
|
+
|
|
193
|
+
'''
|
|
194
|
+
if key in self:
|
|
195
|
+
result = self[key]
|
|
196
|
+
del self[key]
|
|
197
|
+
return result
|
|
198
|
+
if default is self.__marker:
|
|
199
|
+
raise KeyError(key)
|
|
200
|
+
return default
|
|
201
|
+
|
|
202
|
+
def setdefault(self, key, default=None):
|
|
203
|
+
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
|
|
204
|
+
if key in self:
|
|
205
|
+
return self[key]
|
|
206
|
+
self[key] = default
|
|
207
|
+
return default
|
|
208
|
+
|
|
209
|
+
def __repr__(self):
|
|
210
|
+
if not self:
|
|
211
|
+
return '%s()' % (self.__class__.__name__,)
|
|
212
|
+
return '%s(%r)' % (self.__class__.__name__, self.items())
|
|
213
|
+
|
|
214
|
+
def __reduce__(self):
|
|
215
|
+
'Return state information for pickling'
|
|
216
|
+
items = [[k, self[k]] for k in self]
|
|
217
|
+
inst_dict = vars(self).copy()
|
|
218
|
+
for k in vars(OrderedDict()):
|
|
219
|
+
inst_dict.pop(k, None)
|
|
220
|
+
if inst_dict:
|
|
221
|
+
return (self.__class__, (items,), inst_dict)
|
|
222
|
+
return self.__class__, (items,)
|
|
223
|
+
|
|
224
|
+
def copy(self):
|
|
225
|
+
'od.copy() -> a shallow copy of od'
|
|
226
|
+
return self.__class__(self)
|
|
227
|
+
|
|
228
|
+
@classmethod
|
|
229
|
+
def fromkeys(cls, iterable, value=None):
|
|
230
|
+
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
|
|
231
|
+
and values equal to v (which defaults to None).
|
|
232
|
+
|
|
233
|
+
'''
|
|
234
|
+
d = cls()
|
|
235
|
+
for key in iterable:
|
|
236
|
+
d[key] = value
|
|
237
|
+
return d
|
|
238
|
+
|
|
239
|
+
def __eq__(self, other):
|
|
240
|
+
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
|
|
241
|
+
while comparison to a regular mapping is order-insensitive.
|
|
242
|
+
|
|
243
|
+
'''
|
|
244
|
+
if isinstance(other, OrderedDict):
|
|
245
|
+
return len(self)==len(other) and self.items() == other.items()
|
|
246
|
+
return dict.__eq__(self, other)
|
|
247
|
+
|
|
248
|
+
def __ne__(self, other):
|
|
249
|
+
return not self == other
|
|
250
|
+
|
|
251
|
+
# -- the following methods are only used in Python 2.7 --
|
|
252
|
+
|
|
253
|
+
def viewkeys(self):
|
|
254
|
+
"od.viewkeys() -> a set-like object providing a view on od's keys"
|
|
255
|
+
return KeysView(self)
|
|
256
|
+
|
|
257
|
+
def viewvalues(self):
|
|
258
|
+
"od.viewvalues() -> an object providing a view on od's values"
|
|
259
|
+
return ValuesView(self)
|
|
260
|
+
|
|
261
|
+
def viewitems(self):
|
|
262
|
+
"od.viewitems() -> a set-like object providing a view on od's items"
|
|
263
|
+
return ItemsView(self)
|
|
File without changes
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
from collections.abc import Callable
|
|
2
|
+
from importlib import import_module
|
|
3
|
+
|
|
4
|
+
from django import template
|
|
5
|
+
from django.conf import settings
|
|
6
|
+
from django.template.loader import render_to_string
|
|
7
|
+
from django.utils.safestring import mark_safe
|
|
8
|
+
|
|
9
|
+
from micawber.compat import string_types
|
|
10
|
+
from micawber.parsers import full_handler, inline_handler, parse_text, \
|
|
11
|
+
parse_html, extract, extract_html
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _load_from_module(path):
|
|
15
|
+
package, attr = path.rsplit('.', 1)
|
|
16
|
+
module = import_module(package)
|
|
17
|
+
return getattr(module, attr)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
PROVIDERS = getattr(settings, 'MICAWBER_PROVIDERS', 'micawber.contrib.mcdjango.providers.bootstrap_basic')
|
|
21
|
+
|
|
22
|
+
providers = _load_from_module(PROVIDERS)
|
|
23
|
+
if isinstance(providers, Callable):
|
|
24
|
+
providers = providers()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
register = template.Library()
|
|
28
|
+
|
|
29
|
+
def django_template_handler(url, response_data, **params):
|
|
30
|
+
names = (
|
|
31
|
+
response_data.get('provider_name'),
|
|
32
|
+
response_data['type'],
|
|
33
|
+
)
|
|
34
|
+
template_names = ['micawber/%s.html' % name for name in names if name]
|
|
35
|
+
return mark_safe(
|
|
36
|
+
render_to_string(
|
|
37
|
+
template_names,
|
|
38
|
+
{'params': params,
|
|
39
|
+
'response': response_data,
|
|
40
|
+
'url': url,
|
|
41
|
+
}).strip())
|
|
42
|
+
|
|
43
|
+
def fix_width_height(width_height, params):
|
|
44
|
+
if width_height:
|
|
45
|
+
if 'x' in width_height:
|
|
46
|
+
params['maxwidth'], params['maxheight'] = [int(n) for n in width_height.split('x')]
|
|
47
|
+
else:
|
|
48
|
+
params['maxwidth'] = int(width_height)
|
|
49
|
+
params.pop('maxheight', None)
|
|
50
|
+
return params
|
|
51
|
+
|
|
52
|
+
def extension(filter_name, providers=providers, urlize_all=True, html=False, handler=django_template_handler,
|
|
53
|
+
block_handler=inline_handler, text_fn=parse_text, html_fn=parse_html, **kwargs):
|
|
54
|
+
if html:
|
|
55
|
+
fn = html_fn
|
|
56
|
+
else:
|
|
57
|
+
fn = text_fn
|
|
58
|
+
def _extension(s, width_height=None):
|
|
59
|
+
params = getattr(settings, 'MICAWBER_DEFAULT_SETTINGS', {})
|
|
60
|
+
params.update(kwargs)
|
|
61
|
+
params = fix_width_height(width_height, params)
|
|
62
|
+
return mark_safe(fn(s, providers, urlize_all, handler, block_handler, **params))
|
|
63
|
+
register.filter(filter_name, _extension)
|
|
64
|
+
return _extension
|
|
65
|
+
|
|
66
|
+
oembed = extension('oembed')
|
|
67
|
+
oembed_html = extension('oembed_html', html=True)
|
|
68
|
+
|
|
69
|
+
def _extract_oembed(text, width_height=None, html=False):
|
|
70
|
+
if html:
|
|
71
|
+
fn = extract_html
|
|
72
|
+
else:
|
|
73
|
+
fn = extract
|
|
74
|
+
params = getattr(settings, 'MICAWBER_DEFAULT_SETTINGS', {})
|
|
75
|
+
params = fix_width_height(width_height, params)
|
|
76
|
+
url_list, url_data = fn(text, providers, **params)
|
|
77
|
+
return [(u, url_data[u]) for u in url_list if u in url_data]
|
|
78
|
+
|
|
79
|
+
@register.filter
|
|
80
|
+
def extract_oembed(text, width_height=None):
|
|
81
|
+
return _extract_oembed(text, width_height)
|
|
82
|
+
|
|
83
|
+
@register.filter
|
|
84
|
+
def extract_oembed_html(text, width_height=None):
|
|
85
|
+
return _extract_oembed(text, width_height, True)
|
|
86
|
+
|
|
87
|
+
user_extensions = getattr(settings, 'MICAWBER_TEMPLATE_EXTENSIONS', [])
|
|
88
|
+
if isinstance(user_extensions, string_types):
|
|
89
|
+
user_extensions = _load_from_module(user_extensions)
|
|
90
|
+
|
|
91
|
+
for filter_name, filter_params in user_extensions:
|
|
92
|
+
extension(filter_name, **filter_params)
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
from django.template import Context
|
|
2
|
+
from django.template import Template
|
|
3
|
+
from django.test import TestCase
|
|
4
|
+
|
|
5
|
+
from micawber.parsers import parse_text
|
|
6
|
+
from micawber.test_utils import BaseTestCase
|
|
7
|
+
from micawber.test_utils import test_cache
|
|
8
|
+
from micawber.test_utils import test_pr
|
|
9
|
+
from micawber.test_utils import test_pr_cache
|
|
10
|
+
from micawber.test_utils import TestProvider
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class MicawberDjangoTestCase(TestCase, BaseTestCase):
|
|
14
|
+
def render(self, s, **params):
|
|
15
|
+
s = '{%% load micawber_tags %%}%s' % s
|
|
16
|
+
return Template(s).render(Context(params)).strip()
|
|
17
|
+
|
|
18
|
+
def test_oembed_alt(self):
|
|
19
|
+
from micawber.contrib.mcdjango import extension
|
|
20
|
+
|
|
21
|
+
def custom_handler(url, response_data):
|
|
22
|
+
return url
|
|
23
|
+
|
|
24
|
+
oembed_alt = extension(
|
|
25
|
+
'oembed_alt',
|
|
26
|
+
urlize_all=False,
|
|
27
|
+
block_handler=custom_handler)
|
|
28
|
+
|
|
29
|
+
text = '\n'.join((
|
|
30
|
+
'this is the first line',
|
|
31
|
+
'http://photo-test2',
|
|
32
|
+
'this is the third line http://photo-test2',
|
|
33
|
+
'http://photo-test2 this is the fourth line'))
|
|
34
|
+
rendered = self.render('{{ text|oembed_alt }}', text=text)
|
|
35
|
+
self.assertEqual(rendered.splitlines(), [
|
|
36
|
+
'this is the first line',
|
|
37
|
+
self.full_pairs['http://photo-test2'],
|
|
38
|
+
'this is the third line http://photo-test2',
|
|
39
|
+
'http://photo-test2 this is the fourth line',
|
|
40
|
+
])
|
|
41
|
+
|
|
42
|
+
def test_fix_wh(self):
|
|
43
|
+
from micawber.contrib.mcdjango import fix_width_height
|
|
44
|
+
self.assertEqual(fix_width_height('300x400', {}), {'maxwidth': 300, 'maxheight': 400})
|
|
45
|
+
self.assertEqual(fix_width_height('300', {}), {'maxwidth': 300})
|
|
46
|
+
|
|
47
|
+
def test_provider_loading(self):
|
|
48
|
+
from micawber.contrib.mcdjango import providers
|
|
49
|
+
self.assertEqual(providers, test_pr)
|
|
50
|
+
|
|
51
|
+
def test_oembed_filter_multiline_plain(self):
|
|
52
|
+
for url, expected in self.full_pairs.items():
|
|
53
|
+
expected_inline = self.inline_pairs[url]
|
|
54
|
+
frame = 'this is inline: %s\n%s\nand yet another %s'
|
|
55
|
+
|
|
56
|
+
test_str = frame % (url, url, url)
|
|
57
|
+
|
|
58
|
+
parsed = self.render('{{ test_str|oembed }}', test_str=test_str)
|
|
59
|
+
self.assertEqual(parsed, frame % (expected_inline, expected, expected_inline))
|
|
60
|
+
|
|
61
|
+
def test_oembed_filter_multiline_html(self):
|
|
62
|
+
for url, expected in self.full_pairs.items():
|
|
63
|
+
expected_inline = self.inline_pairs[url]
|
|
64
|
+
frame = '<p>%s</p>\n<p>this is inline: %s</p>\n<p>\n%s\n</p><p>last test\n%s\n</p>'
|
|
65
|
+
|
|
66
|
+
test_str = frame % (url, url, url, url)
|
|
67
|
+
|
|
68
|
+
parsed = self.render('{{ test_str|oembed_html }}', test_str=test_str)
|
|
69
|
+
self.assertHTMLEqual(parsed, frame % (expected, expected_inline, expected, expected_inline))
|
|
70
|
+
|
|
71
|
+
for url, expected in self.full_pairs.items():
|
|
72
|
+
expected_inline = self.inline_pairs[url]
|
|
73
|
+
frame = '<p><a href="#foo">%s</a></p>\n<p>this is inline: %s</p>\n<p>last test\n%s\n</p>'
|
|
74
|
+
|
|
75
|
+
test_str = frame % (url, url, url)
|
|
76
|
+
|
|
77
|
+
parsed = self.render('{{ test_str|oembed_html }}', test_str=test_str)
|
|
78
|
+
self.assertHTMLEqual(parsed, frame % (url, expected_inline, expected_inline))
|
|
79
|
+
|
|
80
|
+
def test_urlize(self):
|
|
81
|
+
u1 = 'http://fappio.com/'
|
|
82
|
+
u2 = 'http://google.com/fap/'
|
|
83
|
+
u1h = '<a href="%s">%s</a>' % (u1, u1)
|
|
84
|
+
u2h = '<a href="%s">%s</a>' % (u2, u2)
|
|
85
|
+
for url, expected in self.full_pairs.items():
|
|
86
|
+
expected_inline = self.inline_pairs[url]
|
|
87
|
+
frame = 'test %s\n%s\n%s\nand another %s'
|
|
88
|
+
|
|
89
|
+
test_str = frame % (u1, u2, url, url)
|
|
90
|
+
|
|
91
|
+
parsed = self.render('{{ test_str|oembed }}', test_str=test_str)
|
|
92
|
+
self.assertEqual(parsed, frame % (u1h, u2h, expected, expected_inline))
|
|
93
|
+
|
|
94
|
+
def test_oembed_filter_extension(self):
|
|
95
|
+
for url, expected in self.full_pairs.items():
|
|
96
|
+
expected_inline = self.inline_pairs[url]
|
|
97
|
+
frame = 'test http://fappio.com\nhttp://google.com\n%s\nand another %s'
|
|
98
|
+
|
|
99
|
+
test_str = frame % (url, url)
|
|
100
|
+
|
|
101
|
+
parsed = self.render('{{ test_str|oembed_no_urlize }}', test_str=test_str)
|
|
102
|
+
self.assertEqual(parsed, frame % (expected, expected_inline))
|
|
103
|
+
|
|
104
|
+
def test_extract_filter(self):
|
|
105
|
+
blank = 'http://fapp.io/foo/'
|
|
106
|
+
frame = 'test %s\n%s\n%s\n%s at last'
|
|
107
|
+
frame_html = '<p>test %s</p><p><a href="foo">%s</a> %s</p><p>%s</p>'
|
|
108
|
+
|
|
109
|
+
t = """{% for url, data in test_str|extract_oembed %}{{ url }}\n{% endfor %}"""
|
|
110
|
+
t2 = """{% for url, data in test_str|extract_oembed_html %}{{ url }}\n{% endfor %}"""
|
|
111
|
+
|
|
112
|
+
for url, expected in self.data_pairs.items():
|
|
113
|
+
test_str = frame % (url, blank, url, blank)
|
|
114
|
+
rendered = self.render(t, test_str=test_str)
|
|
115
|
+
self.assertEqual(rendered, url)
|
|
116
|
+
|
|
117
|
+
test_str = frame_html % (url, blank, url, blank)
|
|
118
|
+
rendered = self.render(t, test_str=test_str)
|
|
119
|
+
self.assertEqual(rendered, url)
|