本文整理汇总了Python中mediacore.model.meta.DBSession.add方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.add方法的具体用法?Python DBSession.add怎么用?Python DBSession.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mediacore.model.meta.DBSession
的用法示例。
在下文中一共展示了DBSession.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: attach_and_store_media_file
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import add [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
示例2: _update_settings
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import add [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
示例3: _add_new_media_file
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import add [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
示例4: save
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.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:`~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)
示例5: insert_settings
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.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 sqlalchemy-migrate.
:type defaults: list
:param defaults: Key and value pairs
:rtype: list
:returns: Any settings that have just been created.
"""
inserted = []
existing_settings = set(x[0] for x in DBSession.query(Setting.key) \
.filter(Setting.key \
.in_(key for key, value in defaults)))
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
示例6: save
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import add [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)
示例7: podcast_from_feed
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import add [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
示例8: prepareForUpload
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import add [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,
),
),
}
示例9: example
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.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
示例10: fetch_and_create_multi_setting
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.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
示例11: import_videos_from_feed
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import add [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 add [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_settings
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import add [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()
示例14: popularity_save
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import add [as 别名]
def popularity_save(self, **kwargs):
"""Save :class:`~mediacore.forms.admin.settings.PopularityForm`.
Updates the popularity for every media item based on the submitted
values.
"""
self._save(popularity_form, values=kwargs)
for m in Media.query:
m.update_popularity()
DBSession.add(m)
redirect(action='popularity')
示例15: example
# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.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=VIDEO)
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