本文整理汇总了Python中pajbot.managers.db.DBManager.create_session_scope方法的典型用法代码示例。如果您正苦于以下问题:Python DBManager.create_session_scope方法的具体用法?Python DBManager.create_session_scope怎么用?Python DBManager.create_session_scope使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pajbot.managers.db.DBManager
的用法示例。
在下文中一共展示了DBManager.create_session_scope方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: on_banphrase_update
# 需要导入模块: from pajbot.managers.db import DBManager [as 别名]
# 或者: from pajbot.managers.db.DBManager import create_session_scope [as 别名]
def on_banphrase_update(self, data, conn):
try:
banphrase_id = int(data['id'])
except (KeyError, ValueError):
log.warn('No banphrase ID found in on_banphrase_update')
return False
updated_banphrase = find(lambda banphrase: banphrase.id == banphrase_id, self.banphrases)
if updated_banphrase:
with DBManager.create_session_scope(expire_on_commit=False) as db_session:
db_session.add(updated_banphrase)
db_session.refresh(updated_banphrase)
db_session.expunge(updated_banphrase)
else:
with DBManager.create_session_scope(expire_on_commit=False) as db_session:
updated_banphrase = db_session.query(Banphrase).filter_by(id=banphrase_id).one_or_none()
db_session.expunge_all()
if updated_banphrase is not None:
self.db_session.add(updated_banphrase.data)
if updated_banphrase:
if updated_banphrase not in self.banphrases:
self.banphrases.append(updated_banphrase)
if updated_banphrase.enabled is True and updated_banphrase not in self.enabled_banphrases:
self.enabled_banphrases.append(updated_banphrase)
for banphrase in self.enabled_banphrases:
if banphrase.enabled is False:
self.enabled_banphrases.remove(banphrase)
示例2: points
# 需要导入模块: from pajbot.managers.db import DBManager [as 别名]
# 或者: from pajbot.managers.db.DBManager import create_session_scope [as 别名]
def points():
with DBManager.create_session_scope() as db_session:
custom_web_content = db_session.query(WebContent).filter_by(page='points').first()
custom_content = ''
if custom_web_content and custom_web_content.content:
try:
custom_content = Markup(markdown.markdown(custom_web_content.content))
except:
log.exception('Unhandled exception in def index')
rank = 1
index = 1
last_user_points = -13333337
rankings = []
for user in db_session.query(User).order_by(User.points.desc()).limit(30):
if user.points != last_user_points:
rank = index
rankings.append((rank, user))
index += 1
last_user_points = user.points
return render_template('points.html',
top_30_users=rankings,
custom_content=custom_content)
示例3: commands
# 需要导入模块: from pajbot.managers.db import DBManager [as 别名]
# 或者: from pajbot.managers.db.DBManager import create_session_scope [as 别名]
def commands(**options):
from pajbot.models.module import ModuleManager
bot_commands = pajbot.managers.command.CommandManager(
socket_manager=None,
module_manager=ModuleManager(None).load(),
bot=None).load(enabled=None)
bot_commands_list = bot_commands.parse_for_web()
custom_commands = []
point_commands = []
moderator_commands = []
for command in bot_commands_list:
if command.id is None:
continue
if command.level > 100 or command.mod_only:
moderator_commands.append(command)
elif command.cost > 0:
point_commands.append(command)
else:
custom_commands.append(command)
with DBManager.create_session_scope() as db_session:
commands_data = db_session.query(CommandData).options(joinedload(CommandData.user), joinedload(CommandData.user2)).all()
return render_template(
'admin/commands.html',
commands_data=commands_data,
custom_commands=sorted(custom_commands, key=lambda f: f.command),
point_commands=sorted(point_commands, key=lambda a: (a.cost, a.command)),
moderator_commands=sorted(moderator_commands, key=lambda c: (c.level if c.mod_only is False else 500, c.command)),
created=session.pop('command_created_id', None),
edited=session.pop('command_edited_id', None))
示例4: nl_pos
# 需要导入模块: from pajbot.managers.db import DBManager [as 别名]
# 或者: from pajbot.managers.db.DBManager import create_session_scope [as 别名]
def nl_pos(bot, source, message, event, args):
# XXX: This should be a module
# These phrases should be module settings
nl_0 = '{username} has not typed any messages in this channel BibleThump'
nl_pos = '{username} is rank {nl_pos} line-farmer in this channel!'
if message:
tmp_username = message.split(' ')[0].strip().lower()
user = bot.users.find(tmp_username)
if user:
username = user.username_raw
num_lines = user.num_lines
else:
username = tmp_username
num_lines = 0
else:
username = source.username_raw
num_lines = source.num_lines
phrase_data = {
'username': username,
'num_lines': num_lines
}
if num_lines <= 0:
bot.say(nl_0.format(**phrase_data))
else:
with DBManager.create_session_scope() as db_session:
query_data = db_session.query(func.count(User.id)).filter(User.num_lines > num_lines).one()
phrase_data['nl_pos'] = int(query_data[0]) + 1
bot.say(nl_pos.format(**phrase_data))
示例5: __init__
# 需要导入模块: from pajbot.managers.db import DBManager [as 别名]
# 或者: from pajbot.managers.db.DBManager import create_session_scope [as 别名]
def __init__(self, bot):
self.bot = bot
self.current_stream_chunk = None # should this even exist?
self.num_offlines = 0
self.first_offline = None
self.num_viewers = 0
self.bot.execute_every(self.STATUS_CHECK_INTERVAL,
self.bot.action_queue.add,
(self.refresh_stream_status_stage1, ))
self.bot.execute_every(self.VIDEO_URL_CHECK_INTERVAL,
self.bot.action_queue.add,
(self.refresh_video_url_stage1, ))
"""
This will load the latest stream so we can post an accurate
"time since last online" figure.
"""
with DBManager.create_session_scope(expire_on_commit=False) as db_session:
self.current_stream = db_session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start.desc()).first()
self.last_stream = db_session.query(Stream).filter_by(ended=True).order_by(Stream.stream_end.desc()).first()
if self.current_stream:
self.current_stream_chunk = db_session.query(StreamChunk).filter_by(stream_id=self.current_stream.id).order_by(StreamChunk.chunk_start.desc()).first()
log.info('Set current stream chunk here to {0}'.format(self.current_stream_chunk))
db_session.expunge_all()
示例6: get_current_song
# 需要导入模块: from pajbot.managers.db import DBManager [as 别名]
# 或者: from pajbot.managers.db.DBManager import create_session_scope [as 别名]
def get_current_song(stream_id):
with DBManager.create_session_scope() as session:
cur_song = session.query(PleblistSong).filter(PleblistSong.stream_id == stream_id, PleblistSong.date_played.is_(None)).order_by(PleblistSong.date_added.asc(), PleblistSong.id.asc()).first()
if cur_song is None:
return None
session.expunge(cur_song)
return cur_song
示例7: point_pos
# 需要导入模块: from pajbot.managers.db import DBManager [as 别名]
# 或者: from pajbot.managers.db.DBManager import create_session_scope [as 别名]
def point_pos(bot, source, message, event, args):
# XXX: This should be a module
user = None
# This phrase should be a module setting
point_pos = '{username_w_verb} rank {point_pos} point-hoarder in this channel with {points} points.'
if message:
tmp_username = message.split(' ')[0].strip().lower()
user = bot.users.find(tmp_username)
if not user:
user = source
phrase_data = {
'points': user.points
}
if user == source:
phrase_data['username_w_verb'] = 'You are'
else:
phrase_data['username_w_verb'] = '{0} is'.format(user.username_raw)
if user.points > 0:
with DBManager.create_session_scope() as db_session:
query_data = db_session.query(func.count(User.id)).filter(User.points > user.points).one()
phrase_data['point_pos'] = int(query_data[0]) + 1
bot.whisper(source.username, point_pos.format(**phrase_data))
示例8: create_stream
# 需要导入模块: from pajbot.managers.db import DBManager [as 别名]
# 或者: from pajbot.managers.db.DBManager import create_session_scope [as 别名]
def create_stream(self, status):
log.info('Attempting to create a stream!')
with DBManager.create_session_scope(expire_on_commit=False) as db_session:
stream_chunk = db_session.query(StreamChunk).filter_by(broadcast_id=status['broadcast_id']).one_or_none()
new_stream = False
if stream_chunk is not None:
stream = stream_chunk.stream
else:
log.info('checking if there is an active stream already')
stream = db_session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start.desc()).first()
new_stream = stream is None
if new_stream:
log.info('No active stream, create new!')
stream = Stream(status['created_at'],
title=status['title'])
db_session.add(stream)
db_session.commit()
log.info('Successfully added stream!')
stream_chunk = StreamChunk(stream, status['broadcast_id'], status['created_at'])
db_session.add(stream_chunk)
db_session.commit()
stream.stream_chunks.append(stream_chunk)
log.info('Created stream chunk')
self.current_stream = stream
self.current_stream_chunk = stream_chunk
db_session.expunge_all()
if new_stream:
HandlerManager.trigger('on_stream_start', stop_on_false=False)
log.info('Successfully created a stream')
示例9: post
# 需要导入模块: from pajbot.managers.db import DBManager [as 别名]
# 或者: from pajbot.managers.db.DBManager import create_session_scope [as 别名]
def post(self, row_id, **options):
args = self.post_parser.parse_args()
try:
new_state = int(args['new_state'])
except (ValueError, KeyError):
return {'error': 'Invalid `new_state` parameter.'}, 400
with DBManager.create_session_scope() as db_session:
row = db_session.query(Module).filter_by(id=row_id).one_or_none()
if not row:
return {
'error': 'Module with this ID not found'
}, 404
if validate_module(row_id) is False:
return {'error': 'cannot modify module'}, 400
row.enabled = True if new_state == 1 else False
db_session.commit()
payload = {
'id': row.id,
'new_state': row.enabled,
}
AdminLogManager.post('Module toggled',
options['user'],
'Enabled' if row.enabled else 'Disabled',
row.id)
SocketClientManager.send('module.update', payload)
return {'success': 'successful toggle', 'new_state': new_state}
示例10: post
# 需要导入模块: from pajbot.managers.db import DBManager [as 别名]
# 或者: from pajbot.managers.db.DBManager import create_session_scope [as 别名]
def post(self):
args = self.post_parser.parse_args()
try:
pajbot.web.utils.pleblist_login(args['password'], app.bot_config)
except pajbot.exc.InvalidLogin as e:
return {'error': str(e)}, 401
with DBManager.create_session_scope() as session:
youtube_id = args['youtube_id']
current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start).first()
if current_stream is None:
return {
'error': 'Stream offline'
}, 400
skip_after = args['skip_after']
log.info('Request song youtube ID: {}'.format(youtube_id))
song_requested = PleblistSong(current_stream.id, youtube_id, skip_after=skip_after)
session.add(song_requested)
song_info = session.query(PleblistSongInfo).filter_by(pleblist_song_youtube_id=youtube_id).first()
if song_info is None and song_requested.song_info is None:
PleblistManager.init(app.bot_config['youtube']['developer_key'])
song_info = PleblistManager.create_pleblist_song_info(song_requested.youtube_id)
if song_info is not False:
session.add(song_info)
session.commit()
return {
'success': 'got em!'
}, 200
示例11: stats
# 需要导入模块: from pajbot.managers.db import DBManager [as 别名]
# 或者: from pajbot.managers.db.DBManager import create_session_scope [as 别名]
def stats():
bot_commands_list = pajbot.web.utils.get_cached_commands()
top_5_commands = sorted(bot_commands_list, key=lambda c: c['data']['num_uses'] if c['data'] is not None else -1, reverse=True)[:5]
redis = RedisManager.get()
# TODO: Make this hideable through some magic setting (NOT config.ini @[email protected])
with DBManager.create_session_scope() as db_session:
top_5_line_farmers = []
for redis_user in redis.zrevrangebyscore(
'{streamer}:users:num_lines'.format(streamer=StreamHelper.get_streamer()),
'+inf',
'-inf',
start=0,
num=5,
withscores=True,
score_cast_func=int):
user = UserManager.get_static(redis_user[0], db_session=db_session)
user.save_to_redis = False
user.num_lines = redis_user[1]
top_5_line_farmers.append(user)
return render_template('stats.html',
top_5_commands=top_5_commands,
top_5_line_farmers=top_5_line_farmers)
示例12: modules_edit
# 需要导入模块: from pajbot.managers.db import DBManager [as 别名]
# 或者: from pajbot.managers.db.DBManager import create_session_scope [as 别名]
def modules_edit(module_id, **options):
module_manager = ModuleManager(None).load(do_reload=False)
current_module = find(lambda m: m.ID == module_id, module_manager.all_modules)
if current_module is None:
return render_template('admin/module_404.html'), 404
sub_modules = []
for module in module_manager.all_modules:
module.db_module = None
with DBManager.create_session_scope() as db_session:
for db_module in db_session.query(Module):
module = find(lambda m: m.ID == db_module.id, module_manager.all_modules)
if module:
module.db_module = db_module
if module.PARENT_MODULE == current_module.__class__:
sub_modules.append(module)
if current_module.db_module is None:
return render_template('admin/module_404.html'), 404
if request.method == 'POST':
form_values = {key: value for key, value in request.form.items()}
res = current_module.parse_settings(**form_values)
if res is False:
return render_template('admin/module_404.html'), 404
current_module.db_module.settings = json.dumps(res)
db_session.commit()
settings = None
try:
settings = json.loads(current_module.db_module.settings)
except (TypeError, ValueError):
pass
current_module.load(settings=settings)
payload = {
'id': current_module.db_module.id,
}
SocketClientManager.send('module.update', payload)
AdminLogManager.post('Module edited', options['user'], current_module.NAME)
return render_template('admin/configure_module.html',
module=current_module,
sub_modules=sub_modules)
else:
settings = None
try:
settings = json.loads(current_module.db_module.settings)
except (TypeError, ValueError):
pass
current_module.load(settings=settings)
return render_template('admin/configure_module.html',
module=current_module,
sub_modules=sub_modules)
示例13: pleblist_history_stream
# 需要导入模块: from pajbot.managers.db import DBManager [as 别名]
# 或者: from pajbot.managers.db.DBManager import create_session_scope [as 别名]
def pleblist_history_stream(stream_id):
with DBManager.create_session_scope() as session:
stream = session.query(Stream).filter_by(id=stream_id).one_or_none()
if stream is None:
return render_template('pleblist_history_404.html'), 404
previous_stream = session.query(Stream).filter_by(id=stream_id - 1).one_or_none()
next_stream = session.query(Stream).filter_by(id=stream_id + 1).one_or_none()
q = session.query(PleblistSong, User).outerjoin(User, PleblistSong.user_id == User.id).filter(PleblistSong.stream_id == stream.id).order_by(PleblistSong.id.asc(), PleblistSong.id.asc())
songs = []
for song, user in q:
song.user = user
songs.append(song)
total_length_left = sum([song.skip_after or song.song_info.duration if song.date_played is None and song.song_info is not None else 0 for song in songs])
first_unplayed_song = find(lambda song: song.date_played is None, songs)
stream_chunks = session.query(StreamChunk).filter(StreamChunk.stream_id == stream.id).all()
return render_template('pleblist_history.html',
stream=stream,
previous_stream=previous_stream,
next_stream=next_stream,
songs=songs,
total_length_left=total_length_left,
first_unplayed_song=first_unplayed_song,
stream_chunks=stream_chunks)
示例14: sql_save
# 需要导入模块: from pajbot.managers.db import DBManager [as 别名]
# 或者: from pajbot.managers.db.DBManager import create_session_scope [as 别名]
def sql_save(self, save_to_db=True):
if not self.model_loaded:
return
if save_to_db and not self.shared_db_session:
with DBManager.create_session_scope(expire_on_commit=False) as db_session:
db_session.add(self.user_model)
UserSQLCache.save(self.user_model)
示例15: get
# 需要导入模块: from pajbot.managers.db import DBManager [as 别名]
# 或者: from pajbot.managers.db.DBManager import create_session_scope [as 别名]
def get(self, stream_id):
with DBManager.create_session_scope() as session:
songs = session.query(PleblistSong).filter_by(stream_id=stream_id)
return pajbot.web.utils.jsonify_list(
'songs',
songs,
base_url=url_for(self.endpoint, stream_id=stream_id, _external=True),
)