Miscellaneous Libraries

Base Controller Classes

The Base Controller API

Provides controller classes for subclassing.

class mediadrop.lib.base.BareBonesController(*args, **kwargs)

Bases: pylons.controllers.core.WSGIController

The Bare Bones extension of a WSGIController needed for this app to function

class mediadrop.lib.base.BaseController(*args, **kwargs)

Bases: mediadrop.lib.base.BareBonesController

The BaseController for all our controllers.

Adds functionality for fetching and updating an externally generated template.

update_external_template(tmpl_url, tmpl_name, timeout)

Conditionally fetch and cache the remote template.

This method will only work on *nix systems.

Parameters:
  • tmpl_url – The URL to fetch the Genshi template from.
  • tmpl_name – The template name to save under.
  • timeout – Number of seconds to wait before refreshing
Return type:

bool

Returns:

True if updated successfully, False if unnecessary.

Raises Exception:
 

If update fails unexpectedly due to IO problems.

class mediadrop.lib.base.BaseSettingsController(*args, **kwargs)

Bases: mediadrop.lib.base.BaseController

Dumb controller for display and saving basic settings forms

This maps forms from mediadrop.forms.admin.settings to our model Setting. This controller doesn’t care what settings are used, the form dictates everything. The form field names should exactly match the name in the model, regardless of it’s nesting in the form.

If and when setting values need to be altered for display purposes, or before it is saved to the database, it should be done with a field validator instead of adding complexity here.

Templating Helpers

class mediadrop.lib.templating.TemplateLoader(search_path=None, auto_reload=False, default_encoding=None, max_cache_size=25, default_class=None, variable_lookup='strict', allow_exec=True, callback=None)

Bases: genshi.template.loader.TemplateLoader

load(filename, relative_to=None, cls=None, encoding=None)

Load the template with the given name.

XXX: This code copied and modified from Genshi 0.6

If the filename parameter is relative, this method searches the search path trying to locate a template matching the given name. If the file name is an absolute path, the search path is ignored.

If the requested template is not found, a TemplateNotFound exception is raised. Otherwise, a Template object is returned that represents the parsed template.

Template instances are cached to avoid having to parse the same template file more than once. Thus, subsequent calls of this method with the same template file name will return the same Template object (unless the auto_reload option is enabled and the file was changed since the last parse.)

If the relative_to parameter is provided, the filename is interpreted as being relative to that path.

Parameters:
  • filename – the relative path of the template file to load
  • relative_to – the filename of the template from which the new template is being loaded, or None if the template is being loaded directly
  • cls – the class of the template object to instantiate
  • encoding – the encoding of the template to load; defaults to the default_encoding of the loader instance
Returns:

the loaded Template instance

Raises TemplateNotFound:
 

if a template with the given name could not be found

class mediadrop.lib.templating.XHTMLPlusSerializer(doctype=None, strip_whitespace=True, namespace_prefixes=None, drop_xml_decl=True, cache=True)

Bases: genshi.output.XHTMLSerializer

XHTML+HTML5 Serializer that produces XHTML text from an event stream.

This serializer is aware that <source/> tags are empty, which is required for it to be valid (working) HTML5 in some browsers.

mediadrop.lib.templating.render(template, tmpl_vars=None, method=None)

Generate a markup stream from the given template and vars.

Parameters:
  • template – A template path.
  • tmpl_vars – A dict of variables to pass into the template.
  • method – Optional serialization method for Genshi to use. If None, we don’t serialize the markup stream into a string. Provide ‘auto’ to use the best guess. See render_stream().
Return type:

genshi.Stream or genshi.Markup

Returns:

An iterable markup stream, or a serialized markup string if method was not None.

mediadrop.lib.templating.render_stream(stream, method='auto', template_name=None)

Render the given stream to a unicode Markup string.

We substitute the standard XHTMLSerializer with our own XHTMLPlusSerializer which is (more) HTML5-aware.

Parameters:
  • stream (genshi.Stream) – An iterable markup stream.
  • method – The serialization method for Genshi to use. If given ‘auto’, the default value, we assume xhtml unless a template name is given with an xml extension.
  • template_name – Optional template name which we use only to guess what method to use, if one hasn’t been explicitly provided.
Return type:

genshi.Markup

Returns:

A subclassed unicode object.

Media Players

class mediadrop.lib.players.AbstractEmbedPlayer(media, uris, data=None, width=None, height=None, autoplay=False, autobuffer=False, qualified=False, **kwargs)

Bases: mediadrop.lib.players.AbstractPlayer

Abstract Embed Player for third-party services like YouTube

Typically embed players will play only their own content, and that is the only way such content can be played. Therefore each embed type has been given its own scheme which uniquely identifies it.

For example, mediadrop.lib.storage.YoutubeStorage.get_uris() returns URIs with a scheme of ‘youtube’, and the special YoutubePlayer would overload scheme to also be ‘youtube’. This would allow the Youtube player to play only those URIs.

classmethod can_play(uris)

Test all the given URIs to see if they can be played by this player.

This is a class method, not an instance or static method.

Parameters:uris (list) – A collection of StorageURI tuples to test.
Return type:tuple
Returns:Boolean result for each of the given URIs.
scheme

The StorageURI.scheme which uniquely identifies this embed type.

class mediadrop.lib.players.AbstractFlashEmbedPlayer(media, uris, data=None, width=None, height=None, autoplay=False, autobuffer=False, qualified=False, **kwargs)

Bases: mediadrop.lib.players.FlashRenderMixin, mediadrop.lib.players.AbstractEmbedPlayer

Simple Abstract Flash Embed Player

Provides sane defaults for most flash-based embed players from third-party vendors, which typically never need any flashvars or special configuration.

flashvars()

Return a python dict of flashvars for this player.

swf_url()

Return the flash player URL.

class mediadrop.lib.players.AbstractFlashPlayer(media, uris, data=None, width=None, height=None, autoplay=False, autobuffer=False, qualified=False, **kwargs)

Bases: mediadrop.lib.players.FileSupportMixin, mediadrop.lib.players.FlashRenderMixin, mediadrop.lib.players.AbstractPlayer

Base Class for standard Flash Players.

This does not typically include flash players from other vendors such as embed types.

flashvars()

Return a python dict of flashvars for this player.

supported_containers = set(['mp4', 'f4v', 'mp3', 'flac', 'flv'])
swf_url()

Return the flash player URL.

class mediadrop.lib.players.AbstractHTML5Player(*args, **kwargs)

Bases: mediadrop.lib.players.FileSupportMixin, mediadrop.lib.players.AbstractPlayer

HTML5 <audio> / <video> tag.

References:

html5_attrs()
render_js_player()
render_markup(error_text=None)

Render the XHTML markup for this player instance.

Parameters:error_text – Optional error text that should be included in the final markup if appropriate for the player.
Return type:unicode or genshi.core.Markup
Returns:XHTML that will not be escaped by Genshi.
supported_containers = set(['mp4', 'm3u8', 'ogg', 'mp3', 'webm'])
supported_schemes = set(['http'])
class mediadrop.lib.players.AbstractIframeEmbedPlayer(media, uris, data=None, width=None, height=None, autoplay=False, autobuffer=False, qualified=False, **kwargs)

Bases: mediadrop.lib.players.AbstractEmbedPlayer

Abstract Embed Player for services that provide an iframe player.

render_js_player()

Render a javascript string to instantiate a javascript player.

Each player has a client-side component to provide a consistent way of initializing and interacting with the player. For more information see mediadrop/public/scripts/mcore/players/.

Return type:unicode
Returns:A javascript string which will evaluate to an instance of a JS player class. For example: new mcore.Html5Player().
class mediadrop.lib.players.AbstractPlayer(media, uris, data=None, width=None, height=None, autoplay=False, autobuffer=False, qualified=False, **kwargs)

Bases: mediadrop.plugin.abc.AbstractClass

Player Base Class that all players must implement.

adjusted_height

Return the desired viewable height + the height of the controls.

adjusted_width

Return the desired viewable width + any extra for the player.

can_play(uris)

Test all the given URIs to see if they can be played by this player.

This is a class method, not an instance or static method.

Parameters:uris (list) – A collection of StorageURI tuples to test.
Return type:tuple
Returns:Boolean result for each of the given URIs.
default_data = {}

An optional default data dictionary for user preferences.

display_name

A unicode display name for the class, to be used in the settings UI.

get_uris(**kwargs)

Return a subset of the uris for this player.

This allows for easy filtering of URIs by feeding any number of kwargs to this function. See mediadrop.lib.uri.pick_uris().

classmethod inject_in_db(enable_player=False)
name

A unicode string identifier for this class.

render_js_player()

Render a javascript string to instantiate a javascript player.

Each player has a client-side component to provide a consistent way of initializing and interacting with the player. For more information see mediadrop/public/scripts/mcore/players/.

Return type:unicode
Returns:A javascript string which will evaluate to an instance of a JS player class. For example: new mcore.Html5Player().
render_markup(error_text=None)

Render the XHTML markup for this player instance.

Parameters:error_text – Optional error text that should be included in the final markup if appropriate for the player.
Return type:unicode or genshi.core.Markup
Returns:XHTML that will not be escaped by Genshi.
settings_form_class = None

An optional mediadrop.forms.admin.players.PlayerPrefsForm.

supports_resizing = True

A flag that allows us to mark the few players that can’t be resized.

Setting this to False ensures that the resize (expand/shrink) controls will not be shown in our player control bar.

class mediadrop.lib.players.AbstractRTMPFlashPlayer(media, uris, data=None, width=None, height=None, autoplay=False, autobuffer=False, qualified=False, **kwargs)

Bases: mediadrop.lib.players.AbstractFlashPlayer

Dummy Base Class for Flash Players that can stream over RTMP.

supported_schemes = set(['http', 'rtmp'])
class mediadrop.lib.players.BlipTVFlashPlayer(media, uris, data=None, width=None, height=None, autoplay=False, autobuffer=False, qualified=False, **kwargs)

Bases: mediadrop.lib.players.AbstractFlashEmbedPlayer

BlipTV Player

This simple player handles media with files that stored using mediadrop.lib.storage.BlipTVStorage.

display_name = u'BlipTV'

A unicode display name for the class, to be used in the settings UI.

name = u'bliptv'

A unicode string identifier for this class.

scheme = u'bliptv'

The StorageURI.scheme which uniquely identifies this embed type.

class mediadrop.lib.players.DailyMotionEmbedPlayer(media, uris, data=None, width=None, height=None, autoplay=False, autobuffer=False, qualified=False, **kwargs)

Bases: mediadrop.lib.players.AbstractIframeEmbedPlayer

Daily Motion Universal Player

This simple player handles media with files that stored using mediadrop.lib.storage.DailyMotionStorage.

This player has seamless HTML5 and Flash support.

display_name = u'Daily Motion'

A unicode display name for the class, to be used in the settings UI.

name = u'dailymotion'

A unicode string identifier for this class.

render_markup(error_text=None)

Render the XHTML markup for this player instance.

Parameters:error_text – Optional error text that should be included in the final markup if appropriate for the player.
Return type:unicode or genshi.core.Markup
Returns:XHTML that will not be escaped by Genshi.
scheme = u'dailymotion'

The StorageURI.scheme which uniquely identifies this embed type.

class mediadrop.lib.players.FileSupportMixin

Bases: object

Mixin that provides a can_play test on a number of common parameters.

classmethod can_play(uris)

Test all the given URIs to see if they can be played by this player.

This is a class method, not an instance or static method.

Parameters:uris (list) – A collection of StorageURI tuples to test.
Return type:tuple
Returns:Boolean result for each of the given URIs.
supported_containers
supported_schemes = set(['http'])
supported_types = set([u'audio', u'video'])
class mediadrop.lib.players.FlashRenderMixin

Bases: object

Mixin for rendering flash players. Used by embedtypes as well as flash.

render_embed(error_text=None)
render_js_player()

Render a javascript string to instantiate a javascript player.

Each player has a client-side component to provide a consistent way of initializing and interacting with the player. For more information see mediadrop/public/scripts/mcore/players/.

Return type:unicode
Returns:A javascript string which will evaluate to an instance of a JS player class. For example: new mcore.Html5Player().
render_object(error_text=None)
render_object_embed(error_text=None)
class mediadrop.lib.players.FlowPlayer(media, uris, data=None, width=None, height=None, autoplay=False, autobuffer=False, qualified=False, **kwargs)

Bases: mediadrop.lib.players.AbstractFlashPlayer

FlowPlayer (Flash)

display_name = u'Flowplayer'

A unicode display name for the class, to be used in the settings UI.

flashvars()

Return a python dict of flashvars for this player.

name = u'flowplayer'

A unicode string identifier for this class.

supported_schemes = set(['http'])
swf_url()

Return the flash player URL.

class mediadrop.lib.players.GoogleVideoFlashPlayer(media, uris, data=None, width=None, height=None, autoplay=False, autobuffer=False, qualified=False, **kwargs)

Bases: mediadrop.lib.players.AbstractFlashEmbedPlayer

Google Video Player

This simple player handles media with files that stored using mediadrop.lib.storage.GoogleVideoStorage.

display_name = u'Google Video'

A unicode display name for the class, to be used in the settings UI.

name = u'googlevideo'

A unicode string identifier for this class.

scheme = u'googlevideo'

The StorageURI.scheme which uniquely identifies this embed type.

class mediadrop.lib.players.HTML5Player(*args, **kwargs)

Bases: mediadrop.lib.players.AbstractHTML5Player

HTML5 Player Implementation.

Seperated from AbstractHTML5Player to make it easier to subclass and provide a custom HTML5 player.

display_name = u'Plain HTML5 Player'

A unicode display name for the class, to be used in the settings UI.

name = u'html5'

A unicode string identifier for this class.

class mediadrop.lib.players.HTML5PlusFlowPlayer(media, uris, **kwargs)

Bases: mediadrop.lib.players.AbstractHTML5Player

HTML5 Player with fallback to FlowPlayer.

default_data = {'prefer_flash': False}

An optional default data dictionary for user preferences.

display_name = u'HTML5 + Flowplayer Fallback'

A unicode display name for the class, to be used in the settings UI.

name = u'html5+flowplayer'

A unicode string identifier for this class.

render_js_player()
render_markup(error_text=None)

Render the XHTML markup for this player instance.

Parameters:error_text – Optional error text that should be included in the final markup if appropriate for the player.
Return type:unicode or genshi.core.Markup
Returns:XHTML that will not be escaped by Genshi.
settings_form_class

An optional mediadrop.forms.admin.players.PlayerPrefsForm.

alias of HTML5OrFlashPrefsForm

supported_containers = set(['m3u8', 'f4v', 'webm', 'mp4', 'mp3', 'flac', 'ogg', 'flv'])
supported_schemes = set(['http'])
class mediadrop.lib.players.JWPlayer(media, uris, **kwargs)

Bases: mediadrop.lib.players.AbstractHTML5Player

JWPlayer (Flash)

display_name = u'JWPlayer'

A unicode display name for the class, to be used in the settings UI.

flash_override_playlist()
js_url()
name = u'jwplayer'

A unicode string identifier for this class.

player_vars()

Return a python dict of vars for this player.

playlist()
plugins()
providers = {u'audio': 'sound', u'video': 'video'}
render_js_player()
render_markup(error_text=None)

Render the XHTML markup for this player instance.

Parameters:error_text – Optional error text that should be included in the final markup if appropriate for the player.
Return type:unicode or genshi.core.Markup
Returns:XHTML that will not be escaped by Genshi.
rtmp_playlist()
supported_containers = set(['xml', 'srt', 'm3u8', 'f4v', 'webm', 'mp4', 'mp3', 'flac', 'ogg', 'flv'])
supported_schemes = set(['http', 'rtmp'])
supported_types = set([u'audio_desc', u'audio', u'video', u'captions'])
swf_url()
class mediadrop.lib.players.SublimePlayer(*args, **kwargs)

Bases: mediadrop.lib.players.AbstractHTML5Player

Sublime Video Player with a builtin flash fallback

default_data = {'script_tag': ''}

An optional default data dictionary for user preferences.

display_name = u'Sublime Video Player'

A unicode display name for the class, to be used in the settings UI.

html5_attrs()
name = u'sublime'

A unicode string identifier for this class.

render_js_player()
render_markup(error_text=None)

Render the XHTML markup for this player instance.

Parameters:error_text – Optional error text that should be included in the final markup if appropriate for the player.
Return type:unicode or genshi.core.Markup
Returns:XHTML that will not be escaped by Genshi.
settings_form_class

An optional mediadrop.forms.admin.players.PlayerPrefsForm.

alias of SublimePlayerPrefsForm

supported_types = set([u'video'])

Sublime does not support AUDIO at this time.

supports_resizing = False

A flag that allows us to mark the few players that can’t be resized.

Setting this to False ensures that the resize (expand/shrink) controls will not be shown in our player control bar.

class mediadrop.lib.players.VimeoUniversalEmbedPlayer(media, uris, data=None, width=None, height=None, autoplay=False, autobuffer=False, qualified=False, **kwargs)

Bases: mediadrop.lib.players.AbstractIframeEmbedPlayer

Vimeo Universal Player

This simple player handles media with files that stored using mediadrop.lib.storage.VimeoStorage.

This player has seamless HTML5 and Flash support.

display_name = u'Vimeo'

A unicode display name for the class, to be used in the settings UI.

name = u'vimeo'

A unicode string identifier for this class.

render_markup(error_text=None)

Render the XHTML markup for this player instance.

Parameters:error_text – Optional error text that should be included in the final markup if appropriate for the player.
Return type:unicode or genshi.core.Markup
Returns:XHTML that will not be escaped by Genshi.
scheme = u'vimeo'

The StorageURI.scheme which uniquely identifies this embed type.

class mediadrop.lib.players.YoutubePlayer(media, uris, data=None, width=None, height=None, autoplay=False, autobuffer=False, qualified=False, **kwargs)

Bases: mediadrop.lib.players.AbstractIframeEmbedPlayer

YouTube Player

This simple player handles media with files that stored using mediadrop.lib.storage.YoutubeStorage.

default_data = {'showinfo': 0, 'modestbranding': 1, 'fs': 1, 'autohide': 2, 'hd': 0, 'wmode': 0, 'disablekb': 0, 'version': 3, 'rel': 0, 'iv_load_policy': 1, 'showsearch': 0, 'autoplay': 0}
display_name = u'YouTube'

A unicode display name for the class, to be used in the settings UI.

name = u'youtube'

A unicode string identifier for this class.

render_markup(error_text=None)

Render the XHTML markup for this player instance.

Parameters:error_text – Optional error text that should be included in the final markup if appropriate for the player.
Return type:unicode or genshi.core.Markup
Returns:XHTML that will not be escaped by Genshi.
scheme = u'youtube'

The StorageURI.scheme which uniquely identifies this embed type.

settings_form_class

An optional mediadrop.forms.admin.players.PlayerPrefsForm.

alias of YoutubePlayerPrefsForm

mediadrop.lib.players.embed_iframe(media, width=400, height=225, frameborder=0, **kwargs)

Return an <iframe> tag that loads our universal player.

Parameters:media (mediadrop.model.media.Media) – The media object that is being rendered, to be passed to all instantiated player objects.
Return type:genshi.builder.Element
Returns:An iframe element stream.
mediadrop.lib.players.embed_player(media, width=400, height=225, frameborder=0, **kwargs)

Return an <iframe> tag that loads our universal player.

Parameters:media (mediadrop.model.media.Media) – The media object that is being rendered, to be passed to all instantiated player objects.
Return type:genshi.builder.Element
Returns:An iframe element stream.
class mediadrop.lib.players.iTunesPlayer(media, uris, data=None, width=None, height=None, autoplay=False, autobuffer=False, qualified=False, **kwargs)

Bases: mediadrop.lib.players.FileSupportMixin, mediadrop.lib.players.AbstractPlayer

A dummy iTunes Player that allows us to test if files can_play().

display_name = u'iTunes Player'

A unicode display name for the class, to be used in the settings UI.

name = u'itunes'

A unicode string identifier for this class.

supported_containers = set(['mp4', 'mp3'])
supported_schemes = set(['http'])
mediadrop.lib.players.media_player(media, is_widescreen=False, show_like=True, show_dislike=True, show_download=False, show_embed=False, show_playerbar=True, show_popout=True, show_resize=False, show_share=True, js_init=None, **kwargs)

Instantiate and render the preferred player that can play this media.

We make no effort to pick the “best” player here, we simply return the first player that can play any of the URIs associated with the given media object. It’s up to the user to declare their own preferences wisely.

Player preferences are fetched from the database and the mediadrop.model.players.c.data dict is passed as kwargs to AbstractPlayer.__init__().

Parameters:
  • media (mediadrop.model.media.Media) – A media instance to play.
  • js_init – Optional function to call after the javascript player controller has been instantiated. Example of a function literal: function(controller){ controller.setFillScreen(true); }. Any function reference can be used as long as it is defined in all pages and accepts the JS player controller as its first and only argument.
  • **kwargs – Extra kwargs for AbstractPlayer.__init__().
Return type:

str or None

Returns:

A rendered player.

mediadrop.lib.players.pick_any_media_file(media)

Return a file playable in at least one of the configured players.

Parameters:media – A Media instance.
Returns:A MediaFile object or None
mediadrop.lib.players.pick_podcast_media_file(media)

Return a file playable in the most podcasting client: iTunes.

Parameters:media – A Media instance.
Returns:A MediaFile object or None
mediadrop.lib.players.preferred_player_for_media(media, **kwargs)
mediadrop.lib.players.update_enabled_players()

Ensure that the encoding status of all media is up to date with the new set of enabled players.

The encoding status of Media objects is dependent on there being an enabled player that supports that format. Call this method after changing the set of enabled players, to ensure encoding statuses are up to date.

Decorators

class mediadrop.lib.decorators.ValidationState

Bases: object

A state for FormEncode validate API with a smart _ hook.

This idea and explanation borrowed from Pylons, modified to work with our custom Translator object.

The FormEncode library used by validate() decorator has some provision for localizing error messages. In particular, it looks for attribute _ in the application-specific state object that gets passed to every .to_python() call. If it is found, the _ is assumed to be a gettext-like function and is called to localize error messages.

One complication is that FormEncode ships with localized error messages for standard validators so the user may want to re-use them instead of gathering and translating everything from scratch. To allow this, we pass as _ a function which looks up translation both in application and formencode message catalogs.

mediadrop.lib.decorators.autocommit(func)

Handle database transactions for the decorated controller actions.

This decorator supports firing callbacks immediately after the transaction is committed or rolled back. This is useful when some external process needs to be called to process some new data, since it should only be called once that data is readable by new transactions.

Note

If your callback makes modifications to the database, you must manually handle the transaction, or apply the @autocommit decorator to the callback itself.

On the ingress, two attributes are added to the webob.Request:

request.commit_callbacks
A list of callback functions that should be called immediately after the DBSession has been committed by this decorator.
request.rollback_callbacks
A list of callback functions that should be called immediately after the DBSession has been rolled back by this decorator.

On the egress, we determine which callbacks should be called, remove the above attributes from the request, and then call the appropriate callbacks.

mediadrop.lib.decorators.beaker_cache(key='cache_default', expire='never', type=None, query_args=False, cache_headers=('content-type', 'content-length'), invalidate_on_startup=False, cache_response=True, **b_kwargs)

Cache decorator utilizing Beaker. Caches action or other function that returns a pickle-able object as a result.

Optional arguments:

key
None - No variable key, uses function name as key “cache_default” - Uses all function arguments as the key string - Use kwargs[key] as key list - Use [kwargs[k] for k in list] as key
expire
Time in seconds before cache expires, or the string “never”. Defaults to “never”
type
Type of cache to use: dbm, memory, file, memcached, or None for Beaker’s default
query_args
Uses the query arguments as the key, defaults to False
cache_headers
A tuple of header names indicating response headers that will also be cached.
invalidate_on_startup
If True, the cache will be invalidated each time the application starts or is restarted.
cache_response

Determines whether the response at the time beaker_cache is used should be cached or not, defaults to True.

Note

When cache_response is set to False, the cache_headers argument is ignored as none of the response is cached.

If cache_enabled is set to False in the .ini file, then cache is disabled globally.

mediadrop.lib.decorators.expose(template='string', request_method=None, permission=None)

Simple expose decorator for controller actions.

Transparently wraps a method in a function that will render the method’s return value with the given template.

Sets the ‘exposed’ and ‘template’ attributes of the wrapped method, marking it as safe to be accessed via HTTP request.

Example, using a genshi template:

class MyController(BaseController):

    @expose('path/to/template.html')
    def sample_action(self, *args):
        # do something
        return dict(message='Hello World!')
Parameters:
  • template (string or unicode) –
    One of:
    • The path to a genshi template, relative to the project’s template directory
    • ‘string’
    • ‘json’
  • request_method – Optional request method to verify. If GET or POST is given and the method of the current request does not match, a 405 Method Not Allowed error is raised.
mediadrop.lib.decorators.expose_xhr(template_norm='string', template_xhr='json', request_method=None, permission=None)

Expose different templates for normal vs XMLHttpRequest requests.

Example, using two genshi templates:

class MyController(BaseController):

    @expose_xhr('items/main_list.html', 'items/ajax_list.html')
    def sample_action(self, *args):
        # do something
        return dict(items=get_items_list())
mediadrop.lib.decorators.memoize(func)

Decorate this function so cached results are returned indefinitely.

Copied from docs for the decorator module by Michele Simionato: http://micheles.googlecode.com/hg/decorator/documentation.html#the-solution

mediadrop.lib.decorators.observable(event)

Filter the result of the decorated action through the events observers.

Parameters:event – An instance of mediadrop.plugin.events.Event whose observers are called.
Returns:A decorator function.
mediadrop.lib.decorators.paginate(name, items_per_page=10, use_prefix=False, items_first_page=None)

Paginate a given collection.

Duplicates and extends the functionality of tg.decorators.paginate() to:

  • Copy the docstring of the exposed method to the decorator, allowing sphinx.ext.autodoc to read docstring.
  • Support our CustomPage extension – used any time items_first_page is provided.

This decorator is mainly exposing the functionality of webhelpers.paginate().

You use this decorator as follows:

class MyController(object):

    @expose()
    @paginate("collection")
    def sample(self, *args):
        collection = get_a_collection()
        return dict(collection=collection)

To render the actual pager, use:

${tmpl_context.paginators.<name>.pager()}

where c is the tmpl_context.

It is possible to have several paginate()-decorators for one controller action to paginate several collections independently from each other. If this is desired, don’t forget to set the use_prefix-parameter to True.

Parameters:
name

the collection to be paginated.

items_per_page

the number of items to be rendered. Defaults to 10

use_prefix

if True, the parameters the paginate decorator renders and reacts to are prefixed with “<name>_”. This allows for multi-pagination.

items_first_page

the number of items to be rendered on the first page. Defaults to the value of items_per_page

class mediadrop.lib.decorators.validate(validators=None, error_handler=None, form=None, state=<class 'mediadrop.lib.decorators.ValidationState'>)

Bases: object

Registers which validators ought to be applied to the following action

Copies the functionality of TurboGears2.0, rather than that of Pylons1.0, except that we validate request.params, not kwargs. TurboGears has the unfortunate need to validate all kwargs because it uses object dispatch. We really only need to validate request.params: if we do need to validate the kw/routing args we can and should do that in our routes.

If you want to validate the contents of your form, you can use the @validate() decorator to register the validators that ought to be called.

Parameters:
validators

Pass in a dictionary of FormEncode validators. The keys should match the form field names.

error_handler

Pass in the controller method which should be used to handle any form errors

form

Pass in a ToscaWidget based form with validators

The first positional parameter can either be a dictionary of validators, a FormEncode schema validator, or a callable which acts like a FormEncode validator.

class mediadrop.lib.decorators.validate_xhr(validators=None, error_handler=None, form=None, state=<class 'mediadrop.lib.decorators.ValidationState'>)

Bases: mediadrop.lib.decorators.validate

Special validation that returns JSON dicts for Ajax requests.

Regular synchronous requests are handled normally.

Example Usage:

@expose_xhr()
@validate_xhr(my_form_instance, error_handler=edit)
def save(self, id, **kwargs):
    something = make_something()
    if request.is_xhr:
        return dict(my_id=something.id)
    else:
        redirect(action='view', id=id)

On success, returns this in addition to whatever dict you provide:

{'success': True, 'values': {}, 'my_id': 123}

On validation error, returns:

{'success': False, 'values': {}, 'errors': {}}

File Types

mediadrop.lib.filetypes.guess_container_format(extension)

Return the most likely container format based on the file extension.

This standardizes to an audio/video-agnostic form of the container, if applicable. For example m4v becomes mp4.

Parameters:extension (string) – the file extension, without a preceding period.
Return type:string
mediadrop.lib.filetypes.guess_media_type(extension=None, default=u'video')

Return the most likely media type based on the container or embed site.

Parameters:
  • extension – The file extension without a preceding period.
  • default – Default to video if we don’t have any other guess.
Returns:

AUDIO, VIDEO, CAPTIONS, or None

mediadrop.lib.filetypes.guess_mimetype(container, type_=None, default=None)

Return the best guess mimetype for the given container.

If the type (audio or video) is not provided, we make our best guess as to which is will probably be, using guess_container_type(). Note that this value is ignored for certain mimetypes: it’s useful only when a container can be both audio and video.

Parameters:
  • container – The file extension
  • type – AUDIO, VIDEO, or CAPTIONS
  • default – Default mimetype for when guessing fails
Returns:

A mime string or None.

Thumbnail Images

mediadrop.lib.thumbnails.create_default_thumbs_for(item)

Create copies of the default thumbs for the given item.

This copies the default files (all named with an id of ‘new’) to use the given item’s id. This means there could be lots of duplicate copies of the default thumbs, but at least we can always use the same url when rendering.

Parameters:item (tuple or mapped class instance) – A 2-tuple with a subdir name and an ID. If given a ORM mapped class with _thumb_dir and id attributes, the info can be extracted automatically.
mediadrop.lib.thumbnails.create_thumbs_for(item, image_file, image_filename)

Creates thumbnails in all sizes for a given Media or Podcast object.

Side effects: Closes the open file handle passed in as image_file.

Parameters:
  • item (tuple or mapped class instance) – A 2-tuple with a subdir name and an ID. If given a ORM mapped class with _thumb_dir and id attributes, the info can be extracted automatically.
  • image_file (file) – An open file handle for the original image file.
  • image_filename (unicode) – The original filename of the thumbnail image.
mediadrop.lib.thumbnails.delete_thumbs(item)

Delete the thumbnails associated with the given item.

Parameters:item (tuple or mapped class instance) – A 2-tuple with a subdir name and an ID. If given a ORM mapped class with _thumb_dir and id attributes, the info can be extracted automatically.
mediadrop.lib.thumbnails.has_thumbs(item)

Return True if a thumb exists for this item.

Parameters:item (tuple or mapped class instance) – A 2-tuple with a subdir name and an ID. If given a ORM mapped class with _thumb_dir and id attributes, the info can be extracted automatically.
mediadrop.lib.thumbnails.has_default_thumbs(item)

Return True if the thumbs for the given item are the defaults.

Parameters:item (tuple or mapped class instance) – A 2-tuple with a subdir name and an ID. If given a ORM mapped class with _thumb_dir and id attributes, the info can be extracted automatically.
class mediadrop.lib.thumbnails.ThumbDict(url, dimensions)

Bases: dict

Dict wrapper with convenient attribute access

mediadrop.lib.thumbnails.thumb(item, size, qualified=False, exists=False)

Get the thumbnail url & dimensions for the given item and size.

Parameters:
  • item (tuple or mapped class instance) – A 2-tuple with a subdir name and an ID. If given a ORM mapped class with _thumb_dir and id attributes, the info can be extracted automatically.
  • size (str) – Size key to display, see thumb_sizes in mediadrop.config.app_config
  • qualified (bool) – If True return the full URL including the domain.
  • exists (bool) – If enabled, checks to see if the file actually exists. If it doesn’t exist, None is returned.
Returns:

The url, width (x) and height (y).

Return type:

ThumbDict with keys url, x, y OR None

mediadrop.lib.thumbnails.thumb_path(item, size, exists=False, ext='jpg')

Get the thumbnail path for the given item and size.

Parameters:
  • item (tuple or mapped class instance) – A 2-tuple with a subdir name and an ID. If given a ORM mapped class with _thumb_dir and id attributes, the info can be extracted automatically.
  • size (str) – Size key to display, see thumb_sizes in mediadrop.config.app_config
  • exists (bool) – If enabled, checks to see if the file actually exists. If it doesn’t exist, None is returned.
  • ext (str) – The extension to use, defaults to jpg.
Returns:

The absolute system path or None.

Return type:

str

mediadrop.lib.thumbnails.thumb_paths(item, **kwargs)

Return a list of paths to all sizes of thumbs for a given item.

Parameters:item (tuple or mapped class instance) – A 2-tuple with a subdir name and an ID. If given a ORM mapped class with _thumb_dir and id attributes, the info can be extracted automatically.
Returns:thumb sizes and their paths
Return type:dict
mediadrop.lib.thumbnails.thumb_url(item, size, qualified=False, exists=False)

Get the thumbnail url for the given item and size.

Parameters:
  • item (tuple or mapped class instance) – A 2-tuple with a subdir name and an ID. If given a ORM mapped class with _thumb_dir and id attributes, the info can be extracted automatically.
  • size (str) – Size key to display, see thumb_sizes in mediadrop.config.app_config
  • qualified (bool) – If True return the full URL including the domain.
  • exists (bool) – If enabled, checks to see if the file actually exists. If it doesn’t exist, None is returned.
Returns:

The relative or absolute URL.

Return type:

str

Email Helpers

Email Helpers

Todo

Clean this module up and use genshi text templates.

mediadrop.lib.email.send(to_addrs, from_addr, subject, body)

A simple method to send a simple email.

Parameters:
  • to_addrs (unicode) – Comma separated list of email addresses to send to.
  • from_addr (unicode) – Email address to put in the ‘from’ field
  • subject (unicode) – Subject line of the email.
  • body (unicode) – Body text of the email, optionally marked up with HTML.
mediadrop.lib.email.send_media_notification(media_obj)

Send a creation notification email that a new Media object has been created.

Sends to the address configured in the ‘email_media_uploaded’ address, if one has been created.

Parameters:media_obj (Media instance) – The media object to send a notification about.
mediadrop.lib.email.send_comment_notification(media_obj, comment)

Helper method to send a email notification that a comment has been posted.

Sends to the address configured in the ‘email_comment_posted’ setting, if it is configured.

Parameters:
  • media_obj (Media instance) – The media object to send a notification about.
  • comment (Comment instance) – The newly posted comment.
mediadrop.lib.email.parse_email_string(string)

Convert a string of comma separated email addresses to a list of separate strings.

mediadrop.lib.email.parse_email_string(string)

Convert a string of comma separated email addresses to a list of separate strings.

mediadrop.lib.email.send(to_addrs, from_addr, subject, body)

A simple method to send a simple email.

Parameters:
  • to_addrs (unicode) – Comma separated list of email addresses to send to.
  • from_addr (unicode) – Email address to put in the ‘from’ field
  • subject (unicode) – Subject line of the email.
  • body (unicode) – Body text of the email, optionally marked up with HTML.
mediadrop.lib.email.send_comment_notification(media_obj, comment)

Helper method to send a email notification that a comment has been posted.

Sends to the address configured in the ‘email_comment_posted’ setting, if it is configured.

Parameters:
  • media_obj (Media instance) – The media object to send a notification about.
  • comment (Comment instance) – The newly posted comment.
mediadrop.lib.email.send_media_notification(media_obj)

Send a creation notification email that a new Media object has been created.

Sends to the address configured in the ‘email_media_uploaded’ address, if one has been created.

Parameters:media_obj (Media instance) – The media object to send a notification about.
mediadrop.lib.email.send_support_request(email, url, description, get_vars, post_vars)

Helper method to send a Support Request email in response to a server error.

Sends to the address configured in the ‘email_support_requests’ setting, if it is configured.

Parameters:
  • email (unicode) – The requesting user’s email address.
  • url (unicode) – The url that the user requested assistance with.
  • description (unicode) – The user’s description of their problem.
  • get_vars (dict of str -> str) – The GET variables sent with the failed request.
  • post_vars (dict of str -> str) – The POST variables sent with the failed request.

Miscellaneous/Display Helpers

Helper functions

Consists of functions to typically be used within templates, but also available to Controllers. This module is available to templates as ‘h’.

mediadrop.lib.helpers.any(iterable) → bool

Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False.

mediadrop.lib.helpers.append_class_attr(attrs, class_name)

Append to the class for any input that Genshi’s py:attrs understands.

This is useful when using XIncludes and you want to append a class to the body tag, while still allowing all other tags to remain unchanged.

For example:

<body py:match="body" py:attrs="h.append_class_attr(select('@*'), 'extra_special')">
Parameters:
  • attrs (genshi.core.Stream, genshi.core.Attrs, list of 2-tuples, dict) – A collection of attrs
  • class_name (unicode) – The class name to append
Returns:

All attrs

Return type:

dict

mediadrop.lib.helpers.best_translation(a, b)

Return the best translation given a preferred and a fallback string.

If we have a translation for our preferred string ‘a’ or if we are using English, return ‘a’. Otherwise, return a translation for the fallback string ‘b’.

Parameters:
  • a – The preferred string to translate.
  • b – The fallback string to translate.
Returns:

The best translation

Return type:

string

mediadrop.lib.helpers.can_edit(item=None)

Return True if the logged in user has the “edit” permission.

For a default install this is true for all members of the “admins” group.

Parameters:item (unimplemented) – unused parameter (deprecated)
Returns:Whether or not the current user has “edit” permission.
Return type:bool
mediadrop.lib.helpers.clean_xhtml(string, p_wrap=True, _cleaner_settings=None)

Convert the given plain text or HTML into valid XHTML.

If there is no markup in the string, apply paragraph formatting.

Parameters:
  • string (unicode) – XHTML input string
  • p_wrap (bool) – Wrap the output in <p></p> tags?
  • _cleaner_settings (dict) – Constructor kwargs for mediadrop.lib.htmlsanitizer.Cleaner
Returns:

XHTML

Return type:

unicode

mediadrop.lib.helpers.content_type_for_response(available_formats)
mediadrop.lib.helpers.current_url(with_qs=True, qualified=True)

This method returns the “current” (as in “url as request by the user”) url.

The default “url_for()” returns the current URL in most cases however when the error controller is triggered “url_for()” will return the url of the error document (‘<host>/error/document’) instead of the url requested by the user.

mediadrop.lib.helpers.decode_entities(text)

Converts HTML entities to unicode. For example ‘&amp;’ becomes ‘&’.

FIXME: WARNING: There is a bug between sgmllib.SGMLParser.goahead() and BeautifulSoup.BeautifulStoneSoup.handle_entityref() where entity-like strings that don’t match known entities are guessed at (if they come in the middle of the text) or are omitted (if they come at the end of the text).

Further, unrecognized entities will have their leading ampersand escaped and trailing semicolon (if it exists) stripped. Examples:

Inputs ”...&bob;...”, ”...&bob&...”, ”...&bob;”, and ”...&bob” will give outputs ”...&amp;bob...”, ”...&amp;bob&...”, ”...&amp;bob”, and ”...”, respectively.

mediadrop.lib.helpers.delete_files(paths, subdir=None)

Move the given files to the ‘deleted’ folder, or just delete them.

If the config contains a deleted_files_dir setting, then files are moved there. If that setting does not exist, or is empty, then the files will be deleted permanently instead.

Parameters:
  • paths (iterable) – File paths to delete. These files do not necessarily have to exist.
  • subdir (str or None) – A subdir within the configured deleted_files_dir to move the given files to. If this folder does not yet exist, it will be created.

Return a link (anchor element) to the documentation on the project site.

XXX: Target attribute is not XHTML compliant.

mediadrop.lib.helpers.duration_from_seconds(total_sec, shortest=True)

Return the HH:MM:SS duration for a given number of seconds.

Does not support durations longer than 24 hours.

Parameters:
  • total_sec (int) – Number of seconds to convert into hours, mins, sec
  • shortest – If True, return the shortest possible timestamp. Defaults to True.
Return type:

unicode

Returns:

String HH:MM:SS, omitting the hours if less than one.

mediadrop.lib.helpers.duration_to_seconds(duration)

Return the number of seconds in a given HH:MM:SS.

Does not support durations longer than 24 hours.

Parameters:duration (unicode) – A HH:MM:SS or MM:SS formatted string
Return type:int
Returns:seconds
Raises ValueError:
 If the input doesn’t matched the accepted formats
mediadrop.lib.helpers.encode_entities(text)

Escapes only those entities that are required for XHTML compliance

mediadrop.lib.helpers.excerpt_xhtml(string, size, buffer=60)

Return an excerpt for the given string.

Truncate to the given size iff we are removing more than the buffer size.

Parameters:
  • string – A XHTML string
  • size (int) – The desired length
  • buffer (int) – How much more than the desired length we can go to avoid truncating just a couple words etc.
Returns:

XHTML

mediadrop.lib.helpers.filter_library_controls(query, show='latest')
mediadrop.lib.helpers.filter_vulgarity(text)

Return a sanitized version of the given string.

Words are defined in the Comments settings and are replaced with *’s representing the length of the filtered word.

Parameters:text (str) – The string to be filtered.
Returns:The filtered string.
Return type:str
mediadrop.lib.helpers.format_date(date=None, format='medium')

Return a date formatted according to the given pattern.

This uses the locale of the current request’s pylons.translator.

Parameters:
  • date – the date or datetime object; if None, the current date is used
  • format – one of “full”, “long”, “medium”, or “short”, or a custom date/time pattern
Return type:

unicode

mediadrop.lib.helpers.format_datetime(datetime=None, format='medium', tzinfo=None)

Return a date formatted according to the given pattern.

This uses the locale of the current request’s pylons.translator.

Parameters:
  • datetime – the datetime object; if None, the current date and time is used
  • format – one of “full”, “long”, “medium”, or “short”, or a custom date/time pattern
  • tzinfo – the timezone to apply to the time for display
Return type:

unicode

mediadrop.lib.helpers.format_decimal(number)

Return a formatted number (using the correct decimal mark).

This uses the locale of the current request’s pylons.translator.

Parameters:number – the int, float or decimal object
Return type:unicode
mediadrop.lib.helpers.format_paragraphs(text, preserve_lines=False)

Convert text to HTML paragraphs.

text:
the text to convert. Split into paragraphs at blank lines (i.e., wherever two or more consecutive newlines appear), and wrap each paragraph in a <p>.
preserve_lines:
If true, add <br /> before each single line break
mediadrop.lib.helpers.format_time(time=None, format='medium', tzinfo=None)

Return a time formatted according to the given pattern.

This uses the locale of the current request’s pylons.translator.

Parameters:
  • time – the time or datetime object; if None, the current time in UTC is used
  • format – one of “full”, “long”, “medium”, or “short”, or a custom date/time pattern
  • tzinfo – the time-zone to apply to the time for display
Return type:

unicode

mediadrop.lib.helpers.gravatar_from_email(email, size)

Return the URL for a gravatar image matching the provided email address.

Parameters:
  • email (string or unicode or None) – the email address
  • size (int) – the width (or height) of the desired image
mediadrop.lib.helpers.is_admin()

Return True if the logged in user has the “admin” permission.

For a default install a user has the “admin” permission if he is a member of the “admins” group.

Returns:Whether or not the current user has “admin” permission.
Return type:bool
mediadrop.lib.helpers.js(source)
mediadrop.lib.helpers.line_break_xhtml(string)

Add a linebreak after block-level tags are closed.

Return type:unicode
mediadrop.lib.helpers.list_acceptable_xhtml()
class mediadrop.lib.helpers.literal

Bases: unicode

Represents an HTML literal.

This subclass of unicode has a .__html__() method that is detected by the escape() function.

Also, if you add another string to this string, the other string will be quoted and you will get back another literal object. Also literal(...) % obj will quote any value(s) from obj. If you do something like literal(...) + literal(...), neither string will be changed because escape(literal(...)) doesn’t change the original literal.

capitalize() → unicode

Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case.

center(width[, fillchar]) → unicode

Return S centered in a Unicode string of length width. Padding is done using the specified fill character (default is a space)

expandtabs([tabsize]) → unicode

Return a copy of S where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed.

join(items)
ljust(width[, fillchar]) → int

Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space).

lower() → unicode

Return a copy of the string S converted to lowercase.

lstrip([chars]) → unicode

Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is a str, it will be converted to unicode before stripping

partition(sep) -> (head, sep, tail)

Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings.

replace(old, new[, count]) → unicode

Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

rjust(width[, fillchar]) → unicode

Return S right-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space).

rpartition(sep) -> (head, sep, tail)

Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S.

rsplit(*args, **kwargs)
rstrip([chars]) → unicode

Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is a str, it will be converted to unicode before stripping

split(*args, **kwargs)
splitlines(*args, **kwargs)
strip([chars]) → unicode

Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is a str, it will be converted to unicode before stripping

swapcase() → unicode

Return a copy of S with uppercase characters converted to lowercase and vice versa.

title() → unicode

Return a titlecased version of S, i.e. words start with title case characters, all remaining cased characters have lower case.

translate(table) → unicode

Return a copy of the string S, where all characters have been mapped through the given translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or None. Unmapped characters are left untouched. Characters mapped to None are deleted.

upper() → unicode

Return a copy of S converted to uppercase.

zfill(width) → unicode

Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated.

mediadrop.lib.helpers.mediadrop_version()
mediadrop.lib.helpers.pick_any_media_file(media)

Return a file playable in at least one of the configured players.

Parameters:media – A Media instance.
Returns:A MediaFile object or None
mediadrop.lib.helpers.pick_podcast_media_file(media)

Return a file playable in the most podcasting client: iTunes.

Parameters:media – A Media instance.
Returns:A MediaFile object or None
mediadrop.lib.helpers.pretty_file_size(size)

Return the given file size in the largest possible unit of bytes.

mediadrop.lib.helpers.quote('abc def') → 'abc%20def'

Each part of a URL, e.g. the path info, the query, etc., has a different set of reserved characters that must be quoted.

RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists the following reserved characters.

reserved = ”;” | “/” | ”?” | ”:” | “@” | “&” | “=” | “+” |
“$” | ”,”

Each of these characters is reserved in some component of a URL, but not necessarily in all of them.

By default, the quote function is intended for quoting the path section of a URL. Thus, it will not encode ‘/’. This character is reserved, but in typical usage the quote function is being called on a path where the existing slash characters are used as reserved characters.

mediadrop.lib.helpers.redirect(*args, **kwargs)

Compose a URL using url_for() and raise a redirect.

Raises:webob.exc.HTTPFound
mediadrop.lib.helpers.store_transient_message(cookie_name, text, time=None, path='/', **kwargs)

Store a JSON message dict in the named cookie.

The cookie will expire at the end of the session, but should be explicitly deleted by whoever reads it.

Parameters:
  • cookie_name – The cookie name for this message.
  • text – Message text
  • time – Optional time to report. Defaults to now.
  • path – Optional cookie path
  • kwargs – Passed into the JSON dict
Returns:

The message python dict

Return type:

dict

mediadrop.lib.helpers.strip_xhtml(string, _decode_entities=False)

Strip out xhtml and optionally convert HTML entities to unicode.

Return type:unicode
mediadrop.lib.helpers.thumb(item, size, qualified=False, exists=False)

Get the thumbnail url & dimensions for the given item and size.

Parameters:
  • item (tuple or mapped class instance) – A 2-tuple with a subdir name and an ID. If given a ORM mapped class with _thumb_dir and id attributes, the info can be extracted automatically.
  • size (str) – Size key to display, see thumb_sizes in mediadrop.config.app_config
  • qualified (bool) – If True return the full URL including the domain.
  • exists (bool) – If enabled, checks to see if the file actually exists. If it doesn’t exist, None is returned.
Returns:

The url, width (x) and height (y).

Return type:

ThumbDict with keys url, x, y OR None

mediadrop.lib.helpers.thumb_url(item, size, qualified=False, exists=False)

Get the thumbnail url for the given item and size.

Parameters:
  • item (tuple or mapped class instance) – A 2-tuple with a subdir name and an ID. If given a ORM mapped class with _thumb_dir and id attributes, the info can be extracted automatically.
  • size (str) – Size key to display, see thumb_sizes in mediadrop.config.app_config
  • qualified (bool) – If True return the full URL including the domain.
  • exists (bool) – If enabled, checks to see if the file actually exists. If it doesn’t exist, None is returned.
Returns:

The relative or absolute URL.

Return type:

str

mediadrop.lib.helpers.truncate(string, size, whole_word=True)

Truncate a plaintext string to roughly a given size (full words).

Parameters:
  • string (unicode) – plaintext
  • size – Max length
  • whole_word – Whether to prefer truncating at the end of a word. Defaults to True.
Return type:

unicode

mediadrop.lib.helpers.truncate_xhtml(string, size, _strip_xhtml=False, _decode_entities=False)

Truncate a XHTML string to roughly a given size (full words).

Parameters:
  • string (unicode) – XHTML
  • size – Max length
  • _strip_xhtml – Flag to strip out all XHTML
  • _decode_entities – Flag to convert XHTML entities to unicode chars
Return type:

unicode

mediadrop.lib.helpers.unquote('abc%20def') → 'abc def'.
mediadrop.lib.helpers.url(*args, **kwargs)

Compose a URL with pylons.url(), all arguments are passed.

mediadrop.lib.helpers.url_for(*args, **kwargs)

Compose a URL pylons.url.current(), all arguments are passed.

mediadrop.lib.helpers.url_for_media(media, qualified=False)

Return the canonical URL for that media (‘/media/view’).

mediadrop.lib.helpers.urlencode(query, doseq=0)

Encode a sequence of two-element tuples or dictionary into a URL query string.

If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter.

If the query arg is a sequence of two-element tuples, the order of the parameters in the output will match the order of parameters in the input.

mediadrop.lib.helpers.urlparse(url, scheme='', allow_fragments=True)

Parse a URL into 6 components: <scheme>://<netloc>/<path>;<params>?<query>#<fragment> Return a 6-tuple: (scheme, netloc, path, params, query, fragment). Note that we don’t break the components up in smaller bits (e.g. netloc is a single string) and we don’t expand % escapes.

mediadrop.lib.helpers.viewable_media(query)
mediadrop.lib.helpers.wrap_long_words(string, _encode_entities=True)

Inject <wbr> periodically to let the browser wrap the string.

The <wbr /> tag is widely deployed and included in HTML5, but it isn’t XHTML-compliant. See this for more info: http://dev.w3.org/html5/spec/text-level-semantics.html#the-wbr-element

Return type:literal
You're reading the documentation for MediaDrop 0.11dev (current git master). For the latest stable release please consult the documentation for MediaCore CE 0.10.