本文整理汇总了Python中mediadrop.model.meta.DBSession.add方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.add方法的具体用法?Python DBSession.add怎么用?Python DBSession.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mediadrop.model.meta.DBSession
的用法示例。
在下文中一共展示了DBSession.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save
# 需要导入模块: from mediadrop.model.meta import DBSession [as 别名]
# 或者: from mediadrop.model.meta.DBSession import add [as 别名]
def save(self, id, delete=None, **kwargs):
"""Save changes or create a category.
See :class:`~mediadrop.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)
示例2: fetch_and_create_multi_setting
# 需要导入模块: from mediadrop.model.meta import DBSession [as 别名]
# 或者: from mediadrop.model.meta.DBSession import add [as 别名]
def fetch_and_create_multi_setting(key, value):
multisettings = MultiSetting.query.filter(MultiSetting.key == key).all()
for ms in multisettings:
if ms.value == value:
return ms
ms = MultiSetting(key, value)
DBSession.add(ms)
return ms
示例3: example
# 需要导入模块: from mediadrop.model.meta import DBSession [as 别名]
# 或者: from mediadrop.model.meta.DBSession import add [as 别名]
def example(cls, **kwargs):
defaults = dict(
name = u'baz_users',
display_name = u'Baz Users',
)
defaults.update(kwargs)
group = Group(**defaults)
DBSession.add(group)
DBSession.flush()
return group
示例4: save
# 需要导入模块: from mediadrop.model.meta import DBSession [as 别名]
# 或者: from mediadrop.model.meta.DBSession import add [as 别名]
def save(self, id, slug, title, author_name, author_email,
description, notes, podcast, tags, categories,
delete=None, **kwargs):
"""Save changes or create a new :class:`~mediadrop.model.media.Media` instance.
Form handler the :meth:`edit` action and the
:class:`~mediadrop.forms.admin.media.MediaForm`.
Redirects back to :meth:`edit` after successful editing
and :meth:`index` after successful deletion.
"""
media = fetch_row(Media, id)
if delete:
self._delete_media(media)
redirect(action='index', id=None)
if not slug:
slug = slugify(title)
elif slug.startswith('_stub_'):
slug = slug[len('_stub_'):]
if slug != media.slug:
media.slug = get_available_slug(Media, slug, media)
media.title = title
media.author = Author(author_name, author_email)
media.description = description
media.notes = notes
media.podcast_id = podcast
media.set_tags(tags)
media.set_categories(categories)
media.update_status()
DBSession.add(media)
DBSession.flush()
if id == 'new' and not has_thumbs(media):
create_default_thumbs_for(media)
if request.is_xhr:
status_form_xhtml = unicode(update_status_form.display(
action=url_for(action='update_status', id=media.id),
media=media))
return dict(
media_id = media.id,
values = {'slug': slug},
link = url_for(action='edit', id=media.id),
status_form = status_form_xhtml,
)
else:
redirect(action='edit', id=media.id)
示例5: example
# 需要导入模块: from mediadrop.model.meta import DBSession [as 别名]
# 或者: from mediadrop.model.meta.DBSession import add [as 别名]
def example(cls, **kwargs):
media = Media()
defaults = dict(
title=u'Foo Media',
author=Author(u'Joe', u'[email protected]'),
type = None,
)
defaults.update(kwargs)
defaults.setdefault('slug', get_available_slug(Media, defaults['title']))
for key, value in defaults.items():
assert hasattr(media, key)
setattr(media, key, value)
DBSession.add(media)
DBSession.flush()
return media
示例6: example
# 需要导入模块: from mediadrop.model.meta import DBSession [as 别名]
# 或者: from mediadrop.model.meta.DBSession import add [as 别名]
def example(cls, **kwargs):
category = Category()
defaults = dict(
name=u'Foo',
parent_id=0
)
defaults.update(kwargs)
defaults.setdefault('slug', get_available_slug(Category, defaults['name']))
for key, value in defaults.items():
assert hasattr(category, key)
setattr(category, key, value)
DBSession.add(category)
DBSession.flush()
return category
示例7: save_thumb
# 需要导入模块: from mediadrop.model.meta import DBSession [as 别名]
# 或者: from mediadrop.model.meta.DBSession import add [as 别名]
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
示例8: save_status
# 需要导入模块: from mediadrop.model.meta import DBSession [as 别名]
# 或者: from mediadrop.model.meta.DBSession import add [as 别名]
def save_status(self, id, status, ids=None, **kwargs):
"""Approve or delete a comment or comments.
:param id: A :attr:`~mediadrop.model.comments.Comment.id` if we are
acting on a single comment, or ``"bulk"`` if we should refer to
``ids``.
:type id: ``int`` or ``"bulk"``
:param status: ``"approve"`` or ``"trash"`` depending on what action
the user requests.
:param ids: An optional string of IDs separated by commas.
:type ids: ``unicode`` or ``None``
:rtype: JSON dict
:returns:
success
bool
ids
A list of :attr:`~mediadrop.model.comments.Comment.id`
that have changed.
"""
if id != 'bulk':
ids = [id]
if not isinstance(ids, list):
ids = [ids]
if status == 'approve':
publishable = True
elif status == 'trash':
publishable = False
else:
# XXX: This form should never be submitted without a valid status.
raise AssertionError('Unexpected status: %r' % status)
comments = Comment.query.filter(Comment.id.in_(ids)).all()
for comment in comments:
comment.reviewed = True
comment.publishable = publishable
DBSession.add(comment)
DBSession.flush()
if request.is_xhr:
return dict(success=True, ids=ids)
else:
redirect(action='index')
示例9: popularity_save
# 需要导入模块: from mediadrop.model.meta import DBSession [as 别名]
# 或者: from mediadrop.model.meta.DBSession import add [as 别名]
def popularity_save(self, **kwargs):
"""Save :class:`~mediadrop.forms.admin.settings.PopularityForm`.
Updates the popularity for every media item based on the submitted
values.
"""
self._save(popularity_form, values=kwargs)
# ".util.calculate_popularity()" uses the popularity settings from
# the request.settings which are only updated when a new request
# comes in.
# update the settings manually so the popularity is actually updated
# correctly.
for key in ('popularity_decay_exponent', 'popularity_decay_lifetime'):
request.settings[key] = kwargs['popularity.'+key]
for m in Media.query:
m.update_popularity()
DBSession.add(m)
redirect(action='popularity')
示例10: save_edit
# 需要导入模块: from mediadrop.model.meta import DBSession [as 别名]
# 或者: from mediadrop.model.meta.DBSession import add [as 别名]
def save_edit(self, id, body, **kwargs):
"""Save an edit from :class:`~mediadrop.forms.admin.comments.EditCommentForm`.
:param id: Comment ID
:type id: ``int``
:rtype: JSON dict
:returns:
success
bool
body
The edited comment body after validation/filtering
"""
comment = fetch_row(Comment, id)
comment.body = body
DBSession.add(comment)
return dict(
success = True,
body = comment.body,
)
示例11: save
# 需要导入模块: from mediadrop.model.meta import DBSession [as 别名]
# 或者: from mediadrop.model.meta.DBSession import add [as 别名]
def save(self, id, delete=False, **kwargs):
"""Save changes or create a tag.
See :class:`~mediadrop.forms.admin.settings.tags.TagForm` for POST vars.
:param id: Tag ID
: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')
tag = fetch_row(Tag, id)
if delete:
DBSession.delete(tag)
data = dict(success=True, id=tag.id)
else:
tag.name = kwargs['name']
tag.slug = get_available_slug(Tag, kwargs['slug'], tag)
DBSession.add(tag)
DBSession.flush()
data = dict(
success = True,
id = tag.id,
name = tag.name,
slug = tag.slug,
row = unicode(tag_row_form.display(tag=tag)),
)
if request.is_xhr:
return data
else:
redirect(action='index', id=None)
示例12: save
# 需要导入模块: from mediadrop.model.meta import DBSession [as 别名]
# 或者: from mediadrop.model.meta.DBSession import add [as 别名]
def save(self, id, email_address, display_name, login_details,
delete=None, **kwargs):
"""Save changes or create a new :class:`~mediadrop.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['groups']:
query = DBSession.query(Group).filter(Group.group_id.in_(login_details['groups']))
user.groups = list(query.all())
else:
user.groups = []
DBSession.add(user)
# Check if we're changing the logged in user's own password
if user.id == request.perm.user.id \
and password is not None and password != '':
DBSession.commit()
# repoze.who sees the Unauthorized response and clears the cookie,
# forcing a fresh login with the new password
raise webob.exc.HTTPUnauthorized().exception
redirect(action='index', id=None)
示例13: save
# 需要导入模块: from mediadrop.model.meta import DBSession [as 别名]
# 或者: from mediadrop.model.meta.DBSession import add [as 别名]
def save(
self, id, slug, title, subtitle, author_name, author_email, description, details, feed, delete=None, **kwargs
):
"""Save changes or create a new :class:`~mediadrop.model.podcasts.Podcast` instance.
Form handler the :meth:`edit` action and the
:class:`~mediadrop.forms.admin.podcasts.PodcastForm`.
Redirects back to :meth:`edit` after successful editing
and :meth:`index` after successful deletion.
"""
podcast = fetch_row(Podcast, id)
if delete:
DBSession.delete(podcast)
DBSession.commit()
delete_thumbs(podcast)
redirect(action="index", id=None)
if not slug:
slug = title
if slug != podcast.slug:
podcast.slug = get_available_slug(Podcast, slug, podcast)
podcast.title = title
podcast.subtitle = subtitle
podcast.author = Author(author_name, author_email)
podcast.description = description
podcast.copyright = details["copyright"]
podcast.category = details["category"]
podcast.itunes_url = feed["itunes_url"]
podcast.feedburner_url = feed["feedburner_url"]
podcast.explicit = {"yes": True, "clean": False}.get(details["explicit"], None)
if id == "new":
DBSession.add(podcast)
DBSession.flush()
create_default_thumbs_for(podcast)
redirect(action="edit", id=podcast.id)
示例14: insert_settings
# 需要导入模块: from mediadrop.model.meta import DBSession [as 别名]
# 或者: from mediadrop.model.meta.DBSession import add [as 别名]
def insert_settings(defaults):
"""Insert the given setting if they don't exist yet.
XXX: Does not include any support for MultiSetting. This approach
won't work for that. We'll need to use a migration script.
:type defaults: list
:param defaults: Key and value pairs
:rtype: list
:returns: Any settings that have just been created.
"""
inserted = []
try:
settings_query = DBSession.query(Setting.key)\
.filter(Setting.key.in_([key for key, value in defaults]))
existing_settings = set(x[0] for x in settings_query)
except ProgrammingError:
# If we are running paster setup-app on a fresh database with a
# plugin which tries to use this function every time the
# Environment.loaded event fires, the settings table will not
# exist and this exception will be thrown, but its safe to ignore.
# The settings will be created the next time the event fires,
# which will likely be the first time the app server starts up.
return inserted
for key, value in defaults:
if key in existing_settings:
continue
transaction = DBSession.begin_nested()
try:
s = Setting(key, value)
DBSession.add(s)
transaction.commit()
inserted.append(s)
except IntegrityError:
transaction.rollback()
if inserted:
DBSession.commit()
return inserted
示例15: save
# 需要导入模块: from mediadrop.model.meta import DBSession [as 别名]
# 或者: from mediadrop.model.meta.DBSession import add [as 别名]
def save(self, id, display_name, group_name, permissions, delete=None, **kwargs):
"""Save changes or create a new :class:`~mediadrop.model.auth.Group` instance.
:param id: Group ID. If ``"new"`` a new group is created.
:type id: ``int`` or ``"new"``
:returns: Redirect back to :meth:`index` after successful save.
"""
group = fetch_row(Group, id)
if delete:
DBSession.delete(group)
redirect(action='index', id=None)
group.display_name = display_name
group.group_name = group_name
if permissions:
query = DBSession.query(Permission).filter(Permission.permission_id.in_(permissions))
group.permissions = list(query.all())
else:
group.permissions = []
DBSession.add(group)
redirect(action='index', id=None)