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


Python session.flush函数代码示例

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


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

示例1: rate

    def rate(self, query_id, rating, *args, **kwargs):
        '''
            Rates the chat. Updates user score and statistics.
            
            @param query_id: needed to identify chat session 
            @param rate:  points given
        '''
        cs = ChatSession.select(ChatSession.c.query_id==query_id)[0];

        if not cs.user_id == identity.current.user.user_id:
            return dict()

        cs.rating = int(rating)
        cs.status = "RATED"
        
        session.save(cs);
        session.flush();

        expert=session.query(User).get_by(user_id=int(cs.expert_id))
        
        stats = expert.user_stats

        new_value=round(stats.average_rating*stats.no_of_ques_answered_rated)
        stats.no_of_ques_answered_rated+=1
        stats.average_rating=(new_value+float(rating))/stats.no_of_ques_answered_rated
        stats.score=round(stats.no_of_ques_answered_rated * stats.average_rating + stats.no_of_blog_ratings * stats.average_blog_rating)
        session.flush();

        return dict()
开发者ID:macagua,项目名称:SPREE,代码行数:29,代码来源:chat_controller.py

示例2: remove

 def remove(self, **kw):
     item = ConfigItem.by_id(kw['id'])
     item.set(None, None, identity.current.user)
     session.add(item)
     session.flush()
     flash(_(u"%s cleared") % item.description)
     raise redirect(".")
开发者ID:beaker-project,项目名称:beaker,代码行数:7,代码来源:configuration.py

示例3: test_abort_recipe_bubbles_status_to_job

    def test_abort_recipe_bubbles_status_to_job(self):
        xmljob = XmlJob(xmltramp.parse('''
            <job>
                <whiteboard>job </whiteboard>
                <recipeSet>
                    <recipe>
                        <distroRequires>
                            <distro_name op="=" value="BlueShoeLinux5-5" />
                        </distroRequires>
                        <hostRequires/>
                        <task name="/distribution/install" role="STANDALONE">
                            <params/>
                        </task>
                    </recipe>
                </recipeSet>
                <recipeSet>
                    <recipe>
                        <distroRequires>
                            <distro_name op="=" value="BlueShoeLinux5-5" />
                        </distroRequires>
                        <hostRequires/>
                        <task name="/distribution/install" role="STANDALONE">
                            <params/>
                        </task>
                    </recipe>
                </recipeSet>
            </job>
            '''))
        job = self.controller.process_xmljob(xmljob, self.user)
        session.flush()
        for recipeset in job.recipesets:
            for recipe in recipeset.recipes:
                recipe.process()
                recipe.queue()
                recipe.schedule()
                recipe.waiting()

        # Abort the first recipe.
        job.recipesets[0].recipes[0].abort()
        job.update_status()

        # Verify that it and its children are aborted.
        self.assertEquals(job.recipesets[0].recipes[0].status, TaskStatus.aborted)
        for task in job.recipesets[0].recipes[0].tasks:
            self.assertEquals(task.status, TaskStatus.aborted)

        # Verify that the second recipe and its children are still waiting.
        self.assertEquals(job.recipesets[1].recipes[0].status, TaskStatus.waiting)
        for task in job.recipesets[1].recipes[0].tasks:
            self.assertEquals(task.status, TaskStatus.waiting)

        # Verify that the job still shows waiting.
        self.assertEquals(job.status, TaskStatus.waiting)

        # Abort the second recipe now.
        job.recipesets[1].recipes[0].abort()
        job.update_status()

        # Verify that the whole job shows aborted now.
        self.assertEquals(job.status, TaskStatus.aborted)
开发者ID:ShaolongHu,项目名称:beaker,代码行数:60,代码来源:test_update_status.py

示例4: test_group_removal_is_noticed

    def test_group_removal_is_noticed(self):
        self.group.systems.append(self.system)
        session.flush()
        b = self.browser
        login(b)
        b.get(get_server_base() + 'groups/')
        b.find_element_by_xpath("//input[@name='group.text']").clear()
        b.find_element_by_xpath("//input[@name='group.text']").send_keys(self.group.group_name)
        b.find_element_by_id('Search').submit()
        delete_and_confirm(b, "//tr[td/a[normalize-space(text())='%s']]" % self.group.group_name,
            'Remove')
        should_have_deleted_msg = b.find_element_by_xpath('//body').text
        self.assert_('%s deleted' % self.group.display_name in should_have_deleted_msg)

        # Check it's recorded in System Activity
        b.get(get_server_base() + 'activity/system')
        b.find_element_by_link_text('Show Search Options').click()
        b.find_element_by_xpath("//select[@id='activitysearch_0_table']/option[@value='Action']").click()
        b.find_element_by_xpath("//select[@id='activitysearch_0_operation']/option[@value='is']").click()
        b.find_element_by_xpath("//input[@id='activitysearch_0_value']").send_keys('Removed')
        b.find_element_by_link_text('Add').click()

        b.find_element_by_xpath("//select[@id='activitysearch_1_table']/option[@value='Old Value']").click()
        b.find_element_by_xpath("//select[@id='activitysearch_1_operation']/option[@value='is']").click()
        b.find_element_by_xpath("//input[@id='activitysearch_1_value']").send_keys(self.group.display_name)
        b.find_element_by_id('searchform').submit()
        self.assert_(is_activity_row_present(b,via='WEBUI', action='Removed',
             old_value=self.group.display_name, new_value='',
             object_='System: %s' % self.system.fqdn))
开发者ID:ustbgaofan,项目名称:beaker,代码行数:29,代码来源:test_activity.py

示例5: create_job_for_recipes

def create_job_for_recipes(recipes, owner=None, whiteboard=None, cc=None,product=None,
        retention_tag=None, group=None, submitter=None, priority=None, **kwargs):
    if retention_tag is None:
        retention_tag = RetentionTag.by_tag(u'scratch') # Don't use default, unpredictable
    else:
        retention_tag = RetentionTag.by_tag(retention_tag)

    if owner is None:
        owner = create_user()
    if whiteboard is None:
        whiteboard = unique_name(u'job %s')
    job = Job(whiteboard=whiteboard, ttasks=sum(r.ttasks for r in recipes),
        owner=owner, retention_tag=retention_tag, group=group, product=product,
        submitter=submitter)
    if cc is not None:
        job.cc = cc
    if priority is None:
        priority = TaskPriority.default_priority()
    recipe_set = RecipeSet(ttasks=sum(r.ttasks for r in recipes),
            priority=priority)
    recipe_set.recipes.extend(recipes)
    job.recipesets.append(recipe_set)
    session.add(job)
    session.flush()
    log.debug('Created %s', job.t_id)
    return job
开发者ID:sujithshankar,项目名称:beaker,代码行数:26,代码来源:data_setup.py

示例6: update_setting

 def update_setting(self, *args, **kwargs):
     '''
         Updates user settings.
         
         @param **kwargs: contains information about anonymity, sending a queries by email and newsletter 
     '''
     
     user = User.get_by(User.c.user_id==identity.current.user.user_id)
     s = user.getSettings()
     
     if kwargs['anonymous'] == "true":
         s.anonymous = 1
         user.display_name = "anonymous";
     else:
         s.anonymous = 0
         user.display_name = user.user_name;
                 
     if kwargs['email'] == "true":
         s.email = 1
     else:
         s.email = 0
         
     if kwargs['newsletter'] == "true":
         s.newsletter = 1
     else:
         s.newsletter = 0
                               
     session.save(user);
     session.save(s);
     session.flush();
     return dict()
开发者ID:macagua,项目名称:SPREE,代码行数:31,代码来源:profile_controller.py

示例7: _handle_historical

def _handle_historical(session, data,myth_uuid):
    showcount = 0
    rectime = 0
    db_age = 0
    reccount = 0
    try:
        myth_hist = data['features']['historical']
    except:
        myth_hist = {}

    #session.query(mythtvHistorical).filter_by(machine_id = machine_id).delete()
    session.query(mythtvHistorical).filter_by(myth_uuid = myth_uuid).delete()

    try:
        showcount = myth_hist['showcount']
    except:
        pass

    try:
        rectime = myth_hist['rectime']
    except:
        pass
    try:
        db_age = myth_hist['db_age']
    except:
        pass
    try:
        reccount = myth_hist['reccount']
    except:
        pass

    session.add(mythtvHistorical(myth_uuid,
                                 showcount,rectime,db_age,reccount)
                                 )
    session.flush()
开发者ID:MythTV,项目名称:smolt,代码行数:35,代码来源:client_impl_mythtv.py

示例8: deleteQuery

    def deleteQuery(self, query_id, *args, **kwargs):
        '''
            Allows user to delete a query. Updates query logging.
            
            @param query_id: identifies the query
            @return: status of attempted  delete operation of the query
        '''
        
        query = session.query(Query).get_by(query_id=int(query_id))
        
        status = ""
        
        if not query:
            status = "Query not found"
        elif session.query(ChatSession).get_by(query_id=int(query_id)):
            status = "Chat already started"
        elif query.user_id != identity.current.user.user_id:
            status = "Permission denied"
        else:
            query.experts[:] = []
            query_log=QueryLog(
                query_id = int(query_id),
                user_id = query.user_id,
                user_name = session.query(User).get_by(user_id=query.user_id).user_name,
                created = datetime.now(),
                status = 'Deleted')

            session.save(query_log)
            session.flush()
            session.delete(query);
            session.flush();
            
        return dict(status=status)    
开发者ID:macagua,项目名称:SPREE,代码行数:33,代码来源:search_controller.py

示例9: add_ssh_public_key

def add_ssh_public_key(username):
    """
    Adds a new SSH public key for the given user account.

    Accepts mimetype:`text/plain` request bodies containing the SSH public key 
    in the conventional OpenSSH format: <keytype> <key> <ident>.

    :param username: The user's username.
    """
    user = _get_user(username)
    if not user.can_edit(identity.current.user):
        raise Forbidden403('Cannot edit user %s' % user)
    if request.mimetype != 'text/plain':
        raise UnsupportedMediaType415('Request content type must be text/plain')
    with convert_internal_errors():
        keytext = request.data.strip()
        if '\n' in keytext:
            raise ValueError('SSH public keys may not contain newlines')
        elements = keytext.split(None, 2)
        if len(elements) != 3:
            raise ValueError('Invalid SSH public key')
        key = SSHPubKey(*elements)
        user.sshpubkeys.append(key)
        session.flush() # to populate id
    return jsonify(key.__json__())
开发者ID:beaker-project,项目名称:beaker,代码行数:25,代码来源:user.py

示例10: rate_object

    def rate_object(self, **kwargs):
        #log.info('args = %s' % str(args))
        #log.info('kwargs = %s' % str(kwargs))
        id = kwargs.get("ratingID")
        rating = kwargs.get("value")
        print "ID: %s" % id
        print "RATING: %s" % rating
        if id.startswith("Host"):
            sep = id.find("@")
            if sep == -1:
                host_id = id[4:]
                host = session.query(Host).filter_by(uuid=host_id).one()
                host.rating = int(rating)
                session.flush()
                return dict()

            host_id = id[4:sep]
            id = id[sep+1:]
            if id.startswith("Device"):
                device_id = int(id[6:])
                host = session.query(Host).filter_by(uuid=host_id).one()
                for device in host.devices:
                    if device.device_id == device_id:
                        device.rating = int(rating)
                        session.flush([host, device])
                        return dict()
        return dict()
开发者ID:MythTV,项目名称:smolt,代码行数:27,代码来源:client_impl.py

示例11: isOnline

    def isOnline(self):
        '''
            @return: Boolean (true if user is online).
        '''
        user_stats = self.user_stats
        
        # reload if status is old
        if not user_stats.isOnlineLastUpdated or user_stats.isOnlineLastUpdated < datetime.now() - timedelta(seconds = constants.isOnlineExpire):
            t=[]
            visit=session.query(Visit).select(and_(VisitIdentity.c.visit_key == Visit.c.visit_key, self.user_id == VisitIdentity.c.user_id))
            isOnline = 0
            for v in visit:
                t.append(v.expiry)
            t.sort()
            t.reverse()
            if len(t) > 0 and datetime.now()<t[0]:
                isOnline = 1

            user_stats.isOnline = isOnline
            user_stats.isOnlineLastUpdated = datetime.now()
            
            session.save(user_stats)
            session.flush()
            
        return user_stats.isOnline == 1
开发者ID:macagua,项目名称:SPREE,代码行数:25,代码来源:model.py

示例12: add_json_plus_pub_uuid

 def add_json_plus_pub_uuid(self, uuid, pub_uuid, host, token, smolt_protocol):
     self._run_add_json_checks(uuid, host, token, smolt_protocol)
     res = self.handle_submission(uuid, pub_uuid, host)
     log_entry = BatchJob(host, uuid, added=True)
     session.add(log_entry)
     session.flush()
     return res
开发者ID:MythTV,项目名称:smolt,代码行数:7,代码来源:client_impl.py

示例13: system_command

def system_command(fqdn):
    system = _get_system_by_FQDN(fqdn)
    if not system.lab_controller:
        raise BadRequest400('System is not attached to a lab controller')
    if not system.can_power(identity.current.user):
        raise Forbidden403('You do not have permission to control this system')
    # We accept JSON or form-encoded for convenience
    if request.json:
        if 'action' not in request.json:
            raise BadRequest400('Missing action key')
        action = request.json['action']
    elif request.form:
        if 'action' not in request.form:
            raise BadRequest400('Missing action parameter')
        action = request.form['action']
    else:
        raise UnsupportedMediaType415
    if action == 'reboot':
        raise BadRequest400('"reboot" is not a valid power command, '
                'send "off" followed by "on" instead')
    elif action in ['on', 'off', 'interrupt']:
        if not system.power:
            raise BadRequest400('System is not configured for power support')
        command = system.action_power(service=u'HTTP', action=action)
    elif action == 'clear_netboot':
        command = system.clear_netboot(service=u'HTTP')
    else:
        raise BadRequest400('Unknown action %r' % action)
    session.flush() # for created attribute
    return jsonify(command.__json__())
开发者ID:sujithshankar,项目名称:beaker,代码行数:30,代码来源:systems.py

示例14: reject

    def reject(self, person_name):
        """Reject a user's FPCA.

        This method will remove a user from the FPCA group and any other groups
        that they are in that require the FPCA.  It is used when a person has
        to fulfill some more legal requirements before having a valid FPCA.

        Arguments
        :person_name: Name of the person to reject.
        """
        show = {}
        show["show_postal_address"] = config.get("show_postal_address")
        exc = None
        user = People.by_username(turbogears.identity.current.user_name)
        if not is_admin(user):
            # Only admins can use this
            turbogears.flash(_("You are not allowed to reject FPCAs."))
            exc = "NotAuthorized"
        else:
            # Unapprove the cla and all dependent groups
            person = People.by_username(person_name)
            for role in person.roles:
                if self._cla_dependent(role.group):
                    role.role_status = "unapproved"
            try:
                session.flush()
            except DBAPIError, error:
                turbogears.flash(
                    _("Error removing cla and dependent groups" " for %(person)s\n Error was: %(error)s")
                    % {"person": person_name, "error": str(error)}
                )
                exc = "DBAPIError"
开发者ID:fedora-infra,项目名称:fas,代码行数:32,代码来源:fpca.py

示例15: test_job_priority_changes

    def test_job_priority_changes(self):
        user1 = data_setup.create_user()
        user2 = data_setup.create_user()
        job1 = data_setup.create_job(owner=user1)
        job2 = data_setup.create_job(owner=user1)
        job3 = data_setup.create_job(owner=user2)
        job4 = data_setup.create_job(owner=user2)

        for j in [job1, job2, job3]:
            for rs in j.recipesets:
                activity = RecipeSetActivity(j.owner,
                                             'TEST',
                                             'Changed',
                                             'Priority',
                                             rs.priority.value,
                                             TaskPriority.high)
                activity.created = datetime.datetime(year=2012,
                                                     month=10,
                                                     day=10)
                rs.activity.append(activity)
        session.flush()

        rows = self.execute_reporting_query('job-priority-changes-by-user')
        all_rows = rows.fetchall()
        user1_rows = [row for row in all_rows if row.user_name == user1.user_name]
        user2_rows = [row for row in all_rows if row.user_name == user2.user_name]

        self.assertTrue(user1_rows[0].number_of_jobs_changed, 2)
        self.assertTrue(user2_rows[0].number_of_jobs_changed, 1)
开发者ID:beaker-project,项目名称:beaker,代码行数:29,代码来源:test_reporting_queries.py


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