本文整理汇总了Python中mediacore.model.DBSession.add方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.add方法的具体用法?Python DBSession.add怎么用?Python DBSession.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mediacore.model.DBSession
的用法示例。
在下文中一共展示了DBSession.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save
# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import add [as 别名]
def save(self, id, delete, category='topics', **kwargs):
"""Save changes or create a topic or tag.
See :class:`~mediacore.forms.categories.EditCategoryForm` for POST vars.
:param id: Topic or tag ID
:param category: ``topics`` or ``tags``
:param delete: If true the category is deleted rather than saved.
:type delete: bool
:rtype: JSON dict
:returns:
success
bool
category
``topics`` or ``tags``
"""
model = self.select_model(category)
item = fetch_row(model, id)
if delete:
DBSession.delete(item)
item = None
else:
item.name = kwargs['name']
item.slug = get_available_slug(model, kwargs['slug'], item)
DBSession.add(item)
if request.is_xhr:
return dict(success=True, category=item)
else:
redirect(action='index', category=category)
示例2: edit
# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import add [as 别名]
def edit(self, id, engine_type=None, **kwargs):
"""Display the :class:`~mediacore.lib.storage.StorageEngine` for editing or adding.
:param id: Storage ID
:type id: ``int`` or ``"new"``
:rtype: dict
:returns:
"""
if id != "new":
engine = fetch_row(StorageEngine, id)
else:
types = dict((cls.engine_type, cls) for cls in StorageEngine)
engine_cls = types.get(engine_type, None)
if not engine_cls:
redirect(controller="/admin/storage", action="index")
engine = engine_cls()
if not engine.settings_form:
# XXX: If this newly created storage engine has no settings,
# just save it. This isn't RESTful (as edit is a GET
# action), but it simplifies the creation process.
DBSession.add(engine)
redirect(controller="/admin/storage", action="index")
return {
"engine": engine,
"form": engine.settings_form,
"form_action": url_for(action="save", engine_type=engine_type),
"form_values": kwargs,
}
示例3: save_media_obj
# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import add [as 别名]
def save_media_obj(self, name, email, title, description, tags, uploaded_file, url):
# create our media object as a status-less placeholder initially
media_obj = Media()
media_obj.author = Author(name, email)
media_obj.title = title
media_obj.slug = get_available_slug(Media, title)
media_obj.description = description
if request.settings['wording_display_administrative_notes']:
media_obj.notes = request.settings['wording_administrative_notes']
media_obj.set_tags(tags)
# Give the Media object an ID.
DBSession.add(media_obj)
DBSession.flush()
# Create a MediaFile object, add it to the media_obj, and store the file permanently.
media_file = add_new_media_file(media_obj, file=uploaded_file, url=url)
# The thumbs may have been created already by add_new_media_file
if not has_thumbs(media_obj):
create_default_thumbs_for(media_obj)
media_obj.update_status()
DBSession.flush()
return media_obj
示例4: rate
# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import add [as 别名]
def rate(self, slug, rating=1, **kwargs):
"""Rate up or down the given media.
:param slug: The media :attr:`~mediacore.model.media.Media.slug`
:param rating: ``1`` or ``0`` if the rating is up or down.
:rtype: JSON dict
:returns:
succcess
bool
upRating
Pluralized count of up raters, "# people" or "1 person"
downRating
Pluralized count of down raters, "# people" or "1 person"
"""
media = fetch_row(Media, slug=slug)
if rating > 0:
media.rating.add_vote(1)
else:
media.rating.add_vote(0)
DBSession.add(media)
if request.is_xhr:
return dict(
success = True,
upRating = helpers.text.plural(media.rating.sum, 'person', 'people'),
downRating = None,
)
else:
redirect(action='view')
示例5: test_audiodesc_video_url_media
# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import add [as 别名]
def test_audiodesc_video_url_media(self):
"""Media with both Audio files and Video files attatched should be
Video type."""
try:
# Create the media object
media = self._new_publishable_media(u'description-video',
u'(Audio Description + Video)')
DBSession.add(media)
# Add an audio description
media_file = add_new_media_file(media, None,
u'http://fakesite.com/fakefile.mp3')
media_file.type = AUDIO_DESC
media.update_status()
# Add a video file
media_file = add_new_media_file(media, None,
u'http://fakesite.com/fakefile.m4v')
media.update_status()
# Commit + test
DBSession.commit()
assert media.type == VIDEO, \
"A Media object with a .m4v file and an Audio Description " \
"was not labelled as a video type; it was labelled %s" % \
(t, media.type)
except SQLAlchemyError, e:
DBSession.rollback()
raise e
示例6: comment
# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import add [as 别名]
def comment(self, slug, **values):
"""Post a comment from :class:`~mediacore.forms.media.PostCommentForm`.
:param slug: The media :attr:`~mediacore.model.media.Media.slug`
:returns: Redirect to :meth:`view` page for media.
"""
if tmpl_context.form_errors:
if request.is_xhr:
return dict(
success = False,
errors = tmpl_context.form_errors
)
else:
redirect(action='view')
media = fetch_row(Media, slug=slug)
c = Comment()
c.status = 'unreviewed'
c.author = AuthorWithIP(values['name'], None, request.environ['REMOTE_ADDR'])
c.subject = 'Re: %s' % media.title
c.body = helpers.clean_xhtml(values['body'])
media.comments.append(c)
DBSession.add(media)
email.send_comment_notification(media, c)
if request.is_xhr:
return dict(success = True)
else:
redirect(action='view')
示例7: _add_new_media_file
# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.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.type = file_ext
media_file.url = 'dummy_url' # model requires that url not NULL
media_file.is_original = True
media_file.enable_player = media_file.is_playable
media_file.enable_feed = not media_file.is_embeddable
media_file.size = os.fstat(file.fileno())[6]
# 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.url = file_url
return media_file
示例8: main
# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import add [as 别名]
def main(parser, options, args):
app_globs = app_globals._current_obj()
app_id = app_globals.settings['facebook_appid']
if not app_id:
print 'No Facebook app_id configured, exiting'
sys.exit(3)
app_secret = options.app_secret
fb = FacebookAPI(app_id, app_secret)
from mediacore.model import DBSession, Media
# eager loading of 'meta' to speed up later check.
all_media = Media.query.options(joinedload('_meta')).all()
print 'Checking all media for existing Facebook comments'
progress = ProgressBar(maxval=len(all_media)).start()
for i, media in enumerate(all_media):
progress.update(i+1)
if 'facebook-comment-xid' not in media.meta:
continue
if not fb.has_xid_comments(media):
continue
media.meta[u'facebook-comment-xid'] = unicode(media.id)
DBSession.add(media)
DBSession.commit()
progress.finish()
开发者ID:BlendedLearningCollaborative,项目名称:mediacore-community,代码行数:29,代码来源:upgrade_from_v09_preserve_facebook_xid_comments.py
示例9: save
# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.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)
示例10: _update_settings
# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import add [as 别名]
def _update_settings(self, values):
"""Modify the settings associated with the given dictionary."""
for name, value in values.iteritems():
if name in tmpl_context.settings:
setting = tmpl_context.settings[name]
else:
setting = Setting(key=name, value=value)
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
示例11: _create_user_without_groups
# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import add [as 别名]
def _create_user_without_groups(self):
user = User()
user.user_name = u'joe'
user.email_address = u'[email protected]'
user.display_name = u'Joe'
user.groups = []
DBSession.add(user)
DBSession.flush()
return user
示例12: save_media_obj
# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import add [as 别名]
def save_media_obj(author_name, author_email, title, description, tags, file, url):
media = Media()
media.author = Author(author_name, author_email)
media.title = title
media.description = description
media.tags = tags
add_new_media_file(media, file=file, url=url)
DBSession.add(media)
DBSession.commit()
return media
示例13: save_album_art
# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import add [as 别名]
def save_album_art(self, id, album_art, **kwargs):
"""Save album art uploaded with :class:`~mediacore.forms.media.AlbumArtForm`.
: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, incl_trash=True)
im_path = os.path.join(config.image_dir, 'media/%s%s.%s')
try:
# Create thumbnails
im = Image.open(album_art.file)
if id == 'new':
DBSession.add(media)
DBSession.flush()
# TODO: Allow other formats?
for key, dimensions in config.album_art_sizes.iteritems():
file_path = im_path % (media.id, key, 'jpg')
im.resize(dimensions, 1).save(file_path)
# Backup the original image just for kicks
orig_type = os.path.splitext(album_art.filename)[1].lower()[1:]
backup_file = open(im_path % (media.id, 'orig', orig_type), 'w')
copyfileobj(album_art.file, backup_file)
album_art.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
示例14: comment
# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import add [as 别名]
def comment(self, slug, **values):
"""Post a comment from :class:`~mediacore.forms.comments.PostCommentForm`.
:param slug: The media :attr:`~mediacore.model.media.Media.slug`
:returns: Redirect to :meth:`view` page for media.
"""
akismet_key = helpers.fetch_setting('akismet_key')
akismet_url = helpers.fetch_setting('akismet_url')
if akismet_key:
akismet = Akismet(agent='MediaCore/%s' % MEDIACORE_VERSION)
akismet.key = akismet_key
akismet.blog_url = akismet_url or url_for('/', qualified=True)
akismet.verify_key()
data = {'comment_author': values['name'].encode('utf-8'),
'user_ip': request.environ.get('REMOTE_ADDR'),
'user_agent': request.environ.get('HTTP_USER_AGENT'),
'referrer': request.environ.get('HTTP_REFERER', 'unknown'),
'HTTP_ACCEPT': request.environ.get('HTTP_ACCEPT')}
if akismet.comment_check(values['body'].encode('utf-8'), data):
title = "Comment Rejected"
text = "Your comment appears to be spam and has been rejected."
add_transient_message('comment_posted', title, text)
redirect(action='view', anchor='top')
media = fetch_row(Media, slug=slug)
c = Comment()
c.author = AuthorWithIP(
values['name'], values['email'], request.environ['REMOTE_ADDR']
)
c.subject = 'Re: %s' % media.title
c.body = values['body']
require_review = asbool(helpers.fetch_setting('req_comment_approval'))
if not require_review:
c.reviewed = True
c.publishable = True
media.comments.append(c)
DBSession.add(media)
email.send_comment_notification(media, c)
if require_review:
title = "Thanks for your comment!"
text = "We will post it just as soon as a moderator approves it."
add_transient_message('comment_posted', title, text)
redirect(action='view', anchor='top')
else:
redirect(action='view', anchor='comment-%s' % c.id)
示例15: view
# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import add [as 别名]
def view(self, slug, podcast_slug=None, **kwargs):
"""Display the media player, info and comments.
:param slug: The :attr:`~mediacore.models.media.Media.slug` to lookup
:param podcast_slug: The :attr:`~mediacore.models.podcasts.Podcast.slug`
for podcast this media belongs to. Although not necessary for
looking up the media, it tells us that the podcast slug was
specified in the URL and therefore we reached this action by the
preferred route.
:rtype dict:
:returns:
media
The :class:`~mediacore.model.media.Media` instance for display.
comment_form
The :class:`~mediacore.forms.comments.PostCommentForm` instance.
comment_form_action
``str`` comment form action
comment_form_values
``dict`` form values
next_episode
The next episode in the podcast series, if this media belongs to
a podcast, another :class:`~mediacore.model.media.Media`
instance.
"""
media = fetch_row(Media, slug=slug)
media.increment_views()
DBSession.add(media)
if media.podcast_id is not None:
# Always view podcast media from a URL that shows the context of the podcast
if url_for() != url_for(podcast_slug=media.podcast.slug):
redirect(podcast_slug=media.podcast.slug)
if media.fulltext:
related = Media.query.published()\
.options(orm.undefer('comment_count_published'))\
.filter(Media.id != media.id)\
.search('>(%s) <(%s)' % (media.title, media.fulltext.tags))[:6]
else:
related = []
return dict(
media = media,
related_media = related,
comments = media.comments.published().all(),
comment_form = post_comment_form,
comment_form_action = url_for(action='comment', anchor=post_comment_form.id),
comment_form_values = kwargs,
)