本文整理汇总了Python中mediacore.model.fetch_row函数的典型用法代码示例。如果您正苦于以下问题:Python fetch_row函数的具体用法?Python fetch_row怎么用?Python fetch_row使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了fetch_row函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save
def save(self, id, email_address, display_name, login_details,
delete=None, **kwargs):
"""Save changes or create a new :class:`~mediacore.model.auth.User` instance.
:param id: User ID. If ``"new"`` a new user is created.
:type id: ``int`` or ``"new"``
:returns: Redirect back to :meth:`index` after successful save.
"""
user = fetch_row(User, id)
if delete:
DBSession.delete(user)
redirect(action='index', id=None)
user.display_name = display_name
user.email_address = email_address
user.user_name = login_details['user_name']
password = login_details['password']
if password is not None and password != '':
user.password = password
if login_details['group']:
group = fetch_row(Group, login_details['group'])
user.groups = [group]
else:
user.groups = []
DBSession.add(user)
DBSession.flush()
redirect(action='index', id=None)
示例2: reorder
def reorder(self, id, direction, **kwargs):
"""Reorder a PlayerPref.
:param id: Player ID.
:type id: ``int``
:param direction: ``"up"`` for higher priority, ``"down"`` for
lower priority
:type direction: ``unicode``
:returns: Redirect back to :meth:`index` after success.
"""
if direction == 'up':
offset = -1
elif direction == 'down':
offset = 1
else:
return
player1 = fetch_row(PlayerPrefs, id)
new_priority = player1.priority + offset
try:
player2 = fetch_row(PlayerPrefs, priority=new_priority)
player2.priority = player1.priority
player1.priority = new_priority
except HTTPException, e:
if e.code != 404:
raise
示例3: index
def index(self, page=1, search=None, filter=None, podcast=None, category=None, tag=None, **kwargs):
"""List media with pagination and filtering.
:param page: Page number, defaults to 1.
:type page: int
:param search: Optional search term to filter by
:type search: unicode or None
:param podcast_filter: Optional podcast to filter by
:type podcast_filter: int or None
:rtype: dict
:returns:
media
The list of :class:`~mediacore.model.media.Media` instances
for this page.
search
The given search term, if any
search_form
The :class:`~mediacore.forms.admin.SearchForm` instance
podcast
The podcast object for rendering if filtering by podcast.
"""
media = Media.query.options(orm.undefer("comment_count_published"))
if search:
media = media.admin_search(search)
else:
media = media.order_by_status().order_by(Media.publish_on.desc(), Media.modified_on.desc())
if not filter:
pass
elif filter == "unreviewed":
media = media.reviewed(False)
elif filter == "unencoded":
media = media.reviewed().encoded(False)
elif filter == "drafts":
media = media.drafts()
elif filter == "published":
media = media.published()
if category:
category = fetch_row(Category, slug=category)
media = media.filter(Media.categories.contains(category))
if tag:
tag = fetch_row(Tag, slug=tag)
media = media.filter(Media.tags.contains(tag))
if podcast:
podcast = fetch_row(Podcast, slug=podcast)
media = media.filter(Media.podcast == podcast)
return dict(
media=media,
search=search,
search_form=search_form,
media_filter=filter,
category=category,
tag=tag,
podcast=podcast,
)
示例4: save
def save(self, id, delete=None, **kwargs):
"""Save changes or create a category.
See :class:`~mediacore.forms.admin.settings.categories.CategoryForm` for POST vars.
:param id: Category ID
:param delete: If true the category is to be deleted rather than saved.
:type delete: bool
:rtype: JSON dict
:returns:
success
bool
"""
if tmpl_context.form_errors:
if request.is_xhr:
return dict(success=False, errors=tmpl_context.form_errors)
else:
# TODO: Add error reporting for users with JS disabled?
return redirect(action="edit")
cat = fetch_row(Category, id)
if delete:
DBSession.delete(cat)
data = dict(success=True, id=cat.id, parent_options=unicode(category_form.c["parent_id"].display()))
else:
cat.name = kwargs["name"]
cat.slug = get_available_slug(Category, kwargs["slug"], cat)
if kwargs["parent_id"]:
parent = fetch_row(Category, kwargs["parent_id"])
if parent is not cat and cat not in parent.ancestors():
cat.parent = parent
else:
cat.parent = None
DBSession.add(cat)
DBSession.flush()
data = dict(
success=True,
id=cat.id,
name=cat.name,
slug=cat.slug,
parent_id=cat.parent_id,
parent_options=unicode(category_form.c["parent_id"].display()),
depth=cat.depth(),
row=unicode(
category_row_form.display(
action=url_for(id=cat.id), category=cat, depth=cat.depth(), first_child=True
)
),
)
if request.is_xhr:
return data
else:
redirect(action="index", id=None)
示例5: edit_file
def edit_file(self, id, file_id, file_type=None, delete=None, **kwargs):
"""Save action for the :class:`~mediacore.forms.admin.media.EditFileForm`.
Changes or delets a :class:`~mediacore.model.media.MediaFile`.
:param id: Media ID
:type id: :class:`int`
:rtype: JSON dict
:returns:
success
bool
message
Error message, if unsuccessful
status_form
Rendered XHTML for the status form, updated to reflect the
changes made.
"""
media = fetch_row(Media, id)
data = dict(success=False)
try:
file = [file for file in media.files if file.id == int(file_id)][0]
except IndexError:
data['message'] = 'File no longer exists.'
if file_type:
file.type = file_type
DBSession.add(file)
data['success'] = True
elif delete:
file_path = file.file_path
DBSession.delete(file)
transaction.commit()
if file_path:
helpers.delete_files([file_path], 'media')
media = fetch_row(Media, id)
data['success'] = True
else:
data['message'] = 'No action to perform.'
if data['success']:
data['file_type'] = file.type
media.update_type()
media.update_status()
DBSession.add(media)
DBSession.flush()
# Return the rendered widget for injection
status_form_xhtml = unicode(update_status_form.display(
action=url_for(action='update_status'), media=media))
data['status_form'] = status_form_xhtml
return data
示例6: latest
def latest(self, type=None, podcast=None, ignore=None,
topic=None, tag=None, **kwargs):
"""Expose basic info of the latest media object.
.. todo:: Work this into a more general, documented API scheme.
:param type: ``audio``, ``video``, or ``None`` for either
:param podcast: A :attr:`mediacore.model.podcasts.Podcast.slug`
or empty string.
:param topic: A topic slug
:param ignore: A slug (or slugs, separated by whitespace)
to always exclude from results. This allows us to fetch
two DIFFERENT results when calling this action twice.
:rtype: JSON dict
"""
media_query = self._published_media_query
if type:
media_query = media_query.filter(Media.type == type)
# Filter by podcast, if podcast slug provided
if podcast != None:
if podcast == '':
media_query = media_query\
.filter(Media.podcast_id == None)
else:
podcast = fetch_row(Podcast, slug=podcast)
media_query = media_query\
.filter(Media.podcast_id == podcast.id)
# Filter by topic, if topic slug provided
if topic:
topic = fetch_row(Topic, slug=topic)
media_query = media_query\
.filter(Media.topics.contains(topic))
# Filter by tag, if tag slug provided
if tag:
tag = fetch_row(Tag, slug=tag)
media_query = media_query\
.filter(Media.tags.contains(tag))
# Filter out a media item we don't like
if ignore:
ignore = ignore.split(' ')
media_query = media_query.filter(sql.not_(Media.slug.in_(ignore)))
# get the actual object (hope there is one!)
media = media_query.first()
return self._jsonify(media)
示例7: panda_update
def panda_update(self, media_id=None, file_id=None, video_id=None, **kwargs):
if file_id:
media_file = fetch_row(MediaFile, file_id)
media_files = [media_file]
elif media_id:
media = fetch_row(Media, media_id)
media_files = media.files
storage = DBSession.query(PandaStorage).first()
for media_file in media_files:
storage.panda_helper().video_status_update(media_file, video_id)
redirect(controller='/admin/media', action='edit', id=media_id)
示例8: view
def view(self, slug, page=1, show='latest', **kwargs):
"""View a podcast and the media that belongs to it.
:param slug: A :attr:`~mediacore.model.podcasts.Podcast.slug`
:param page: Page number, defaults to 1.
:type page: int
:rtype: dict
:returns:
podcast
A :class:`~mediacore.model.podcasts.Podcast` instance.
episodes
A list of :class:`~mediacore.model.media.Media` instances
that belong to the ``podcast``.
podcasts
A list of all the other podcasts
"""
podcast = fetch_row(Podcast, slug=slug)
episodes = podcast.media.published()
episodes, show = helpers.filter_library_controls(episodes, show)
return dict(
podcast = podcast,
episodes = episodes,
result_count = episodes.count(),
show = show,
)
示例9: edit
def edit(self, id, **kwargs):
"""Display the :class:`~mediacore.forms.users.UserForm` for editing or adding.
:param id: User ID
:type id: ``int`` or ``"new"``
:rtype: dict
:returns:
user
The :class:`~mediacore.model.auth.User` instance we're editing.
user_form
The :class:`~mediacore.forms.users.UserForm` instance.
user_action
``str`` form submit url
user_values
``dict`` form values
"""
user = fetch_row(User, id)
if tmpl_context.action == "save" or id == "new":
# Use the values from error_handler or GET for new users
user_values = kwargs
user_values["login_details.password"] = None
user_values["login_details.confirm_password"] = None
else:
user_values = dict(
display_name=user.display_name,
email_address=user.email_address,
login_details=dict(group=user.groups[0].group_id if user.groups else None, user_name=user.user_name),
)
return dict(user=user, user_form=user_form, user_action=url_for(action="save"), user_values=user_values)
示例10: edit
def edit(self, id, engine_type=None, **kwargs):
"""Display the :class:`~mediacore.lib.storage.StorageEngine` for editing or adding.
:param id: Storage ID
:type id: ``int`` or ``"new"``
:rtype: dict
:returns:
"""
if id != "new":
engine = fetch_row(StorageEngine, id)
else:
types = dict((cls.engine_type, cls) for cls in StorageEngine)
engine_cls = types.get(engine_type, None)
if not engine_cls:
redirect(controller="/admin/storage", action="index")
engine = engine_cls()
if not engine.settings_form:
# XXX: If this newly created storage engine has no settings,
# just save it. This isn't RESTful (as edit is a GET
# action), but it simplifies the creation process.
DBSession.add(engine)
redirect(controller="/admin/storage", action="index")
return {
"engine": engine,
"form": engine.settings_form,
"form_action": url_for(action="save", engine_type=engine_type),
"form_values": kwargs,
}
示例11: _import_video
def _import_video(self, entry):
player_url = self._player_url_from_entry(entry)
if not player_url:
log.debug('Video Feed Error: No player URL? %s' % entry)
return None
if self._has_media_file_for(player_url):
return None
media = fetch_row(Media, u'new')
media.author = Author(self.user.display_name, self.user.email_address)
media.reviewed = True
media.title = unicode(entry.media.title.text, "utf-8")
if entry.media.description.text:
encoded_description = unicode(entry.media.description.text, "utf-8")
media.description = clean_xhtml(encoded_description)
media.slug = get_available_slug(Media, media.title, media)
if self.tags:
media.set_tags(unicode(self.tags))
if self.categories:
media.set_categories(self.categories)
try:
media_file = add_new_media_file(media, url=player_url)
except StorageError, e:
log.debug('Video Feed Error: Error storing video: %s at %s' \
% (e.message, player_url))
return None
示例12: feed
def feed(self, slug, **kwargs):
"""Serve the feed as RSS 2.0.
If :attr:`~mediacore.model.podcasts.Podcast.feedburner_url` is
specified for this podcast, we redirect there if the useragent
does not contain 'feedburner', as described here:
http://www.google.com/support/feedburner/bin/answer.py?hl=en&answer=78464
:param feedburner_bypass: If true, the redirect to feedburner is disabled.
:rtype: Dict
:returns:
podcast
A :class:`~mediacore.model.podcasts.Podcast` instance.
episodes
A list of :class:`~mediacore.model.media.Media` instances
that belong to the ``podcast``.
Renders: :data:`podcasts/feed.xml` XML
"""
podcast = fetch_row(Podcast, slug=slug)
if (
podcast.feedburner_url
and not "feedburner" in request.environ.get("HTTP_USER_AGENT", "").lower()
and not kwargs.get("feedburner_bypass", False)
):
redirect(podcast.feedburner_url.encode("utf-8"))
response.content_type = content_type_for_response(["application/rss+xml", "application/xml", "text/xml"])
episodes = podcast.media.published().order_by(Media.publish_on.desc())[:25]
return dict(podcast=podcast, episodes=episodes)
示例13: edit
def edit(self, id, **kwargs):
"""Display the :class:`~mediacore.forms.admin.groups.GroupForm` for editing or adding.
:param id: Group ID
:type id: ``int`` or ``"new"``
:rtype: dict
:returns:
user
The :class:`~mediacore.model.auth.Group` instance we're editing.
user_form
The :class:`~mediacore.forms.admin.groups.GroupForm` instance.
user_action
``str`` form submit url
group_values
``dict`` form values
"""
group = fetch_row(Group, id)
if tmpl_context.action == 'save' or id == 'new':
# Use the values from error_handler or GET for new groups
group_values = kwargs
else:
group_values = dict(
display_name = group.display_name,
group_name = group.group_name,
)
return dict(
group = group,
group_form = group_form,
group_action = url_for(action='save'),
group_values = group_values,
)
示例14: serve
def serve(self, id, slug, container, **kwargs):
"""Serve a :class:`~mediacore.model.media.MediaFile` binary.
:param id: File ID
:type id: ``int``
:param slug: The media :attr:`~mediacore.model.media.Media.slug`
:type slug: The file :attr:`~mediacore.model.media.MediaFile.container`
:raises webob.exc.HTTPNotFound: If no file exists for the given params.
:raises webob.exc.HTTPNotAcceptable: If an Accept header field
is present, and if the mimetype of the requested file doesn't
match, then a 406 (not acceptable) response is returned.
"""
media = fetch_row(Media, slug=slug)
for file in media.files:
if file.id == id and file.container == container:
# Catch external redirects in case they aren't linked to directly
if file.url:
redirect(file.url.encode('utf-8'))
# Ensure that the clients request allows for files of this container
mimetype = mimeparse.best_match([file.mimetype],
request.environ.get('HTTP_ACCEPT', '*/*'))
if mimetype == '':
raise webob.exc.HTTPNotAcceptable() # 406
response.headers['Content-Type'] = mimetype
response.headers['Content-Disposition'] = \
'attachment;filename="%s"' % file.display_name.encode('utf-8')
return open(file.file_path, 'rb').read()
else:
raise webob.exc.HTTPNotFound()
示例15: comment
def comment(self, slug, name="", email=None, body="", **kwargs):
"""Post a comment from :class:`~mediacore.forms.comments.PostCommentForm`.
:param slug: The media :attr:`~mediacore.model.media.Media.slug`
:returns: Redirect to :meth:`view` page for media.
"""
def result(success, message=None, comment=None):
if request.is_xhr:
result = dict(success=success, message=message)
if comment:
result["comment"] = render("comments/_list.html", {"comment_to_render": comment}, method="xhtml")
return result
elif success:
return redirect(action="view")
else:
return self.view(slug, name=name, email=email, body=body, **kwargs)
akismet_key = request.settings["akismet_key"]
if akismet_key:
akismet = Akismet(agent=USER_AGENT)
akismet.key = akismet_key
akismet.blog_url = request.settings["akismet_url"] or url_for("/", qualified=True)
akismet.verify_key()
data = {
"comment_author": name.encode("utf-8"),
"user_ip": request.environ.get("REMOTE_ADDR"),
"user_agent": request.environ.get("HTTP_USER_AGENT", ""),
"referrer": request.environ.get("HTTP_REFERER", "unknown"),
"HTTP_ACCEPT": request.environ.get("HTTP_ACCEPT"),
}
if akismet.comment_check(body.encode("utf-8"), data):
return result(False, _(u"Your comment has been rejected."))
media = fetch_row(Media, slug=slug)
request.perm.assert_permission(u"view", media.resource)
c = Comment()
name = filter_vulgarity(name)
c.author = AuthorWithIP(name, email, request.environ["REMOTE_ADDR"])
c.subject = "Re: %s" % media.title
c.body = filter_vulgarity(body)
require_review = request.settings["req_comment_approval"]
if not require_review:
c.reviewed = True
c.publishable = True
media.comments.append(c)
DBSession.flush()
send_comment_notification(media, c)
if require_review:
message = _("Thank you for your comment! We will post it just as " "soon as a moderator approves it.")
return result(True, message=message)
else:
return result(True, comment=c)