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


Python db_session.commit函数代码示例

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


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

示例1: createNewUser

 def createNewUser(login, password, first_name, last_name, email, role_id, region_id):
     user = UserDao(login, hashlib.md5(password).hexdigest(), first_name, last_name, email, role_id, region_id)
     if role_id == RoleDao.get_role_id_by_name("Customer"):
         user.level_id = UserLevel.get_level_id_by_name("Standard")
         user.balance = 0
     db_session.add(user)
     db_session.commit()
开发者ID:NTsvyatkov,项目名称:itacademy,代码行数:7,代码来源:user_dao.py

示例2: breakup

 def breakup(self, json):
   """解散、強制解散"""
   args = loads(json)
   print args
   user = self._whoami(args["caller"])
   if user is None:
     return dumps((False,))
   pr = self._is_room_owner(args["channel"], args["caller"])
   if (not pr) and (not args["force"]):
     return dumps((False,))
   if (not pr) and args["force"]:
     q = db_session.query(GeneralRecord
       ).filter(GeneralRecord.active==True
       ).filter(GeneralRecord.room_number==args["room_number"]
       ).filter(GeneralRecord.channel==args["channel"])
     try:
       gr = q.one()
     except NoResultFound:
       return dumps((False,))
   else:
     gr = pr.general_record
   members = self._execute_breakup(gr)
   returns = self._construct_room_info(gr, user)
   returns.update({"members": [self._construct_member_info(pr) for pr in members]})
   db_session.commit()
   return dumps((True, returns))
开发者ID:rakou1986,项目名称:tamahiyo,代码行数:26,代码来源:services.py

示例3: users_self_update_password

def users_self_update_password(user):
    schema = {
        "type": "object",
        "properties": {
            "encrypted_private_key": {"type": "string"},
            "aes_iv": {"type": "string"},
            "pbkdf2_salt": {"type": "string"},
            "auth_key": {"type": "string"},
        },
        "required": ["encrypted_private_key", "aes_iv", "pbkdf2_salt",
            "auth_key"]
    }

    error = validate_schema(request.json, schema)
    if error:
        return error

    u = User.query.get(user.id)

    user.encrypted_private_key = request.json["encrypted_private_key"]
    user.aes_iv = request.json["aes_iv"]
    user.pbkdf2_salt = request.json["pbkdf2_salt"]
    user.auth_hash = bcrypt.hashpw(request.json["auth_key"].encode("UTF-8"),
        bcrypt.gensalt()).decode("UTF-8")

    db_session.commit()

    return jsonify(success=True)
开发者ID:camerongray1515,项目名称:Multi-User-Password-Locker,代码行数:28,代码来源:server.py

示例4: vote

def vote():
    topic = g.topic
    data = request.get_json()
    up = data.get('up', True)

    try:
        vote = topic.vote(user=g.user, ip=request.remote_addr, up=up)
        if vote.id:
            # this is an updated vote
            if vote.changed:
                points = topic.update_points(up=up, points=2)
                topic.user.update_points(up=up, points=6)
            else:
                points = topic.points
        else:
            # this is a new vote
            points = topic.update_points(up)
            user_points = 1
            if up:
                user_points = 5
            topic.user.update_points(up=up, points=user_points)
        
        db_session.commit()
        data = {
            "points": points
        }

        cache.update_topic(topic.id, topic)
        cache.update_sorted_topics(topic, 'points')
        return jsonify({"data": data})
    except Exception, e:
        logging.error(e)
        db_session.rollback()
        return json_error_database()
开发者ID:laoshanlung,项目名称:flask-demo,代码行数:34,代码来源:api_topics.py

示例5: register

 def register(self):
     if request.method == u'POST':
         client_key = self.generate_client_key()
         secret = self.generate_client_secret()
         # TODO: input sanitisation?
         name = request.form.get(u"name")
         description = request.form.get(u"description")
         callback = request.form.get(u"callback")
         pubkey = request.form.get(u"pubkey")
         # TODO: redirect?
         # TODO: pubkey upload
         # TODO: csrf
         info = {
             u"client_key": client_key,
             u"name": name,
             u"description": description,
             u"secret": secret,
             u"pubkey": pubkey
         }
         client = Client(**info)
         client.callbacks.append(Callback(callback))
         client.resource_owner = g.user
         db_session.add(client)
         db_session.commit()
         return render_template(u"client.html", **info)
     else:
         clients = g.user.clients
         return render_template(u"register.html", clients=clients)
开发者ID:felixhummel,项目名称:flask-oauthprovider,代码行数:28,代码来源:provider.py

示例6: send

    def send(self):
        """
        发送邮件
        :return:
        """
        ret_oper = False
        recvers = ";".join(self.mailto_list)
        try:
            smtp_server = smtplib.SMTP()
            smtp_server.connect(self.smtp_host, self.smtp_port)
            smtp_server.login(self.smtp_user, self.smtp_pwd)
            msg = MIMEText(self.content, "html", "utf-8")
            msg['Subject'] = self.subject
            msg['From'] = MAIL_SENDER
            msg['To'] = recvers
            smtp_server.sendmail(self.sender, recvers, msg.as_string())
            ret_oper = True
        except Exception as e:
            pass
        finally:
            try:
                mail_log = EmailLog()
                mail_log.recver = ";".join(self.mailto_list)
                mail_log.subject = self.subject
                mail_log.content = self.content
                mail_log.status = EmailLog.STATUS_SEND_SUCCESS if ret_oper else EmailLog.STATUS_SEND_FAILURE
                db_session.add(mail_log)
                db_session.commit()
            except Exception as e:
                db_session.rollback()
            smtp_server.quit()

        return ret_oper
开发者ID:caimmy,项目名称:prehistory,代码行数:33,代码来源:mail_helper.py

示例7: vote

def vote():
    article = g.article
    data = request.get_json()
    up = data.get('up', True)

    try:
        vote = article.vote(user=g.user, ip=request.remote_addr, up=up)
        if vote.id:
            # this is an updated vote
            if vote.changed:
                points = article.update_points(up=up, points=2)
                article.user.update_points(up=up, points=11)
            else:
                points = article.points
        else:
            # this is a new vote
            points = article.update_points(up)
            user_points = 1
            if up:
                user_points = 10
            article.user.update_points(up=up, points=user_points)
        
        db_session.commit()
        data = {
            "points": points
        }

        cache.update_article(article.id, article)
        cache.update_sorted_articles(article, 'points')
        return jsonify({"data": data})
    except Exception, e:
        logging.error(e)
        db_session.rollback()
        return json_error_database()
开发者ID:laoshanlung,项目名称:flask-demo,代码行数:34,代码来源:api_articles.py

示例8: comment_create

def comment_create():
    data = request.get_json()
    article = g.article
    
    form = CommentForm(**data)
    if form.validate():
        form_data = form.data
        form_data['user'] = g.user
        form_data['ip'] = request.remote_addr

        try:
            comment = article.create_comment(**form_data)
            article.update_comment_count()
            article.update_user_comment_count(user_id=comment.user_id)

            db_session.commit()

            cache.update_article(article.id, article)
            cache.update_sorted_articles(article, 'comment_count')
            return jsonify({"data": comment.json_data()})
        except ModelException, me:
            db_session.rollback()
            return json_error(type=me.type, messages=me.message)
        except Exception, e:
            logging.error(e)
            db_session.rollback()
            return json_error_database()
开发者ID:laoshanlung,项目名称:flask-demo,代码行数:27,代码来源:api_articles.py

示例9: handleAddGeoUnit

 def handleAddGeoUnit(self):
     """
     处理往地理坐标集合上添加坐标点的工作
     :return:
     """
     gid, geo_name, longitude, latitude, desc, area, high, map_type = \
         self.postParams("gid", "geo_name", "longitude", "latitude", "desc", "area", "high", "map_type")
     if self.checkParamsAvailable(gid, geo_name, longitude, latitude, desc, area, high, map_type):
         try:
             current_user = UserIdentify.getCurrentUser()
             geo_unit = GeoPointUnit()
             geo_unit.group_id = gid
             geo_unit.name = geo_name
             geo_unit.longitude = longitude
             geo_unit.latitude = latitude
             geo_unit.desc = desc
             geo_unit.map_type = map_type
             if str(high).isdigit():
                 geo_unit.high = high
             else:
                 geo_unit.high = 0
             if str(area).isdigit():
                 geo_unit.area = area
             else:
                 geo_unit.area = 0
             geo_unit.u_id = current_user.get('uid', 0)
             db_session.add(geo_unit)
             db_session.commit()
             self.changeResponse2Success()
         except Exception as e:
             db_session.rollback()
             self.setFailureReason(str(e))
开发者ID:caimmy,项目名称:prehistory,代码行数:32,代码来源:archgis_operation.py

示例10: handleRemoveGeopointGroup

 def handleRemoveGeopointGroup(self):
     """
     删除指定的整个地理坐标集合
     需要校验地理坐标集合是否属于操作者本人
     :return:
     """
     gid, pwd = self.postParams("gid", "pwd")
     if self.checkParamsAvailable(gid, pwd):
         if self.userIdentification(pwd):
             current_user = UserIdentify()
             geo_group_info = db_session.query(GeoPointGroup).filter(GeoPointGroup.id==gid).first()
             if geo_group_info is not None:
                 if (geo_group_info.u_id == current_user.uid):
                     try:
                         # 删除集合下的所有观察子节点
                         db_session.query(GeoPointUnit).filter(GeoPointUnit.group_id==gid).delete()
                         db_session.delete(geo_group_info)
                         db_session.commit()
                         self.changeResponse2Success()
                     except Exception as e:
                         self.setFailureReason(str(e), redirect_url=url_for(".ViewGeoGroup", gid=gid))
                 else:
                     self.setFailureReason("该地理坐标点位集合不属于您,无法执行删除操作!", redirect_url=url_for(".ViewGeoGroup", gid=gid))
             else:
                 self.setFailureReason("指定的地理坐标点位集合不存在!", redirect_url=url_for(".ViewGeoGroup", gid=gid))
         else:
             self.setFailureReason("对不起,您不具备执行当前操作的权限!", redirect_url=url_for(".ViewGeoGroup", gid=gid))
开发者ID:caimmy,项目名称:prehistory,代码行数:27,代码来源:archgis_operation.py

示例11: handleUpdateProjectDataRecord

 def handleUpdateProjectDataRecord(self):
     '''
     更新研究项目中的一行数据
     :return:
     '''
     _data_dict = self.postParams("*")
     if "pid" in _data_dict and "row_id" in _data_dict:
         try:
             project_id = int(_data_dict.get("pid", 0))
             row_id = _data_dict.get("row_id", '')
         except Exception:
             project_id = 0
         if project_id > 0 and '' != row_id:
             try:
                 db_session.query(ProjectItem).filter(ProjectItem.proj_id==project_id).filter(ProjectItem.row_id==row_id).delete()
                 for _d in _data_dict:
                     if "pid" != _d and "row_id" != _d:
                         pproperty_item = db_session.query(ProjectProperty).filter(ProjectProperty.label==_d).first()
                         if pproperty_item is not None:
                             p_item = ProjectItem()
                             p_item.label = _d
                             p_item.value = _data_dict[_d]
                             p_item.row_id = row_id
                             p_item.proj_id = project_id
                             p_item.p_id = pproperty_item.id
                             db_session.add(p_item)
                 db_session.commit()
                 self.changeResponse2Success()
             except Exception as e:
                 db_session.rollback()
                 self.setFailureReason(str(e))
     else:
         self.setFailureReason('缺少关键参数!')
开发者ID:caimmy,项目名称:prehistory,代码行数:33,代码来源:arghlaborary_operation.py

示例12: handleAddProjectDataRecord

 def handleAddProjectDataRecord(self):
     _data_dict = self.postParams("*")
     if "pid" in _data_dict:
         try:
             project_id = int(_data_dict.get('pid'))
         except Exception as e:
             project_id = 0
         if project_id > 0:
             row_num = str(uuid1())
             try:
                 for _d in _data_dict:
                     if "pid" != _d:
                         pproperty_item = db_session.query(ProjectProperty).\
                             filter(ProjectProperty.label==_d).\
                             filter(ProjectProperty.p_id==project_id).first()
                         if pproperty_item is not None:
                             p_item = ProjectItem()
                             p_item.label = _d
                             p_item.value = _data_dict[_d]
                             p_item.row_id = row_num
                             p_item.proj_id = project_id
                             p_item.p_id = pproperty_item.id
                             db_session.add(p_item)
                 db_session.commit()
                 self.changeResponse2Success()
             except Exception as e:
                 db_session.rollback()
                 self.setFailureReason(str(e))
开发者ID:caimmy,项目名称:prehistory,代码行数:28,代码来源:arghlaborary_operation.py

示例13: update_view_count

    def update_view_count(self, ip, user=None, commit=False):
        """Updates the view count of the entry. The view count is only updated once very 2 hours to avoid duplication
        Args:
            ip (str): an ip address of the current user_id
            user (User): the current user (None if it is a guest)
            commit (bool): whether to commit changes
        Returns
            True if view_count is updated
            False otherwise
        """
        updated = False
        last_view = self._last_ip_view(hash(ip))
        threshold = 2*3600*1000 # update view_count once very 2 hours
        diff = now_ms() - last_view
        if diff == 0 or diff > threshold:
            cls = self.__class__
            self.query.filter_by(id=self.id).update({cls.view_count: cls.view_count + 1})
            updated = True
            if commit:
                db_session.commit()

        # add the entry to user log
        if user is not None:
            self._update_user_view_log(user.id)

        return updated
开发者ID:laoshanlung,项目名称:flask-demo,代码行数:26,代码来源:loggable.py

示例14: leave_room

 def leave_room(self, json):
   """退室。ホストが抜けたら解散"""
   args = loads(json)
   print args
   pr = self._is_room_owner(args["channel"], args["caller"])
   if pr:
     members = self._execute_breakup(pr.general_record)
   else:
     user = self._whoami(args["caller"])
     if user is None:
       return dumps((False,))
     pr = self._get_active_pr(user)
     if pr is None:
       return dumps((False,))
     if pr.general_record.channel != args["channel"]:
       return dumps((False,))
     pr.active = False
     pr.leaved = True
   pr.general_record.umari_at = None
   pr.general_record.rating_match = None
   db_session.commit()
   returns = self._construct_room_info(pr.general_record, pr.user)
   if pr.general_record.brokeup:
     returns.update({"members": [self._construct_member_info(pr) for pr in members]})
   return dumps((True, returns))
开发者ID:rakou1986,项目名称:tamahiyo,代码行数:25,代码来源:services.py

示例15: folders_add

def folders_add(user):
    if not user.admin:
        return error_response("not_admin", "You must be an administrator to "
            "add a folder")

    schema = {
        "type": "object",
        "properties": {
            "name": {"type": "string"}
        },
        "required": ["name"]
    }

    error = validate_schema(request.json, schema)
    if error:
        return error

    folder = request.json

    if not folder.get("name").strip():
        return error_response("input_validation_fail", "You must supply a name "
            "for this folder");

    if Folder.query.filter(Folder.name==folder.get("name")).count():
        return error_response("already_exists", "A folder with that name "
            "already exists")

    f = Folder(name=folder.get("name"))
    db_session.add(f)
    db_session.commit()

    return jsonify(success=True, folder_id=f.id)
开发者ID:camerongray1515,项目名称:Multi-User-Password-Locker,代码行数:32,代码来源:server.py


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