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

Python db_session.commit函数代码示例

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

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



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


示例16: handleRegister

 def handleRegister(self):
     """
     处理用户注册
     :return:
     """
     name, email, pwd = self.postParams('name', 'email', 'pwd')
     if self.checkParamsAvailable(email, pwd):
         exists_query = db_session.query(User).filter(User.email==email).exists()
         if not db_session.query(exists_query).scalar():
             try:
                 set_user = User()
                 set_user.name = name
                 set_user.email = email
                 set_user.salt = User.genSalt()
                 set_user.pwd = User.genPassword(pwd, set_user.salt)
                 set_user.reg_ip = str(request.remote_addr)
                 db_session.add(set_user)
                 db_session.commit()
                 self.changeResponse2Success()
                 mailer = getMailSender()
                 mailer.setMailtoList([email])
                 mailer.setSubject("感谢注册 [史前-在线定量研究工具]")
                 _mail_content = render_template("noticer/email/_register.html", nickname=name)
                 mailer.setContent(_mail_content)
                 mailer.send()
             except Exception as e:
                 db_session.rollback()
                 self.setFailureReason(str(e))
         else:
             self.setFailureReason("该邮箱已经被注册,请更换邮箱申请或尝试找回密码!")
开发者ID:caimmy,项目名称:prehistory,代码行数:30,代码来源:userinfo_operation.py


示例17: edit_event

def edit_event(request, event_id):
    '''
    INPUT
    Member object in the request to check permissions.  Also an Event form in order to
    update the contents of this one.

    RESULT
    If all goes well, event is edited and returns True.  Otherwise, an Exception.
    '''

    # First, grab the event and its group.
    this_event = Event.query.get(event_id)
    this_group = Group.query.get(this_event.group_id)

    # Now, use the form parameters to update the Event.
    this_event.name = request.form['name']
    this_event.start_time = request.form['start_time']
    this_event.end_time = request.form['end_time']
    this_event.location = request.form['location']
    this_event.description = request.form['description']
    this_event.visible_to_uninvited = request.form['visible_to_uninvited']
    this_event.invited_can_invite = request.form['invited_can_invite']

    # Nope, need to actively update both the hosting Roles and hosting Members.  Then call a function on
    # the Event class, update_hosts_by_roles(), which updates the Members whenever the Roles change.
    this_event.hosting_members = [Member.query.get(member_id) for member_id in request['host_members']]
    new_hosting_roles = [Role.query.get(role_id) for role_id in request.form['host_roles']]
    if new_hosting_roles != this_event.hosting_roles:
        this_event.hosting_roles = new_hosting_roles
        this_event.update_hosts_by_roles()

    db_session.add(this_event)
    db_session.commit()
开发者ID:john-osullivan,项目名称:groupbot,代码行数:33,代码来源:event.py


示例18: update_current_order

 def update_current_order(id,new_status_id, new_delivery_id=None, new_delivery_address=None, new_comment=None):
     entry = Order.get_order(id)
     entry.status_id = new_status_id
     entry.delivery_id = new_delivery_id
     entry.delivery_address = new_delivery_address
     entry.comment = new_comment
     db_session.commit()
开发者ID:NTsvyatkov,项目名称:itacademy,代码行数:7,代码来源:order_dao.py


示例19: event_invite

def event_invite(request, event_id):
    '''
    INPUT
    There needs to be a member object in the request, but this is not the Member being invited.
    The Member in the request is the User doing the inviting, and needs to be verified to make
    sure they have Permission to invite people.  The Member being invited is contained in
    request.form['member'].  The event, of course, comes from the URL.

    RESULT
    The specified Member is added to the Event's 'invited' relationship.  It returns True if
    everything goes the same way.
    '''
    # Grab the standard Group and Member so we know who and where the request is coming from.
    this_event = Event.query.get(event_id)
    inviting_member = Member.query.filter_by(user_id=current_user.user_id, group_id=this_event.group_id).first()
    # Check to make sure the inviting Member is a host.
    if this_event.is_host(inviting_member):

        # First, we need to update the Members who are invited.  The form field returns a list of codenames.
        this_event.invited_members = [Member.query.filter_by(group_id=this_event.group_id, codename=membername).first()
                                      for membername in request.form['invited_members']]

        # Next, check if the invited Roles need updating.  If the values are updated, make sure to call
        # the Event's update_invited_members_after_role_change() function. The current behavior is that
        # changing the Roles will reset the Member invitations to be accurate with the change -- No Exceptions.
        new_roles = [Role.query.get(role_id) for role_id in request.form['invited_roles']]
        if new_roles != this_event.invited_roles:
            this_event.update_invited_by_roles()

        db_session.add(this_event)
        db_session.commit()
    else:
        raise Exception("That Member can't invite someone, they're not a host!")
开发者ID:john-osullivan,项目名称:groupbot,代码行数:33,代码来源:event.py


示例20: event_rsvp

def event_rsvp(request, event_id, member_id):
    '''
    INPUT
    Member object in the request to make sure they were invited to begin with. Other
    than that, the event_id is enough to work things out.

    RESULT
    The Member is added to the Event's .rsvp_yes attribute.  The function returns
    True to confirm successful operation, Exception if it fails.
    '''
    # Grab the standard Group and Member so we know who and where the request is coming from.

    # Grab the event and validate where the guest was even invited.
    # ...
    # Because *God*, does she even go here?
    this_event = Event.query.get(event_id)
    rsvp_member = Member.query.get(member_id)
    if rsvp_member in this_event.invited:
        attending = request.form['attending']
        if attending: # Note, this works specifically because the form's value for Yes is True.
            this_event.rsvp_yes.append(rsvp_member)
        else:
            this_event.rsvp_no.append(rsvp_member)
        db_session.commit()
    else:
        return Exception("That member wasn't even invited to this event!")
开发者ID:john-osullivan,项目名称:groupbot,代码行数:26,代码来源:event.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python db_session.query函数代码示例发布时间:2022-05-27
下一篇:
Python db_session.add函数代码示例发布时间: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