本文整理汇总了Python中mediadrop.lib.i18n._函数的典型用法代码示例。如果您正苦于以下问题:Python _函数的具体用法?Python _怎么用?Python _使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_media_notification_to_author
def send_media_notification_to_author(media_obj):
"""
Send a creation notification email to author that a new Media object has been
created.
:param media_obj: The media object to send a notification about.
:type media_obj: :class:`~mediadrop.model.media.Media` instance
"""
send_to = [media_obj.author.email]
if not send_to:
# media notification emails are disabled!
return
#FIXME: extract host from env on production server
edit_url = 'http://127.0.0.1/media/' + media_obj.slug
clean_description = strip_xhtml(line_break_xhtml(line_break_xhtml(media_obj.description)))
type = media_obj.type
title = media_obj.title
author_name = media_obj.author.name
author_email = media_obj.author.email
subject = _('New %(type)s: %(title)s') % locals()
body = _("""A new %(type)s file has been uploaded!
Title: %(title)s
Author: %(author_name)s (%(author_email)s)
Video URL: %(edit_url)s
Description: %(clean_description)s
""") % locals()
send(send_to, request.settings['email_send_from'], subject, body)
示例2: _retrieve_video_details
def _retrieve_video_details(self, video_id, parts):
search = self.youtube.videos().list(
id=video_id,
part=parts,
)
try:
search_response = search.execute()
except apiclient.errors.HttpError as api_error:
response_content = api_error.content
# LATER: log raw error content
error_details = json.loads(response_content)['error']['errors'][0]
reason = error_details['reason']
youtube_reason = reason
if 'message' in error_details:
youtube_reason += ' / ' + error_details['message']
message = _('unknown YouTube error: %(reason)s') % dict(reason=youtube_reason)
if reason == 'keyInvalid':
message = _('Invalid API key. Please check your Google API key in settings.')
elif reason == 'accessNotConfigured':
# Access Not Configured. The API (YouTube Data API) is not
# enabled for your project. Please use the Google Developers
# Console to update your configuration.
message = error_details['message']
return Result(False, message=message)
videos = search_response.get('items', [])
return videos
示例3: _parse
def _parse(self, url, **kwargs):
"""Return metadata for the given URL that matches :attr:`url_pattern`.
:type url: unicode
:param url: A remote URL string.
:param \*\*kwargs: The named matches from the url match object.
:rtype: dict
:returns: Any extracted metadata.
"""
id = kwargs['id']
yt_service = gdata.youtube.service.YouTubeService()
yt_service.ssl = False
try:
entry = yt_service.GetYouTubeVideoEntry(video_id=id)
except gdata.service.RequestError, request_error:
e = request_error.args[0]
if e['status'] == 403 and e['body'] == 'Private video':
raise UserStorageError(
_('This video is private and cannot be embedded.'))
elif e['status'] == 400 and e['body'] == 'Invalid id':
raise UserStorageError(
_('Invalid YouTube URL. This video does not exist.'))
raise UserStorageError(_('YouTube Error: %s') % e['body'])
示例4: send_comment_notification
def 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.
:param media_obj: The media object to send a notification about.
:type media_obj: :class:`~mediadrop.model.media.Media` instance
:param comment: The newly posted comment.
:type comment: :class:`~mediadrop.model.comments.Comment` instance
"""
send_to = request.settings['email_comment_posted']
if not send_to:
# Comment notification emails are disabled!
return
author_name = media_obj.author.name
comment_subject = comment.subject
post_url = url_for_media(media_obj, qualified=True)
comment_body = strip_xhtml(line_break_xhtml(line_break_xhtml(comment.body)))
subject = _('New Comment: %(comment_subject)s') % locals()
body = _("""A new comment has been posted!
Author: %(author_name)s
Post: %(post_url)s
Body: %(comment_body)s
""") % locals()
send(send_to, request.settings['email_send_from'], subject, body)
示例5: boolean_radiobuttonlist
def boolean_radiobuttonlist(name, **kwargs):
return RadioButtonList(
name,
options=lambda: ((True, _('Yes')), (False, _('No'))),
validator=StringBool,
**kwargs
)
示例6: register_default_types
def register_default_types():
default_types = [
(VIDEO, _('Video')),
(AUDIO, _('Audio')),
(AUDIO_DESC, _('Audio Description')),
(CAPTIONS, _('Captions')),
]
for t in default_types:
yield t
示例7: index
def index(self, page=1, show='latest', q=None, tag=None, **kwargs):
"""List media with pagination.
The media paginator may be accessed in the template with
:attr:`c.paginators.media`, see :class:`webhelpers.paginate.Page`.
:param page: Page number, defaults to 1.
:type page: int
:param show: 'latest', 'popular' or 'featured'
:type show: unicode or None
:param q: A search query to filter by
:type q: unicode or None
:param tag: A tag slug to filter for
:type tag: unicode or None
:rtype: dict
:returns:
media
The list of :class:`~mediadrop.model.media.Media` instances
for this page.
result_count
The total number of media items for this query
search_query
The query the user searched for, if any
"""
media = Media.query.published()
media, show = helpers.filter_library_controls(media, show)
if q:
media = media.search(q, bool=True)
if tag:
tag = fetch_row(Tag, slug=tag)
media = media.filter(Media.tags.contains(tag))
if (request.settings['rss_display'] == 'True') and (not (q or tag)):
if show == 'latest':
response.feed_links.extend([
(url_for(controller='/sitemaps', action='latest'), _(u'Latest RSS')),
])
elif show == 'featured':
response.feed_links.extend([
(url_for(controller='/sitemaps', action='featured'), _(u'Featured RSS')),
])
media = viewable_media(media)
return dict(
media = media,
result_count = media.count(),
search_query = q,
show = show,
tag = tag,
)
示例8: explore
def explore(self, **kwargs):
"""Display the most recent 15 media.
:rtype: Dict
:returns:
latest
Latest media
popular
Latest media
"""
media = Media.query.published()
latest = media.order_by(Media.publish_on.desc())
popular = media.order_by(Media.popularity_points.desc())
featured = None
is_featured_item_enabled = request.settings['appearance_enable_featured_items'] or request.settings['appearance_enable_cooliris']
if is_featured_item_enabled:
featured_cat = helpers.get_featured_category()
if featured_cat:
featured = viewable_media(latest.in_category(featured_cat)).first()
if not featured:
featured = viewable_media(popular).first()
nr_latest_items = 8
if is_featured_item_enabled:
nr_popular_items = max(nr_latest_items - 3, 0)
else:
nr_popular_items = nr_latest_items
popular = viewable_media(popular.exclude(featured))[:nr_popular_items]
latest = viewable_media(latest.exclude(featured, popular))[:nr_latest_items]
if request.settings['sitemaps_display'] == 'True':
response.feed_links.extend([
(url_for(controller='/sitemaps', action='google'), _(u'Sitemap XML')),
(url_for(controller='/sitemaps', action='mrss'), _(u'Sitemap RSS')),
])
if request.settings['rss_display'] == 'True':
response.feed_links.extend([
(url_for(controller='/sitemaps', action='latest'), _(u'Latest RSS')),
])
return dict(
featured = featured,
latest = latest,
popular = popular,
categories = Category.query.populated_tree(),
)
示例9: _parse
def _parse(self, url, **kwargs):
"""Return metadata for the given URL that matches :attr:`url_pattern`.
:type url: unicode
:param url: A remote URL string.
:param \*\*kwargs: The named matches from the url match object.
:rtype: dict
:returns: Any extracted metadata.
"""
id = kwargs['id']
# Ensure the video uses the .com TLD for the API request.
url = 'http://www.dailymotion.com/video/%s' % id
data_url = 'http://www.dailymotion.com/services/oembed?' + \
urlencode({'format': 'json', 'url': url})
headers = {'User-Agent': USER_AGENT}
req = Request(data_url, headers=headers)
try:
temp_data = urlopen(req)
try:
data_string = temp_data.read()
if data_string == 'This video cannot be embeded.':
raise UserStorageError(
_('This DailyMotion video does not allow embedding.'))
data = simplejson.loads(data_string)
finally:
temp_data.close()
except URLError, e:
log.exception(e)
data = {}
示例10: best_translation
def 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'.
:param a: The preferred string to translate.
:param b: The fallback string to translate.
:returns: The best translation
:rtype: string
"""
translated_a = _(a)
if a != translated_a or translator.locale.language == 'en':
return translated_a
else:
return _(b)
示例11: _parse
def _parse(self, url, id, **kwargs):
"""Return metadata for the given URL that matches :attr:`url_pattern`.
:type url: unicode
:param url: A remote URL string.
:param \*\*kwargs: The named matches from the url match object.
:rtype: dict
:returns: Any extracted metadata.
"""
if '?' in url:
url += '&skin=api'
else:
url += '?skin=api'
req = Request(url)
try:
temp_data = urlopen(req)
xmlstring = temp_data.read()
try:
try:
xmltree = ElementTree.fromstring(xmlstring)
except:
temp_data.close()
raise
except SyntaxError:
raise UserStorageError(
_('Invalid BlipTV URL. This video does not exist.'))
except URLError, e:
log.exception(e)
raise
示例12: fetch_video_details
def fetch_video_details(self, video_id):
video_result = self._retrieve_video_details(video_id, 'snippet,contentDetails')
# LATER: add debug logging for youtube response
if video_result == False:
return Result(
False,
meta_info=None,
message=video_result.message
)
elif len(video_result) == 0:
return Result(
False,
meta_info=None,
message=_('Invalid YouTube URL. This video does not exist or is private and can not be embedded.')
)
video_details = video_result[0]
iso8601_duration = video_details['contentDetails']['duration']
duration = aniso8601.parse_duration(iso8601_duration)
snippet = video_details['snippet']
best_thumbnail = self._find_biggest_thumbnail(snippet['thumbnails'])
meta_info = {
'unique_id': video_details['id'],
'duration': timedelta_to_seconds(duration),
'display_name': snippet['title'],
'description': snippet['description'],
'thumbnail': {
'width': best_thumbnail['width'],
'height': best_thumbnail['height'],
'url': best_thumbnail['url'],
},
'type': VIDEO,
}
return Result(True, meta_info=meta_info, message=None)
示例13: store
def store(self, media_file, file=None, url=None, meta=None):
"""Store the given file or URL and return a unique identifier for it.
:type media_file: :class:`~mediadrop.model.media.MediaFile`
:param media_file: The associated media file object.
:type file: :class:`cgi.FieldStorage` or None
:param file: A freshly uploaded file object.
:type url: unicode or None
:param url: A remote URL string.
:type meta: dict
:param meta: The metadata returned by :meth:`parse`.
:rtype: unicode or None
:returns: The unique ID string. Return None if not generating it here.
:raises SwiftUploadError: If storing the file fails.
"""
file_name = safe_file_name(media_file, file.filename)
swift = self._connect()
try:
swift.put_object(config['swift_container'], file_name, file.file)
swift.close()
except Exception, e:
log.exception(e)
swift.close()
msg = _('Could not upload the file to your Swift server: %s')\
% e.message
raise SwiftUploadError(msg, None, None)
示例14: save_thumb
def save_thumb(self, id, thumb, **kwargs):
"""Save a thumbnail uploaded with :class:`~mediadrop.forms.admin.ThumbForm`.
:param id: Media ID. If ``"new"`` a new Media stub is created.
:type id: ``int`` or ``"new"``
:param file: The uploaded file
:type file: :class:`cgi.FieldStorage` or ``None``
:rtype: JSON dict
:returns:
success
bool
message
Error message, if unsuccessful
id
The :attr:`~mediadrop.model.media.Media.id` which is
important if a new media has just been created.
"""
if id == 'new':
media = Media()
user = request.perm.user
media.author = Author(user.display_name, user.email_address)
media.title = os.path.basename(thumb.filename)
media.slug = get_available_slug(Media, '_stub_' + media.title)
DBSession.add(media)
DBSession.flush()
else:
media = fetch_row(Media, id)
try:
# Create JPEG thumbs
create_thumbs_for(media, thumb.file, thumb.filename)
success = True
message = None
except IOError, e:
success = False
if id == 'new':
DBSession.delete(media)
if e.errno == 13:
message = _('Permission denied, cannot write file')
elif e.message == 'cannot identify image file':
message = _('Unsupported image type: %s') \
% os.path.splitext(thumb.filename)[1].lstrip('.')
elif e.message == 'cannot read interlaced PNG files':
message = _('Interlaced PNGs are not supported.')
else:
raise
示例15: send_support_request
def 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.
:param email: The requesting user's email address.
:type email: unicode
:param url: The url that the user requested assistance with.
:type url: unicode
:param description: The user's description of their problem.
:type description: unicode
:param get_vars: The GET variables sent with the failed request.
:type get_vars: dict of str -> str
:param post_vars: The POST variables sent with the failed request.
:type post_vars: dict of str -> str
"""
send_to = request.settings['email_support_requests']
if not send_to:
return
get_vars = "\n\n ".join(x + " : " + get_vars[x] for x in get_vars)
post_vars = "\n\n ".join([x + " : " + post_vars[x] for x in post_vars])
subject = _('New Support Request: %(email)s') % locals()
body = _("""A user has asked for support
Email: %(email)s
URL: %(url)s
Description: %(description)s
GET_VARS:
%(get_vars)s
POST_VARS:
%(post_vars)s
""") % locals()
send(send_to, request.settings['email_send_from'], subject, body)