• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python managers.DBManager类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pajbot.managers.DBManager的典型用法代码示例。如果您正苦于以下问题:Python DBManager类的具体用法?Python DBManager怎么用?Python DBManager使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了DBManager类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: on_banphrase_update

    def on_banphrase_update(self, data, conn):
        try:
            banphrase_id = int(data['banphrase_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)
开发者ID:TalVivian,项目名称:pajbot,代码行数:29,代码来源:banphrase.py


示例2: generate_token_for_user

    def generate_token_for_user(self, user, scopes):
        if not user:
            return None

        token = APIToken(user, scopes)
        DBManager.session_add_expunge(token)

        return token
开发者ID:rigor789,项目名称:pajbot,代码行数:8,代码来源:apitoken.py


示例3: get_user

def get_user(username):
    session = DBManager.create_session()
    user = session.query(User).filter_by(username=username).one_or_none()
    if user is None:
        return make_response(jsonify({'error': 'Not found'}), 404)

    rank = session.query(func.Count(User.id)).filter(User.points > user.points).one()
    rank = rank[0] + 1
    session.close()
    if user:
        accessible_data = {
                'id': user.id,
                'username': user.username,
                'username_raw': user.username_raw,
                'points': user.points,
                'rank': rank,
                'level': user.level,
                'last_seen': user.last_seen,
                'last_active': user.last_active,
                'subscriber': user.subscriber,
                'num_lines': user.num_lines,
                'minutes_in_chat_online': user.minutes_in_chat_online,
                'minutes_in_chat_offline': user.minutes_in_chat_offline,
                'banned': user.banned,
                'ignored': user.ignored,
                }
        return jsonify(accessible_data)

    return make_response(jsonify({'error': 'Not found'}), 404)
开发者ID:coral,项目名称:pajbot,代码行数:29,代码来源:api.py


示例4: command_remove

def command_remove(command_id, **options):
    with DBManager.create_session_scope() as db_session:
        command = db_session.query(Command).filter_by(id=command_id).one_or_none()
        if command is None:
            return make_response(jsonify({'error': 'Invalid command ID'}), 404)
        if command.level > options['user'].level:
            abort(403)
        log_msg = 'The !{} command has been removed'.format(command.command.split('|')[0])
        AdminLogManager.add_entry('Command removed',
                options['user'],
                log_msg)
        db_session.delete(command.data)
        db_session.delete(command)

    payload = {
            'event': 'command.remove',
            'data': {
                'command_id': command_id
                }
            }
    payload_bytes = json.dumps(payload).encode('utf-8')
    try:
        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
            client.connect(config['sock']['sock_file'])
            client.sendall(payload_bytes)
            return make_response(jsonify({'success': 'good job'}))
    except:
        log.exception('???')
        return make_response(jsonify({'error': 'Could not push update'}))
开发者ID:coral,项目名称:pajbot,代码行数:29,代码来源:api.py


示例5: pleblist_next

def pleblist_next():
    if not request.method == 'POST':
        return make_response(jsonify({'error': 'Invalid request method'}), 405)
    if 'song_id' not in request.form:
        return make_response(jsonify({'error': 'Missing data song_id'}), 400)
    if 'password' not in request.form:
        return make_response(jsonify({'error': 'Missing data password'}), 400)
    salted_password = generate_password_hash(config['web']['pleblist_password'], config['web']['pleblist_password_salt'])
    try:
        user_password = base64.b64decode(request.form['password'])
    except binascii.Error:
        return make_response(jsonify({'error': 'Invalid data password'}), 400)
    if not user_password == salted_password:
        return make_response(jsonify({'error': 'Invalid password'}), 401)

    with DBManager.create_session_scope() as session:
        try:
            current_song = session.query(PleblistSong).filter(PleblistSong.id == int(request.form['song_id'])).order_by(PleblistSong.date_added.asc()).first()
        except ValueError:
            return make_response(jsonify({'error': 'Invalid data song_id'}), 400)

        if current_song is None:
            return make_response(jsonify({'error': 'No song active in the pleblist'}), 404)

        current_song.date_played = datetime.datetime.now()
        session.commit()

        # TODO: Add more data.
        # Was this song forcefully skipped? Or did it end naturally.

        return jsonify({'message': 'Success!'})
开发者ID:coral,项目名称:pajbot,代码行数:31,代码来源:api.py


示例6: enable

    def enable(self, bot):
        self.bot = bot
        HandlerManager.add_handler('on_message', self.on_message, priority=100)
        HandlerManager.add_handler('on_commit', self.on_commit)
        if bot:
            self.run_later = bot.execute_delayed

            if 'safebrowsingapi' in bot.config['main']:
                # XXX: This should be loaded as a setting instead.
                # There needs to be a setting for settings to have them as "passwords"
                # so they're not displayed openly
                self.safeBrowsingAPI = SafeBrowsingAPI(bot.config['main']['safebrowsingapi'], bot.nickname, bot.version)
            else:
                self.safeBrowsingAPI = None

        if self.db_session is not None:
            self.db_session.commit()
            self.db_session.close()
            self.db_session = None
        self.db_session = DBManager.create_session()
        self.blacklisted_links = []
        for link in self.db_session.query(BlacklistedLink):
            self.blacklisted_links.append(link)

        self.whitelisted_links = []
        for link in self.db_session.query(WhitelistedLink):
            self.whitelisted_links.append(link)
开发者ID:coral,项目名称:pajbot,代码行数:27,代码来源:linkchecker.py


示例7: point_pos

    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))
开发者ID:Nacht123,项目名称:pajbot,代码行数:26,代码来源:dispatch.py


示例8: post

    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(Banphrase).filter_by(id=row_id).one_or_none()

            if not row:
                return {
                        'error': 'Banphrase with this ID not found'
                        }, 404

            row.enabled = True if new_state == 1 else False
            db_session.commit()
            payload = {
                    'id': row.id,
                    'new_state': row.enabled,
                    }
            AdminLogManager.post('Banphrase toggled',
                    options['user'],
                    'Enabled' if row.enabled else 'Disabled',
                    row.phrase)
            SocketClientManager.send('banphrase.update', payload)
            return {'success': 'successful toggle', 'new_state': new_state}
开发者ID:Nacht123,项目名称:pajbot,代码行数:28,代码来源:banphrases.py


示例9: authorized

    def authorized():
        try:
            resp = twitch.authorized_response()
        except OAuthException:
            log.exception('An exception was caught while authorizing')
            next_url = get_next_url(request, 'state')
            return redirect(next_url)

        print(resp)
        if resp is None:
            log.warn('Access denied: reason={}, error={}'.format(request.args['error'], request.args['error_description']))
            next_url = get_next_url(request, 'state')
            return redirect(next_url)
        elif type(resp) is OAuthException:
            log.warn(resp.message)
            log.warn(resp.data)
            log.warn(resp.type)
            next_url = get_next_url(request, 'state')
            return redirect(next_url)
        session['twitch_token'] = (resp['access_token'], )
        me = twitch.get('user')
        level = 100
        with DBManager.create_session_scope() as db_session:
            db_user = db_session.query(User).filter_by(username=me.data['name'].lower()).one_or_none()
            if db_user:
                level = db_user.level
        session['user'] = {
                'username': me.data['name'],
                'username_raw': me.data['display_name'],
                'level': level,
                }
        next_url = get_next_url(request, 'state')
        return redirect(next_url)
开发者ID:TalVivian,项目名称:pajbot,代码行数:33,代码来源:login.py


示例10: get_current_song

 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
开发者ID:Nacht123,项目名称:pajbot,代码行数:7,代码来源:pleblist.py


示例11: modules_edit

    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)
开发者ID:Nacht123,项目名称:pajbot,代码行数:60,代码来源:modules.py


示例12: nl_pos

    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))
开发者ID:Nacht123,项目名称:pajbot,代码行数:29,代码来源:dispatch.py


示例13: decks_warrior

 def decks_warrior():
     session = DBManager.create_session()
     decks = session.query(Deck).filter_by(deck_class='warrior').order_by(Deck.last_used.desc(), Deck.first_used.desc()).all()
     session.close()
     return render_template('decks/by_class.html',
             decks=decks,
             deck_class='Warrior')
开发者ID:Nacht123,项目名称:pajbot,代码行数:7,代码来源:decks.py


示例14: post

    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:
            try:
                current_song = session.query(PleblistSong).filter(PleblistSong.id == args['song_id']).order_by(PleblistSong.date_added.asc()).first()
            except ValueError:
                return {
                        'error': 'Invalid data song_id'
                        }, 400

            if current_song is None:
                return {
                        'error': 'No song active in the pleblist'
                        }, 404

            current_song.date_played = datetime.datetime.now()
            session.commit()

            # TODO: Add more data.
            # Was this song forcefully skipped? Or did it end naturally.

            return {
                    'success': 'got em!'
                    }, 200
开发者ID:Nacht123,项目名称:pajbot,代码行数:30,代码来源:pleblist.py


示例15: commands

    def commands(**options):
        from pajbot.models.command import CommandManager
        from pajbot.models.module import ModuleManager
        bot_commands = 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))
开发者ID:Nacht123,项目名称:pajbot,代码行数:33,代码来源:commands.py


示例16: create_stream

    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')
开发者ID:Nacht123,项目名称:pajbot,代码行数:33,代码来源:stream.py


示例17: generic_toggle

def generic_toggle(route_key, row_id, **options):
    valid_routes = {
            'timer': Timer,
            'banphrase': Banphrase,
            'module': Module,
            }

    route_name = {
            'timer': lambda x: x.name,
            'banphrase': lambda x: x.phrase,
            'module': lambda x: x.id,
            }

    route_title = {
            'timer': 'Timer',
            'banphrase': 'Banphrase',
            'module': 'Module',
            }

    route_validator = {
            'module': lambda x: validate_module(x.id)
            }

    if route_key not in valid_routes:
        return make_response(jsonify({'error': 'Invalid route.'}), 400)
    if 'new_state' not in request.form:
        return make_response(jsonify({'error': 'Missing `new_state` parameter.'}), 400)
    try:
        new_state = int(request.form['new_state'])
    except (ValueError, KeyError):
        return make_response(jsonify({'error': 'Invalid `new_state` parameter.'}), 400)

    route_value = valid_routes[route_key]

    with DBManager.create_session_scope() as db_session:
        row = db_session.query(route_value).filter_by(id=row_id).one_or_none()
        if row:
            validator = route_validator.get(route_key, None)

            if validator is not None:
                res = validator(row)
                if not res:
                    return make_response(jsonify({'error': 'cannot modify {}'.format(route_key)}), 400)

            row.enabled = True if new_state == 1 else False
            db_session.commit()
            payload = {
                    '{}_id'.format(route_key): row.id,  # remove this
                    'id': row.id,
                    'new_state': row.enabled,
                    }
            AdminLogManager.post('{title} toggled'.format(title=route_title[route_key]),
                    options['user'],
                    'Enabled' if row.enabled else 'Disabled',
                    route_name[route_key](row))
            SocketClientManager.send('{}.update'.format(route_key), payload)
            return make_response(jsonify({'success': 'successful toggle', 'new_state': new_state}))
        else:
            return make_response(jsonify({'error': 'invalid {} id'.format(route_key)}))
开发者ID:TalVivian,项目名称:pajbot,代码行数:59,代码来源:api.py


示例18: timer_remove

def timer_remove(timer_id, **options):
    with DBManager.create_session_scope() as db_session:
        timer = db_session.query(Timer).filter_by(id=timer_id).one_or_none()
        if timer is None:
            return make_response(jsonify({'error': 'Invalid timer ID'}))
        db_session.delete(timer)
        SocketClientManager.send('timer.remove', {'timer_id': timer.id})
        return make_response(jsonify({'success': 'good job'}))
开发者ID:coral,项目名称:pajbot,代码行数:8,代码来源:api.py


示例19: __init__

    def __init__(self, bot):
        self.bot = bot
        self.banphrases = []
        self.enabled_banphrases = []
        self.db_session = DBManager.create_session(expire_on_commit=False)

        if self.bot:
            self.bot.socket_manager.add_handler('banphrase.update', self.on_banphrase_update)
            self.bot.socket_manager.add_handler('banphrase.remove', self.on_banphrase_remove)
开发者ID:TalVivian,项目名称:pajbot,代码行数:9,代码来源:banphrase.py


示例20: pleblist_blacklist

def pleblist_blacklist():
    with DBManager.create_session_scope() as session:
        current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start).first()
        if current_stream is None:
            return make_response(jsonify({'error': 'Stream offline'}), 400)

        # TODO: implement this

        return make_response(jsonify({'error': 'NOT IMPLEMENTED'}), 400)
开发者ID:coral,项目名称:pajbot,代码行数:9,代码来源:api.py



注:本文中的pajbot.managers.DBManager类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python managers.HandlerManager类代码示例发布时间:2022-05-27
下一篇:
Python managers.AdminLogManager类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap