Coverage for tw2.core.resources : 95%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# TBD is there a better place to put this?
""" Deprecated compatibility shim with old TW2 stuff. Use js_symbol. """
raise ValueError("JSSymbol must receive up to only one arg.")
raise ValueError("JSSymbol must receive only one src arg.")
# Backwards compatibility for accessing the source.
""" Just a list of resources.
Use it as follows:
>>> jquery_ui = ResourceBundle(resources=[jquery_js, jquery_css]) >>> jquery_ui.inject()
"""
def inject(cls):
'Location on the page where the resource should be placed.' \ 'This can be one of: head, headbottom, bodytop or bodybottom. '\ 'None means the resource will not be injected, which is still '\ 'useful, e.g. static images.', default=None)
''' A link to a file. ''' 'Direct web link to file. If this is not specified, it is ' + 'automatically generated, based on :attr:`modname` and ' + ':attr:`filename`.', ) 'Name of Python module that contains the file.', default=None, ) 'Path to file, relative to module base.', default=None, ) "Don't inject this link. (Default: False)", default=False, ) "Make the whole directory available. (Default: False)", default=False, )
def guess_modname(cls): """ Try to guess my modname.
If I wasn't supplied any modname, take a guess by stepping back up the frame stack until I find something not in tw2.core """
except Exception: return None
def post_define(cls):
type(cls.filename) != property:
cls.modname or '__anon__', cls.filename, cls.whole_dir )
# TBD shouldn't we test for this in __new__ ? "Either 'link' or 'filename' must be specified" ) self.modname or '__anon__', self.filename )
hasattr(self, 'link') and \ self.link or \ ((self.modname or '') + self.filename) )
and self.modname == other.modname and self.filename == other.filename)
return "%s('%s')" % ( self.__class__.__name__, getattr(self, 'link', '%s/%s' % (self.modname, self.filename)) )
''' A whole directory as a resource.
Unlike :class:`JSLink` and :class:`CSSLink`, this resource doesn't inject anything on the page.. but it does register all resources under the marked directory to be served by the middleware.
This is useful if you have a css file that pulls in a number of other static resources like icons and images. '''
self.modname, self.filename, )
''' A JavaScript source file. '''
''' A CSS style sheet. '''
""" Inline JavaScript source code. """
raise ValueError("%r must be provided a 'src' attr" % self)
""" Inline Cascading Style-Sheet code. """
return "%s('%s')" % (self.__class__.__name__, self.src)
raise ValueError("%r must be provided a 'src' attr" % self)
""" Internal use inline JavaScript function call.
Please use tw2.core.js_function(...) externally. """
self.prepare()
else: else:
and getattr(self, 'args', None) == getattr(other, 'args', None) )
"""WSGI Middleware to serve static resources
This handles URLs like this: /resources/tw2.forms/static/forms.css
Where: resources is the prefix tw2.forms is a python package name static is a directory inside the package forms.css is the file to retrieve
For this to work, the file must have been registered in advance, using :meth:`register`. There is a ResourcesApp instance for each TwMiddleware instance. """
""" Register a file for static serving.
After this method has been called, for say ('tw2.forms', 'static/forms.css'), the URL /resources/tw2.forms/static/forms.css will then serve that file from within the tw2.forms package. This works correctly for zipped eggs.
*Security Consideration* - This file will be readable by users of the application, so make sure it contains no confidential data. For DirLink resources, the whole directory, and subdirectories will be readable.
`modname` The python module that contains the file to publish. You can also pass a pkg_resources.Requirement instance to point to the root of an egg distribution.
`filename` The path, relative to the base of the module, of the file to be published. If *modname* is None, it's an absolute path. """
else:
""" Return a resource's web path. """
modname = os.path.basename(pr.working_set.find(modname).location)
else: else: stream = open(filename) else: resp.content_type_params['charset'] = enc
""" ToscaWidgets can inject resources that have been registered for injection in the current request.
Usually widgets register them when they're displayed and they have instances of :class:`tw2.core.resources.Resource` declared at their :attr:`tw2.core.Widget.javascript` or :attr:`tw2.core.Widget.css` attributes.
Resources can also be registered manually from a controller or template by calling their :meth:`tw2.core.resources.Resource.inject` method.
When a page including widgets is rendered, Resources that are registered for injection are collected in a request-local storage area (this means any thing stored here is only visible to one single thread of execution and that its contents are freed when the request is finished) where they can be rendered and injected in the resulting html.
ToscaWidgets' middleware can take care of injecting them automatically (default) but they can also be injected explicitly, example::
>>> from tw2.core.resources import JSLink, inject_resources >>> JSLink(link="http://example.com").inject() >>> html = "<html><head></head><body></body></html>" >>> inject_resources(html) '<html><head><script type="text/javascript" src="http://example.com"></script></head><body></body></html>'
Once resources have been injected they are popped from request local and cannot be injected again (in the same request). This is useful in case :class:`injector_middleware` is stacked so it doesn't inject them again.
Injecting them explicitly is necessary if the response's body is being cached before the middleware has a chance to inject them because when the cached version is served no widgets are being rendered so they will not have a chance to register their resources. """
r'<head(?!er).*?>': self._injector_for_location('head'), r'</head(?!er).*?>': self._injector_for_location( 'headbottom', False ), r'<body.*?>': self._injector_for_location('bodytop'), r'</body.*?>': self._injector_for_location('bodybottom', False) }, re.I | re.M)
r.display(displays_on='string') for r in resources if r.location == key ])
"""Injects resources, if any, into html string when called.
.. note:: Ignore the ``self`` parameter if seeing this as :func:`tw.core.resource_injector.inject_resources` docstring since it is an alias for an instance method of a private class.
``html`` must be a ``encoding`` encoded string. If ``encoding`` is not given it will be tried to be derived from a <meta>.
""" self, html, resources, encoding )
# Bind __call__ directly so docstring is included in docs
r"charset\s*=\s*(?P<charset>[\w-]+)([^\>])*", re.I | re.M)
|