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


Python dbsession.flush函数代码示例

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


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

示例1: 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

示例2: create_game_level

def create_game_level(number, buyout):
    ''' Creates a GameLevel object '''
    if GameLevel.by_number(number) is not None:
        logging.info("Game level #%s already exists, skipping" % number)
        return GameLevel.by_number(number)
    logging.info("Create Game Level #%s with a buyout of $%s" % (
        number, buyout
    ))
    new_level = GameLevel(
        number=abs(int(number)),
        buyout=abs(int(buyout)),
    )
    game_levels = GameLevel.all()
    game_levels.append(new_level)
    logging.debug("Updating game level linked list ...")
    game_levels = sorted(game_levels)
    index = 0
    for level in game_levels[:-1]:
        level.next_level_id = game_levels[index + 1].id
        dbsession.add(level)
        index += 1
    game_levels[0].number = 0
    dbsession.add(game_levels[0])
    game_levels[-1].next_level_id = None
    dbsession.add(game_levels[-1])
    dbsession.flush()
    return new_level
开发者ID:CRYPTOlab,项目名称:RootTheBox,代码行数:27,代码来源:helpers.py

示例3: 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

示例4: create_flag

def create_flag(name, token, value, box, description="No description", is_file=False):
    if Flag.by_name(name) is not None:
        logging.info("Flag with name '%s' already exists, skipping" % (name))
        return Flag.by_name(name)
    if Flag.by_token(token) is not None:
        logging.info("Flag with token '%s' already exists, skipping" % (token))
        return Flag.by_token(token)
    if is_file and os.path.exists(token):
        with open(token) as favatar:
            _token = Flag.digest(favatar.read())
    elif is_file and 40 == len(token):
        _token = unicode(token)  # Just assume it's a SHA1
    elif is_file:
        raise ValueError("Flag token file does not exist, and is not a hash.")
    else:
        _token = unicode(token[:256])
    logging.info("Create Flag: %s" % name)
    flag = Flag(
        name=unicode(name[:32]),
        token=_token,
        is_file=is_file,
        description=unicode(description[:256]),
        value=abs(int(value)),
        box_id=box.id,
    )
    dbsession.add(flag)
    dbsession.flush()
    return flag
开发者ID:CRYPTOlab,项目名称:RootTheBox,代码行数:28,代码来源:helpers.py

示例5: post_avatar

 def post_avatar(self, *args, **kwargs):
     '''
     Saves avatar - Reads file header an only allows approved formats
     '''
     user = User.by_id(self.session['user_id'])
     if 'avatar' in self.request.files:
         if len(self.request.files['avatar'][0]['body']) < (1024 * 1024):
             if user.avatar == "default_avatar.jpeg":
                 user.avatar = unicode(uuid4()) + u".jpeg"
             ext = imghdr.what(
                 "", h=self.request.files['avatar'][0]['body']
             )
             avatar_path = str(self.application.settings['avatar_dir'] + '/' + user.avatar)
             if ext in ['png', 'jpeg', 'gif', 'bmp']:
                 if os.path.exists(avatar_path):
                     os.unlink(avatar_path)
                 user.avatar = unicode(user.avatar[:user.avatar.rfind('.')] + "." + ext)
                 file_path = str(self.application.settings['avatar_dir'] + '/' + user.avatar)
                 avatar = open(file_path, 'wb')
                 avatar.write(self.request.files['avatar'][0]['body'])
                 avatar.close()
                 dbsession.add(user)
                 dbsession.flush()
                 self.render_page(success=["Successfully changed avatar"])
             else:
                 self.render_page(
                     errors=["Invalid image format, avatar must be: .png .jpeg .gif or .bmp"]
                 )
         else:
             self.render_page(errors=["The image is too large"])
     else:
         self.render_page(errors=["Please provide an image"])
开发者ID:CRYPTOlab,项目名称:RootTheBox,代码行数:32,代码来源:UserHandlers.py

示例6: 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

示例7: 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

示例8: query_plugins

 def query_plugins(self, weapon_system, rpc):
     if 0 < len(weapon_system.plugins):
         self.output += "[-] Clearing old plugin(s) ...\n"
         for old_plugin in weapon_system.plugins:
             dbsession.delete(old_plugin)
         dbsession.flush()
     self.output += "[*] Attempting to detect remote plugin(s) ...\n"
     for algo in Algorithm.all():
         self.output += "[+] Looking for %s plugins ..." % algo
         plugin_names = rpc.root.exposed_get_category_plugins(algo.name)
         self.output += " found %d\n" % len(plugin_names)
         for plugin_name in plugin_names:
             self.output += "[+] Query info from remote plugin '%s'\n" % plugin_name
             details = rpc.root.exposed_get_plugin_details(algo.name, plugin_name)
             plugin = PluginDetails(
                 name=unicode(plugin_name),
                 author=unicode(details['author']),
                 website=unicode(details['website']),
                 version=unicode(details['version']),
                 description=unicode(details['description']),
                 copyright=unicode(details['copyright']),
             )
             plugin.precomputation = details['precomputation']
             plugin.algorithm_id = algo.id
             weapon_system.plugins.append(plugin)
开发者ID:DJHartley,项目名称:The-Planetary-Assault-System,代码行数:25,代码来源:AdminHandlers.py

示例9: 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

示例10: 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

示例11: 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

示例12: 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

示例13: 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

示例14: post

 def post(self, *args, **kwargs):
     ''' Attempt to upgrade hash algo '''
     form = Form(
         old_password="Enter your existing password",
         new_password1="Enter a new password",
         new_password2="Confirm your new password",
     )
     if form.validate(self.request.arguments):
         user = self.get_current_user()
         passwd = self.get_argument('new_password1')
         old_passwd = self.get_argument('old_password')
         if not user.validate_password(old_passwd):
             self.render_page(["Invalid password"])
         elif not passwd == self.get_argument('new_password2'):
             self.render_page(["New passwords do not match"])
         elif user.team.money < self.config.password_upgrade:
             self.render_page(["You cannot afford to upgrade your hash"])
         elif len(passwd) <= self.config.max_password_length:
             user.team.money -= self.config.password_upgrade
             dbsession.add(user.team)
             dbsession.flush()
             self.update_password(passwd)
             self.render_page()
         else:
             self.render_page(["New password is too long"])
     else:
         self.render_page(form.errors)
开发者ID:brutalhonesty,项目名称:RootTheBox,代码行数:27,代码来源:UpgradeHandlers.py

示例15: 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


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