本文整理汇总了Python中mediacore.model.meta.DBSession类的典型用法代码示例。如果您正苦于以下问题:Python DBSession类的具体用法?Python DBSession怎么用?Python DBSession使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DBSession类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: init_model
def init_model(engine):
"""Call me before using any of the tables or classes in the model."""
DBSession.configure(bind=engine)
from mediacore.model import meta
meta.metadata.bind = engine
meta.engine = engine
示例2: _update_settings
def _update_settings(self, values):
"""Modify the settings associated with the given dictionary."""
for name, value in values.iteritems():
setting = tmpl_context.settings[name]
if value is None:
value = u''
else:
value = unicode(value)
if setting.value != value:
setting.value = value
DBSession.add(setting)
DBSession.flush()
# Clear the settings cache unless there are multiple processes.
# We have no way of notifying the other processes that they need
# to clear their caches too, so we've just gotta let it play out
# until all the caches expire.
if not request.environ.get('wsgi.multiprocess', False):
app_globals.settings_cache.clear()
else:
# uWSGI provides an automagically included module
# that we can use to call a graceful restart of all
# the uwsgi processes.
# http://projects.unbit.it/uwsgi/wiki/uWSGIReload
try:
import uwsgi
uwsgi.reload()
except ImportError:
pass
示例3: 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()),
)
示例4: increment_views
def increment_views(self):
"""Increment the number of views in the database.
We avoid concurrency issues by incrementing JUST the views and
not allowing modified_on to be updated automatically.
"""
if self.id is None:
self.views += 1
return self.views
# Don't raise an exception should concurrency problems occur.
# Views will not actually be incremented in this case, but thats
# relatively unimportant compared to rendering the page for the user.
# We may be able to remove this after we improve our triggers to not
# issue an UPDATE on media_fulltext unless one of its columns are
# actually changed. Even when just media.views is updated, all the
# columns in the corresponding media_fulltext row are updated, and
# media_fulltext's MyISAM engine must lock the whole table to do so.
transaction = DBSession.begin_nested()
try:
DBSession.query(self.__class__)\
.filter(self.__class__.id == self.id)\
.update({self.__class__.views: self.__class__.views + 1})
transaction.commit()
except exc.OperationalError, e:
transaction.rollback()
# (OperationalError) (1205, 'Lock wait timeout exceeded, try restarting the transaction')
if not '1205' in e.message:
raise
示例5: _add_new_media_file
def _add_new_media_file(media, original_filename, file):
# FIXME: I think this will raise a KeyError if the uploaded
# file doesn't have an extension.
file_ext = os.path.splitext(original_filename)[1].lower()[1:]
# set the file paths depending on the file type
media_file = MediaFile()
media_file.display_name = original_filename
media_file.container = guess_container_format(file_ext)
media_file.type = guess_media_type(media_file.container)
# Small files are stored in memory and do not have a tmp file w/ fileno
if hasattr(file, 'fileno'):
media_file.size = os.fstat(file.fileno())[6]
else:
# The file may contain multi-byte characters, so we must seek instead of count chars
file.seek(0, os.SEEK_END)
media_file.size = file.tell()
file.seek(0)
# update media relations
media.files.append(media_file)
# add the media file (and its media, if new) to the database to get IDs
DBSession.add(media_file)
DBSession.flush()
# copy the file to its permanent location
file_name = '%d_%d_%s.%s' % (media.id, media_file.id, media.slug, file_ext)
file_url = _store_media_file(file, file_name)
media_file.file_name = file_name
return media_file
示例6: save_fields
def save_fields(**result):
"""Save SEO settings to the database on a Media item save.
When the :attr:`mediacore.plugin.events.Admin.MediaController.save`
event is triggered it receives the dict of values returned by
:meth:`mediacore.controllers.admin.media.MediaController.save`.
The SEO values are extracted from tmpl_context.form_values and if
a value was entered it is saved. If a valid setting was found, but
it does not have a value, we remove it form the given media item.
:param result: A dict of form values for the Media item
:param type: dict
:returns: A dict of form values for the Media item
:rtpye: dict
"""
media = Media.query.get(result['media_id'])
for key, value in tmpl_context.form_values['seo'].iteritems():
meta_key = u'seo_%s' % key
if value:
media.meta[meta_key] = value
elif meta_key in media.meta:
DBSession.delete(media._meta[meta_key])
return result
示例7: attach_and_store_media_file
def attach_and_store_media_file(media, media_file, file):
"""Given a Media object, a MediaFile object, and a file handle,
attaches the MediaFile to the Media object, and saves the file to permanent
storage.
Adds the MediaFile to the database.
"""
# Small files are stored in memory and do not have a tmp file w/ fileno
if hasattr(file, 'fileno'):
media_file.size = os.fstat(file.fileno())[6]
else:
# The file may contain multi-byte characters, so we must seek instead of count chars
file.seek(0, os.SEEK_END)
media_file.size = file.tell()
file.seek(0)
# update media relations
media.files.append(media_file)
# add the media file (and its media, if new) to the database to get IDs
DBSession.add(media_file)
DBSession.flush()
# copy the file to its permanent location
file_name = '%d_%d_%s.%s' % (media.id, media_file.id, media.slug, media_file.container)
file_url = store_media_file(file, file_name)
if file_url:
# The file has been stored remotely
media_file.url = file_url
else:
# The file is stored locally and we just need its name
media_file.file_name = file_name
示例8: restore_necessary_files
def restore_necessary_files():
# Restore the appropriate media files and thumbnail files
# for any media currently in the database.
# Use the python models to do this.
if not deleted_dir:
return
filename_pairs = []
for media in DBSession.query(Media).all():
for thumb in thumb_paths(media).values():
filename_pairs.append((
thumb.replace(m_img_dir, m_deleted_dir),
thumb
))
for file in media.files:
if file.file_path:
filename_pairs.append((
file.file_path.replace(media_dir, m_deleted_dir),
file.file_path
))
for podcast in DBSession.query(Podcast).all():
for thumb in thumb_paths(podcast).values():
filename_pairs.append((
thumb.replace(p_img_dir, p_deleted_dir),
thumb
))
for src, dest in filename_pairs:
if os.path.exists(src):
if DEBUG:
print "Moving %s to %s" % (src, dest)
shutil.move(src, dest)
示例9: _autocommit_commit
def _autocommit_commit(req):
try:
DBSession.commit()
except:
_autocommit_rollback(req)
raise
else:
_autocommit_fire_callbacks(req, req.commit_callbacks)
示例10: backup_files
def backup_files(dump_dir):
# Backup all files (media files, thumbs) referenced by an object in the DB
# to the provided dump_dir.
# TODO: display errors when file operations fail
if dump_dir == "/":
return 1, "Dump Files directory should never be the root directory, '/'"
# normalize dirname
dump_dir = dump_dir.rstrip(os.sep) + os.sep
# These are the directories we will write to.
media_thumb_dir = dump_dir + Media._thumb_dir
podcast_thumb_dir = dump_dir + Podcast._thumb_dir
media_files_dir = dump_dir + "media_files"
# Initialize our default paths to backup
default_images = ["news.jpg", "newm.jpg", "newl.jpg"]
media_thumbs = [m_img_dir + os.sep + img for img in default_images]
podcast_thumbs = [p_img_dir + os.sep + img for img in default_images]
media_files = []
# Add the media thumbs and media files
for media in DBSession.query(Media).all():
file_paths = [file_path(f) for f in media.files]
media_files += [fp for fp in file_paths if fp]
media_thumbs += thumb_paths(media).values()
# Add the podcast thumbs
for podcast in DBSession.query(Podcast).all():
podcast_thumbs += thumb_paths(podcast).values()
# Ensure the necessary directories exist.
assert os.path.isdir(dump_dir)
for subdir in (media_thumb_dir, media_files_dir, podcast_thumb_dir):
if not os.path.exists(subdir):
os.mkdir(subdir)
assert os.path.isdir(subdir)
empty_dir(subdir)
# Copy over all of the files:
sources_dests = (
(media_thumbs, media_thumb_dir),
(media_files, media_files_dir),
(podcast_thumbs, podcast_thumb_dir),
)
for sources, dest_dir in sources_dests:
for src in sources:
if DEBUG:
print "Copying %s to %s%s" % (src, dest_dir, os.sep)
shutil.copy2(src, dest_dir)
return (
0,
"%d thumbnails and %d media files successfully backed up"
% (len(media_thumbs) + len(podcast_thumbs), len(media_files)),
)
示例11: _autocommit_commit
def _autocommit_commit(req):
from mediacore.model.meta import DBSession
try:
DBSession.commit()
except:
_autocommit_rollback(req)
raise
else:
_autocommit_fire_callbacks(req, req.commit_callbacks)
示例12: 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)
示例13: disassociate_video_id
def disassociate_video_id(self, media_file, video_id):
# Create a meta_key for this MediaCore::MediaFile -> Panda::Video pairing.
# This is sort of a perversion of the meta table, but hey, it works.
meta_key = u"%s%s" % (META_VIDEO_PREFIX, video_id)
mfm = DBSession.query(MediaFilesMeta)\
.filter(MediaFilesMeta.media_files_id==media_file.id)\
.filter(MediaFilesMeta.key==meta_key)
for x in mfm:
DBSession.delete(x)
示例14: podcast_from_feed
def podcast_from_feed(d, tags=False, save_files=False):
# Assume not explicit
explicit = False
if 'itunes_explicit' in d['feed']:
explicit = bool(d['feed']['itunes_explicit'])
image = None
if 'image' in d['feed']:
image = d['feed']['image']['href']
title = u''
if 'title' in d['feed']:
title = d['feed']['title']
description = u''
if 'summary' in d['feed']:
description = d['feed']['summary']
subtitle = u''
if 'subtitle' in d['feed']:
subtitle = d['feed']['subtitle']
slug = slugify(title)
author_name = u"PLACEHOLDER NAME"
author_email = u"[email protected]"
podcast = Podcast()
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.explicit = explicit
DBSession.add(podcast)
DBSession.flush()
# Create thumbs from image, or default thumbs
created_images = False
if image:
temp_imagefile = tempfile.TemporaryFile()
imagefile = urllib2.urlopen(image)
temp_imagefile.write(imagefile.read())
temp_imagefile.seek(0)
filename = urlparse.urlparse(image)[2]
create_thumbs_for(podcast, temp_imagefile, filename)
created_images = True
if not created_images:
create_default_thumbs_for(podcast)
# Now add all of the entries
for entry in d['entries']:
media = media_from_entry(entry, tags, save_files)
media.podcast = podcast
return podcast
示例15: 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