本文整理汇总了Python中mediacore.model.meta.DBSession.flush方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.flush方法的具体用法?Python DBSession.flush怎么用?Python DBSession.flush使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mediacore.model.meta.DBSession
的用法示例。
在下文中一共展示了DBSession.flush方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: fetch_and_create_tags
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import flush [as 别名]
def fetch_and_create_tags(tag_names):
# copy the tag_names list
new_tag_names = tag_names[:]
# find tag names that already exist (case insensitive match)
# and remove those names from our list
lower_case_tags = [t.lower() for t in new_tag_names]
existing_tags = DBSession.query(Tag).\
filter(
func.lower(Tag.name).in_(lower_case_tags)
).all()
for t in existing_tags:
for n in new_tag_names[:]:
if n.lower() == t.name.lower():
new_tag_names.remove(n)
break
# create the tags that don't yet exist
if new_tag_names:
new_tags = [{'name': n, 'slug': slugify(n)} for n in new_tag_names]
DBSession.connection().execute(tags.insert(), new_tags)
DBSession.flush()
existing_tags += DBSession.query(Tag)\
.filter(
Tag.slug.in_([t['slug'] for t in new_tags])
).all()
return existing_tags
示例2: test_metagroup_assignment_does_not_fail_if_groups_are_not_found_in_db
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import flush [as 别名]
def test_metagroup_assignment_does_not_fail_if_groups_are_not_found_in_db(self):
DBSession.delete(self.anonymous)
DBSession.delete(self.authenticated)
DBSession.flush()
user = User.example()
self.assert_user_groups([], user)
示例3: save
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import flush [as 别名]
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)
示例4: _add_new_media_file
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import flush [as 别名]
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
示例5: attach_and_store_media_file
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import flush [as 别名]
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
示例6: _update_settings
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import flush [as 别名]
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
示例7: save
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import flush [as 别名]
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)
示例8: podcast_from_feed
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import flush [as 别名]
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
示例9: prepareForUpload
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import flush [as 别名]
def prepareForUpload(self, environ, media_id, content_type, filename, filesize, meta=None, **kwargs):
STORAGE_ENGINE = getStorageEngine()
log.info("{self}.prepareForUpload({media_id},{content_type},{filename},{filesize})".format(**vars()))
if not meta:
meta = {}
else:
try:
meta = json.loads(meta)
except Exception as e:
return {"success": False, "message": "Invalid JSON object given for `meta`"}
media = fetch_row(Media, media_id)
mediaFile = MediaFile()
mediaFile.storage = STORAGE_ENGINE
mediaFile.media = media
mediaFile.media_id = media_id
mediaFile.type = content_type
mediaFile.meta = meta
media.type = content_type
mediaFile.display_name = filename
mediaFile.size = filesize
media.files.append(mediaFile)
DBSession.add(media)
DBSession.add(mediaFile)
DBSession.flush()
# This is to ensure that we don't allow any uploads that haven't been prepared for with prepareForUpload
token = "".join(random.choice(string.ascii_uppercase + string.digits) for x in range(13))
upload_tokens[str(mediaFile.id)] = token
return {
"success": True,
"id": mediaFile.id,
"upload_url": "http://{host}{path}".format(
host=environ["HTTP_HOST"],
path=url_for(
controller="upload_api/api/uploader", action="uploadFile", media_id=media_id, file_id=mediaFile.id
),
),
"upload_headers": {
"Content-Type": "application/octet-stream",
"Cache-Control": "none",
"X-File-Name": filename,
"X-Upload-Token": token,
},
"postprocess_url": "http://{host}{path}".format(
host=environ["HTTP_HOST"],
path=url_for(
controller="upload_api/api/uploader",
action="postprocessFile",
media_id=media_id,
file_id=mediaFile.id,
),
),
}
示例10: example
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import flush [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
示例11: import_videos_from_feed
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import flush [as 别名]
def import_videos_from_feed(self, feed):
for entry in feed.entry:
youtube_id = self.id_for_entry(entry)
if not self._should_import_video(youtube_id):
continue
media = self._import_video(entry)
self._video_notifcation(youtube_id)
if media:
DBSession.add(media)
DBSession.flush()
示例12: save_thumb
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import flush [as 别名]
def save_thumb(self, id, thumb, **kwargs):
"""Save a thumbnail uploaded with :class:`~mediacore.forms.admin.ThumbForm`.
:param id: Media ID. If ``"new"`` a new Media stub is created with
:func:`~mediacore.model.media.create_media_stub`.
: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:`~mediacore.model.media.Media.id` which is
important if a new media has just been created.
"""
if id == 'new':
media = create_media_stub()
else:
media = fetch_row(Media, id)
try:
# Create thumbs
img = Image.open(thumb.file)
if id == 'new':
DBSession.add(media)
DBSession.flush()
# TODO: Allow other formats?
for key, xy in config['thumb_sizes'][media._thumb_dir].iteritems():
thumb_path = helpers.thumb_path(media, key)
thumb_img = helpers.resize_thumb(img, xy)
thumb_img.save(thumb_path)
# Backup the original image just for kicks
backup_type = os.path.splitext(thumb.filename)[1].lower()[1:]
backup_path = helpers.thumb_path(media, 'orig', ext=backup_type)
backup_file = open(backup_path, 'w+b')
thumb.file.seek(0)
shutil.copyfileobj(thumb.file, backup_file)
thumb.file.close()
backup_file.close()
success = True
message = None
except IOError:
success = False
message = 'Unsupported image type'
except Exception, e:
success = False
message = e.message
示例13: update_status
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import flush [as 别名]
def update_status(self, id, update_button=None, publish_on=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:`~mediacore.model.media.Media.status` should change.
:type update_status: ``unicode`` or ``None``
:param publish_on: A date to set to
:attr:`~mediacore.model.media.Media.publish_on`
:type publish_on: :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 update_button == _('Review Complete'):
media.reviewed = True
elif update_button == _('Publish Now'):
media.publishable = True
media.publish_on = publish_on or datetime.now()
media.update_popularity()
# Remove the stub prefix if the user wants the default media title
if media.slug.startswith('_stub_'):
new_slug = get_available_slug(Media, media.slug[len('_stub_'):])
media.slug = new_slug
elif publish_on:
media.publish_on = publish_on
media.update_popularity()
# 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')
示例14: fetch_and_create_tags
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import flush [as 别名]
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
"""
results = TagList()
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
示例15: _update_settings
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import flush [as 别名]
def _update_settings(self, values):
"""Modify the settings associated with the given dictionary."""
for name, value in values.iteritems():
if value is None:
value = u''
else:
value = unicode(value)
if self.settings[name].value != value:
self.settings[name].value = value
DBSession.add(self.settings[name])
DBSession.flush()