当前位置: 首页>>代码示例>>Python>>正文


Python dbsession.add函数代码示例

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


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

示例1: initialize

 def initialize(self, *args):
     ''' One time initialization, gathers system information '''
     success = False
     logging.info(
         "Preforming weapon system initialization, please wait ... ")
     ssh_keyfile = NamedTemporaryFile()
     ssh_keyfile.write(self.ssh_key)
     ssh_keyfile.seek(0)
     try:
         logging.info("Connectiong to remote ssh server at %s:%s" %
                      (self.ip_address, self.ssh_port))
         ssh_context = SshContext(self.ip_address,
                                  user=self.ssh_user, keyfile=ssh_keyfile.name)
         rpc_connection = rpyc.ssh_connect(ssh_context, self.service_port)
         capabilities = rpc_connection.root.exposed_get_capabilities()
         self.lm_capable = 'LM' in capabilities
         self.ntlm_capable = 'NTLM' in capabilities
         self.md5_capable = 'MD5' in capabilities
         self.cpu_count = rpc_connection.root.exposed_cpu_count()
         self.initialized = True
         dbsession.add(self)
         dbsession.flush()
         success = True
     except ValueError:
         logging.exception(
             "Failed to initialize weapon system, check parameters")
     except EOFError:
         logging.exception(
             "Failed to initialize weapon system, check parameters")
     finally:
         ssh_keyfile.close()
         return success
开发者ID:brutalhonesty,项目名称:The-Planetary-Assault-System,代码行数:32,代码来源:WeaponSystem.py

示例2: stats_complexity

 def stats_complexity(self):
     ''' Returns stats on solved hash's plain text complexity '''
     if self.cached_complexity_analysis == None:
         complexity = []
         if 0 < len(self.lower_case_passwords):
             complexity.append(
                 {'Lower Case': len(self.lower_case_passwords)})
         if 0 < len(self.upper_case_passwords):
             complexity.append(
                 {'Upper Case': len(self.upper_case_passwords)})
         if 0 < len(self.numeric_passwords):
             complexity.append({'Numeric': len(self.numeric_passwords)})
         if 0 < len(self.mixed_case_passwords):
             complexity.append(
                 {'Mixed Case': len(self.mixed_case_passwords)})
         if 0 < len(self.lower_alpha_numeric_passwords):
             complexity.append({'Lower Case Alpha-numeric':
                                len(self.lower_alpha_numeric_passwords)})
         if 0 < len(self.upper_alpha_numeric_passwords):
             complexity.append({'Upper Case Alpha-numeric':
                                len(self.upper_alpha_numeric_passwords)})
         if 0 < len(self.mixed_alpha_numeric_passwords):
             complexity.append({'Mixed Case Alpha-numeric':
                                len(self.mixed_alpha_numeric_passwords)})
         self.cached_complexity_analysis = json.dumps(complexity)
         dbsession.add(self)
         dbsession.flush()
     return self.cached_complexity_analysis
开发者ID:brutalhonesty,项目名称:The-Planetary-Assault-System,代码行数:28,代码来源:Job.py

示例3: create_file

 def create_file(self, user):
     """ Saves uploaded file """
     file_name = os.path.basename(self.request.files["file_data"][0]["filename"])
     char_white_list = ascii_letters + digits + "-._"
     file_name = filter(lambda char: char in char_white_list, file_name)
     content = guess_type(file_name)
     if content[0] is None:
         self.render(
             "share_upload/share_files.html",
             errors=["Unknown file content, please zip and upload"],
             shares=user.team.files,
         )
     elif len(file_name) < 1:
         self.render("share_upload/share_files.html", errors=["Invalid file name"])
     else:
         uuid = unicode(uuid4())
         filePath = self.application.settings["shares_dir"] + "/" + uuid
         save = open(filePath, "w")
         data = b64encode(self.request.files["file_data"][0]["body"])
         save.write(data)
         save.close()
         file_upload = FileUpload(
             file_name=unicode(file_name),
             content=unicode(str(content[0])),
             uuid=uuid,
             description=unicode(self.get_argument("description")),
             byte_size=len(self.request.files["file_data"][0]["body"]),
             team_id=user.team.id,
         )
         dbsession.add(file_upload)
         dbsession.flush()
         self.event_manager.team_file_share(user, file_upload)
开发者ID:brutalhonesty,项目名称:RootTheBox,代码行数:32,代码来源:ShareUploadHandlers.py

示例4: create_file

 def create_file(self, user):
     ''' Saves uploaded file '''
     file_name = os.path.basename(
         self.request.files['file_data'][0]['filename']
     )
     char_white_list = ascii_letters + digits + "-._"
     file_name = filter(lambda char: char in char_white_list, file_name)
     content = guess_type(file_name)
     if content[0] is None:
         self.render("share_upload/share_files.html",
             errors=["Unknown file content, please zip and upload"],
             shares=user.team.files
         )
     elif len(file_name) < 1:
         self.render("share_upload/share_files.html",
             errors=["Invalid file name"]
         )
     else:
         uuid = unicode(uuid4())
         filePath = self.application.settings['shares_dir'] + '/' + uuid
         save = open(filePath, 'w')
         data = b64encode(self.request.files['file_data'][0]['body'])
         save.write(data)
         save.close()
         file_upload = FileUpload(
             file_name=unicode(file_name),
             content=unicode(str(content[0])),
             uuid=uuid,
             description=unicode(self.get_argument('description', 'No description.')),
             byte_size=len(self.request.files['file_data'][0]['body']),
             team_id=user.team.id
         )
         dbsession.add(file_upload)
         dbsession.flush()
         return file_upload
开发者ID:CRYPTOlab,项目名称:RootTheBox,代码行数:35,代码来源:ShareUploadHandlers.py

示例5: post

 def post(self, *args, **kwargs):
     user_uuid = self.get_argument('uuid', '')
     user = User.by_uuid(user_uuid)
     if user is not None:
         errors = []
         username = self.get_argument('username', None)
         password = self.get_argument('password', None)
         if password is not None:
             if 12 <= len(password) <= 100:
                 self.change_user_password(user)
             else:
                 errors.append("Password invalid length (12-100)")
         if username is not None and username != user.username:
             if 3 <= len(username) <= 15:
                 if User.by_username(username) is None:
                     user.username = username
                     dbsession.add(user)
                     dbsession.flush()
                 else:
                     errors.append("Username already exists")
             else:
                 errors.append("Username is an invalid length (3-15)")
         self.render("admin/manage_users.html", errors=errors)
     else:
         self.render("admin/manage_users.html",
             errors=["User does not exist"]
         )
开发者ID:DJHartley,项目名称:The-Planetary-Assault-System,代码行数:27,代码来源:AdminHandlers.py

示例6: create_team

def create_team():
    team = Team()
    team.name = "TestTeam"
    team.motto = "TestMotto"
    dbsession.add(team)
    dbsession.commit()
    return team
开发者ID:AdaFormacion,项目名称:RootTheBox,代码行数:7,代码来源:Helpers.py

示例7: edit_ipv6

 def edit_ipv6(self):
     ''' Add ipv6 addresses to a box (sorta edits the box object) '''
     form = Form(box_uuid="Select a box", ipv6="Please provide a list of IPv6 addresses")
     if form.validate(self.request.arguments):
         errors = []
         box = Box.by_uuid(self.get_argument('box_uuid'))
         if box is not None:
             ips_string = self.get_argument('ipv6').replace('\n', ',').lower()
             ips = filter(lambda char: char in "1234567890abcdef:,", ips_string).split(",")
             for ip in filter(lambda ip: 0 < len(ip), ips):
                 try:
                     box = Box.by_ip_address(ip)
                     if box is None:
                         addr = IpAddress(box_id=box.id, v6=ip)
                         dbsession.add(addr)
                     else:
                         errors.append(
                             "%s has already been assigned to %s." % (ip, box.name,)
                         )
                 except ValueError:
                     errors.append(
                         "'%s' is not a valid IPv6 address" % str(ip[:39])
                     )
             dbsession.flush()
         else:
             errors.append("Box does not exist")
         self.render("admin/view/game_objects.html", errors=errors)
     else:
         self.render("admin/view/game_objects.html", errors=form.errors)
开发者ID:mach327,项目名称:RootTheBox,代码行数:29,代码来源:AdminHandlers.py

示例8: edit_users

 def edit_users(self):
     ''' Update user objects in the database '''
     form = Form(
         uuid="User not selected",
         account="Please enter an account name",
         handle="Please enter a handle name",
         hash_algorithm="Please select a hash algorithm",
         team_uuid="Please select a team",
     )
     if form.validate(self.request.arguments):
         errors = []
         user = User.by_uuid(self.get_argument('uuid'))
         if user is not None:
             # Update user account name
             if user.account != self.get_argument('account'):
                 if User.by_account(self.get_argument('account')) is None:
                     logging.info("Updated user account %s -> %s" %
                         (user.account, self.get_argument('account'),))
                     user.account = unicode(self.get_argument('account'))
                 else:
                     errors.append("Account name is already in use")
             # Update user handle
             if user.handle != self.get_argument('handle'):
                 if User.by_handle(self.get_argument('handle')) is None:
                     logging.info("Updated user handle %s -> %s" %
                         (user.handle, self.get_argument('handle'),))
                     user.handle = unicode(self.get_argument('handle'))
                 else:
                     errors.append("Handle is already in use")
             # Update hashing algoritm
             if self.get_argument('hash_algorithm') in user.algorithms:
                 if user.algorithm != self.get_argument('hash_algorithm'):
                     if 0 < len(self.get_argument('password', '')):
                         logging.info("Updated %s's hashing algorithm %s -> %s" %
                             (user.handle, user.algorithm, self.get_argument('hash_algorithm'),)
                         )
                         user.algorithm = self.get_argument('hash_algorithm')
                     else:
                         errors.append("You must provide a password when updating the hashing algorithm")
             else:
                 errors.append("Not a valid hash algorithm")
             # Update password
             if 0 < len(self.get_argument('password', '')):
                 user.password = self.get_argument('password')
             # Update team
             team = Team.by_uuid(self.get_argument('team_uuid'))
             if team is not None:
                 if user.team_id != team.id:
                     logging.info("Updated %s's team %s -> %s" %
                         (user.handle, user.team_id, team.name))
                     user.team_id = team.id
             else:
                 errors.append("Team does not exist in database")
             dbsession.add(user)
             dbsession.flush()
         else:
             errors.append("User does not exist")
         self.render("admin/view/user_objects.html", errors=errors)
     else:
         self.render("admin/view/user_objects.html", errors=form.errors)
开发者ID:mach327,项目名称:RootTheBox,代码行数:60,代码来源:AdminHandlers.py

示例9: __queue__

 def __queue__(self):
     ''' Starts a job or leaves it in the queue (thread safe) '''
     logging.debug("Attempting to acquire queue mutex ...")
     self.mutex.acquire()
     logging.debug("Successfully acquired queue mutex.")
     queue = list(Job.queue())  # Create a copy of the queue
     for job in queue:
         logging.info("Dispatching job: %s" % job.job_name)
         if len(job) == 0:
             job.status = u"COMPLETED"
             dbsession.add(job)
             dbsession.flush()
         else:
             algo = Algorithm.by_id(job.algorithm_id)
             weapon_systems = WeaponSystem.system_ready(algo)
             if weapon_systems is not None and 0 < len(weapon_systems):
                 logging.info("Weapon systems available: %d" % (
                     len(weapon_systems),
                 ))
                 thread.start_new_thread(
                     self.__crack__, 
                     (job, weapon_systems[0],)
                 )
             else:
                 logging.info("No available weapon systems at this time.")
     self.mutex.release()
开发者ID:DJHartley,项目名称:The-Planetary-Assault-System,代码行数:26,代码来源:Dispatch.py

示例10: score_bots

def score_bots():
    ''' Award money for botnets ''' 
    logging.info("Scoring botnets, please wait ...")
    bot_manager = BotManager.instance()
    event_manager = EventManager.instance()
    for team in Team.all():
        if len(team.members) > 0:
            bots = bot_manager.by_team(team.name)
            if 0 < len(bots):
                reward = 0
                for bot in bots:
                    try:
                        reward += options.bot_reward
                        bot.write_message({
                            'opcode': 'status',
                            'message': 'Collected $%d reward' % options.bot_reward
                        })
                    except:
                        logging.info(
                            "Bot at %s failed to respond to score ping" % bot.remote_ip
                        )

                message = "%s was awarded $%d for controlling %s bot(s)" % (
                    team.name, reward, len(bots),
                )
                bot_manager.add_rewards(team.name, options.bot_reward)
                bot_manager.notify_monitors(team.name)
                team.money += reward
                dbsession.add(team)
                dbsession.flush()
                event_manager.bot_scored(team, message)
    dbsession.commit()
开发者ID:moloch--,项目名称:RootTheBox,代码行数:32,代码来源:Scoreboard.py

示例11: create_boxes

def create_boxes(parent, corporation):
    ''' Create boxes for a corporation '''
    logging.info("Found %s boxes" % parent.get('count'))
    for index, box_elem in enumerate(parent.getchildren()):
        try:
            name = get_child_text(box_elem, 'name')
            game_level = GameLevel.by_number(box_elem.get('gamelevel'))
            if game_level is None:
                logging.warning("GameLevel does not exist for box %s, skipping" % name)
            elif Box.by_name(name) is None:
                box = Box(corporation_id=corporation.id)
                box.name = name
                box.game_level_id = game_level.id
                box.difficulty = get_child_text(box_elem, 'difficulty')
                box.description = get_child_text(box_elem, 'description')
                box.operating_system = get_child_text(box_elem, 'operatingsystem')
                box.avatar = get_child_text(box_elem, 'avatar').decode('base64')
                box.garbage = get_child_text(box_elem, 'garbage')
                dbsession.add(box)
                dbsession.flush()
                create_flags(get_child_by_tag(box_elem, 'flags'), box)
                create_hints(get_child_by_tag(box_elem, 'hints'), box)
            else:
                logging.info("Box with name %s already exists, skipping" % name)
        except:
            logging.exception("Failed to import box %d" % (index + 1))
开发者ID:AdaFormacion,项目名称:RootTheBox,代码行数:26,代码来源:xmlsetup.py

示例12: post

 def post(self, *args, **kwargs):
     ''' Change user password '''
     user = self.get_current_user()
     old_password = self.get_argument('old_password', None)
     pass1 = self.get_argument('pass1', None)
     pass2 = self.get_argument('pass2', None)
     if old_password is None or pass1 is None or pass2 is None:
         self.render('veil/settings.html', 
             errors=['Fill in all the forms']
         )
     elif len(pass1) < 12 or len(pass2) < 12:
         self.render('veil/settings.html', 
             errors=['New password too short  (min. 12)']
         )
     elif pass1 != pass2:
         self.render('veil/settings.html',
             errors=['New passwords do not match']
         )
     elif user.validate_password(old_password):
         user.password = pass1
         dbsession.add(user)
         dbsession.flush()
         self.render('veil/settings.html', errors=[])
     else:
         self.render('veil/settings.html',
             errors=['Old password incorrect']
         )
开发者ID:DJHartley,项目名称:Veil,代码行数:27,代码来源:VeilHandlers.py

示例13: create_levels

def create_levels(levels):
    ''' Create GameLevel objects based on XML data '''
    logging.info("Found %s game level(s)" % levels.get('count'))
    for index, level_elem in enumerate(levels.getchildren()):
        # GameLevel 0 is created automatically by the bootstrap
        if get_child_text(level_elem, 'number') != '0':
            try:
                number = get_child_text(level_elem, 'number')
                if GameLevel.by_number(number) is None:
                    game_level = GameLevel()
                    game_level.number = number
                    game_level.buyout = get_child_text(level_elem, 'buyout')
                    dbsession.add(game_level)
                else:
                    logging.info("GameLevel %d already exists, skipping" % number)
            except:
                logging.exception("Failed to import game level #%d" % (index + 1))
    dbsession.flush()
    game_levels = GameLevel.all()
    for index, game_level in enumerate(game_levels):
        if index + 1 < len(game_levels):
            game_level.next_level_id = game_levels[index + 1].id
            logging.info("%r -> %r" % (game_level, game_levels[index + 1]))
            dbsession.add(game_level)
    dbsession.commit()
开发者ID:AdaFormacion,项目名称:RootTheBox,代码行数:25,代码来源:xmlsetup.py

示例14: score_bots

def score_bots():
    ''' Award money for botnets '''
    logging.info("Scoring botnets, please wait ...")
    bot_manager = BotManager.Instance()
    config = ConfigManager.Instance()
    for team in Team.all():
        bots = bot_manager.by_team(team.name)
        reward = 0
        for bot in bots:
            try:
                reward += config.bot_reward
                bot.write_message({
                    'opcode': 'status',
                    'message': 'Collected $%d reward' % config.bot_reward
                })
            except:
                logging.info(
                    "Bot at %s failed to respond to score ping" % bot.remote_ip
                )
        if 0 < len(bots):
            logging.debug("%s was awarded $%d for controlling %s bot(s)" % (
                team.name, reward, len(bots),
            ))
            bot_manager.add_rewards(team.name, config.bot_reward)
            bot_manager.notify_monitors(team.name)
            team.money += reward
            dbsession.add(team)
            dbsession.flush()
开发者ID:lavalamp-,项目名称:RootTheBox,代码行数:28,代码来源:Scoreboard.py

示例15: delivered

 def delivered(cls, user_id, uuid):
     notify = dbsession.query(cls).filter(
         and_(cls.event_uuid == uuid, cls.user_id == user_id)
     ).first()
     notify.viewed = True
     dbsession.add(notify)
     dbsession.flush()
开发者ID:brutalhonesty,项目名称:RootTheBox,代码行数:7,代码来源:Notification.py


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