本文整理汇总了Python中mediadrop.model.meta.DBSession类的典型用法代码示例。如果您正苦于以下问题:Python DBSession类的具体用法?Python DBSession怎么用?Python DBSession使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DBSession类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: bulk
def bulk(self, type=None, ids=None, **kwargs):
"""Perform bulk operations on media items
:param type: The type of bulk action to perform (delete)
:param ids: A list of IDs.
"""
if not ids:
ids = []
elif not isinstance(ids, list):
ids = [ids]
if type == 'delete':
Category.query.filter(Category.id.in_(ids)).delete(False)
DBSession.commit()
success = True
else:
success = False
return dict(
success = success,
ids = ids,
parent_options = unicode(category_form.c['parent_id'].display()),
)
示例2: fetch_and_create_multi_setting
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: setUp
def setUp(self):
super(DBTestCase, self).setUp()
self.env_dir = self._create_environment_folders()
self.pylons_config = setup_environment_and_database(self.env_dir,
enabled_plugins=self.enabled_plugins)
add_default_data()
DBSession.commit()
config.push_process_config(self.pylons_config)
示例4: _autocommit_commit
def _autocommit_commit(req):
from mediadrop.model.meta import DBSession
try:
DBSession.commit()
except:
_autocommit_rollback(req)
raise
else:
_autocommit_fire_callbacks(req, req.commit_callbacks)
示例5: example
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
示例6: update_status
def update_status(self, id, status=None, publish_on=None, publish_until=None, **values):
"""Update the publish status for the given media.
:param id: Media ID
:type id: ``int``
:param update_status: The text of the submit button which indicates
that the :attr:`~mediadrop.model.media.Media.status` should change.
:type update_status: ``unicode`` or ``None``
:param publish_on: A date to set to
:attr:`~mediadrop.model.media.Media.publish_on`
:type publish_on: :class:`datetime.datetime` or ``None``
:param publish_until: A date to set to
:attr:`~mediadrop.model.media.Media.publish_until`
:type publish_until: :class:`datetime.datetime` or ``None``
: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)
new_slug = None
# Make the requested change assuming it will be allowed
if status == 'unreviewed':
media.reviewed = True
elif status == 'draft':
self._publish_media(media, publish_on)
elif publish_on:
media.publish_on = publish_on
media.update_popularity()
elif publish_until:
media.publish_until = publish_until
# Verify the change is valid by re-determining the status
media.update_status()
DBSession.flush()
if request.is_xhr:
# Return the rendered widget for injection
status_form_xhtml = unicode(update_status_form.display(
action=url_for(action='update_status'), media=media))
return dict(
success = True,
status_form = status_form_xhtml,
slug = new_slug,
)
else:
redirect(action='edit')
示例7: fetch_and_create_tags
def fetch_and_create_tags(tag_names):
"""Return a list of Tag instances that match the given names.
Tag names that don't yet exist are created automatically and
returned alongside the results that did already exist.
If you try to create a new tag that would have the same slug
as an already existing tag, the existing tag is used instead.
:param tag_names: The display :attr:`Tag.name`
:type tag_names: list
:returns: A list of :class:`Tag` instances.
:rtype: :class:`TagList` instance
"""
lower_names = [name.lower() for name in tag_names]
slugs = [slugify(name) for name in lower_names]
# Grab all the tags that exist already, whether its the name or slug
# that matches. Slugs can be changed by the tag settings UI so we can't
# rely on each tag name evaluating to the same slug every time.
results = Tag.query.filter(sql.or_(func.lower(Tag.name).in_(lower_names),
Tag.slug.in_(slugs))).all()
# Filter out any tag names that already exist (case insensitive), and
# any tag names evaluate to slugs that already exist.
for tag in results:
# Remove the match from our three lists until its completely gone
while True:
try:
try:
index = slugs.index(tag.slug)
except ValueError:
index = lower_names.index(tag.name.lower())
tag_names.pop(index)
lower_names.pop(index)
slugs.pop(index)
except ValueError:
break
# Any remaining tag names need to be created.
if tag_names:
# We may still have multiple tag names which evaluate to the same slug.
# Load it into a dict so that duplicates are overwritten.
uniques = dict((slug, name) for slug, name in izip(slugs, tag_names))
# Do a bulk insert to create the tag rows.
new_tags = [{'name': n, 'slug': s} for s, n in uniques.iteritems()]
DBSession.execute(tags.insert(), new_tags)
DBSession.flush()
# Query for our newly created rows and append them to our result set.
results += Tag.query.filter(Tag.slug.in_(uniques.keys())).all()
return results
示例8: save
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)
示例9: delete
def delete(self, id, **kwargs):
"""Delete a user.
:param id: User ID.
:type id: ``int``
:returns: Redirect back to :meth:`index` after successful delete.
"""
user = fetch_row(User, id)
DBSession.delete(user)
if request.is_xhr:
return dict(success=True)
redirect(action='index', id=None)
示例10: init_model
def init_model(engine, table_prefix=None):
"""Call me before using any of the tables or classes in the model."""
DBSession.configure(bind=engine)
from mediadrop.model import meta
meta.metadata.bind = engine
meta.engine = engine
# Change all table names to include the given prefix. This can't be
# easily done before the models are added to the metadata because
# that happens on import, before the config is available.
if table_prefix:
table_prefix = table_prefix.rstrip('_') + '_'
for table in meta.metadata.sorted_tables:
table.name = table_prefix + table.name
示例11: delete
def delete(self, id, **kwargs):
"""Delete a group.
:param id: Group ID.
:type id: ``int``
:returns: Redirect back to :meth:`index` after successful delete.
"""
group = fetch_row(Group, id)
DBSession.delete(group)
if request.is_xhr:
return dict(success=True)
redirect(action='index', id=None)
示例12: cleanup_players_table
def cleanup_players_table(enabled=False):
"""
Ensure that all available players are added to the database
and that players are prioritized in incrementally increasing order.
:param enabled: Should the default players be enabled upon creation?
:type enabled: bool
"""
from mediadrop.lib.players import (BlipTVFlashPlayer,
DailyMotionEmbedPlayer, GoogleVideoFlashPlayer, JWPlayer,
VimeoUniversalEmbedPlayer, YoutubePlayer)
# When adding players, prefer them in the following order:
default_players = [
JWPlayer,
YoutubePlayer,
VimeoUniversalEmbedPlayer,
GoogleVideoFlashPlayer,
BlipTVFlashPlayer,
DailyMotionEmbedPlayer,
]
unordered_players = [p for p in AbstractPlayer if p not in default_players]
all_players = default_players + unordered_players
# fetch the players that are already in the database
s = players.select().order_by('priority')
existing_players_query = DBSession.execute(s)
existing_player_rows = [p for p in existing_players_query]
existing_player_names = [p['name'] for p in existing_player_rows]
# Ensure all priorities are monotonically increasing from 1..n
priority = 0
for player_row in existing_player_rows:
priority += 1
if player_row['priority'] != priority:
u = players.update()\
.where(players.c.id == player_row['id'])\
.values(priority=priority)
DBSession.execute(u)
# Ensure that all available players are in the database
for player_cls in all_players:
if player_cls.name not in existing_player_names:
enable_player = enabled and player_cls in default_players
priority += 1
DBSession.execute(players.insert().values(
name=player_cls.name,
enabled=enable_player,
data=player_cls.default_data,
priority=priority,
))
示例13: example
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
示例14: example
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
示例15: get_available_slug
def get_available_slug(mapped_class, string, ignore=None, slug_attr='slug', slug_length=SLUG_LENGTH):
"""Return a unique slug based on the provided string.
Works by appending an int in sequence starting with 2:
1. awesome-stuff
2. awesome-stuff-2
3. awesome-stuff-3
:param mapped_class: The ORM-controlled model that the slug is for
:param string: A title, name, etc
:type string: unicode
:param ignore: A record which doesn't count as a collision
:type ignore: Int ID, ``mapped_class`` instance or None
:returns: A unique slug
:rtype: unicode
"""
if isinstance(ignore, mapped_class):
ignore = ignore.id
elif ignore is not None:
ignore = int(ignore)
new_slug = slug = slugify(string)
appendix = 2
while DBSession.query(mapped_class.id)\
.filter(getattr(mapped_class, slug_attr) == new_slug)\
.filter(mapped_class.id != ignore)\
.first():
str_appendix = u'-%s' % appendix
max_substr_len = slug_length - len(str_appendix)
new_slug = slug[:max_substr_len] + str_appendix
appendix += 1
return new_slug