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


Python db_session.add函数代码示例

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


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

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

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

示例3: insert_data

    def insert_data(self, data):
        """
        Will handle inserting data into the database
        """
        try:
            # Check if book is in database, if so update else create
            try:
                book = db_session.query(Book).filter(Book.book_id == data.get('book_id')).one()
            except NoResultFound:
                book = Book()

            book.title = data.get('title')
            book.subtitle = data.get('subtitle')
            book.author = data.get('author')
            book.year = data.get('year')
            book.pages = data.get('pages')
            book.language = data.get('language')
            book.publisher = data.get('publisher')
            book.isbn = data.get('isbn')
            book.format = data.get('format')
            book.description = data.get('description')
            book.file_source = data.get('file_source')
            book.file_cover_source = data.get('file_cover_source')
            book.file_location = data.get('file_location')
            book.file_cover_location = data.get('file_cover_location')
            book.book_id = data.get('book_id')
            book.time_collected = data.get('time_collected')

            db_session.add(book)
            db_session.commit()
            # self.track_stat('rows_added_to_db', rows_affected)

        except Exception:
            db_session.rollback()
            logger.exception("Error adding to db {data}".format(data=data))
开发者ID:xtream1101,项目名称:scrape-itebooks,代码行数:35,代码来源:it-ebooks.py

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

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

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

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

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

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

示例10: create_comment

    def create_comment(self, content, user, ip, commit=False):
        ref_name = get_remote_side(self, 'comments')
        
        cls = get_remote_side_class(self, 'comments')

        # verify that the user has not created any comment for this article within the last 30s
        # TODO: cache this shit
        last_comment = cls.query.filter_by(ip=hash(ip)).order_by(cls.date_created.desc()).first()

        if last_comment:
            time_diff = now_ms() - last_comment.date_created
            limit = self.comment_limit

            if time_diff < limit:
                raise ModelException(
                    type='VALIDATION_FAILED',
                    message=_(u'Please wait %(time)s seconds before sending new comment', time=int(round((limit-time_diff)/1000)))
                )

        comment = cls()
        setattr(comment, ref_name, self.id)
        comment.user_id = user.id
        comment.content = content
        comment.ip = hash(ip)

        # also update the comment count
        cache.update_user_comment_count(self, user.id)

        db_session.add(comment)

        if commit:
            db_session.commit()

        return comment
开发者ID:laoshanlung,项目名称:flask-demo,代码行数:34,代码来源:commentable.py

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

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

示例13: create_book

def create_book():
    book = Book(request.form['title'], request.form['repo_url'])
    db_session.add(book)
    db_session.commit()
    book_for_user = BookForUser(book.id, g.user.id, request.form['branch'])
    db_session.add(book_for_user)
    db_session.commit()
    return redirect(url_for('index'))
开发者ID:yattom,项目名称:yomoyama,代码行数:8,代码来源:views.py

示例14: _save_session

 def _save_session(self, hostname, user):
   """make_room(新規ゲーム), join_room(参加表明)のとき、会員のFQDNとIPアドレスを記録する。"""
   try:
     ipaddr = unicode(socket.gethostbyname(hostname))
   except socket.gaierror: # DNSが引けないとかネット切断とか
     ipaddr = None
   db_session.add(Session(int(time.time()), hostname, ipaddr, user.id))
   db_session.flush()
开发者ID:rakou1986,项目名称:tamahiyo,代码行数:8,代码来源:services.py

示例15: save_access_token

 def save_access_token(self, client_key, access_token, request_token,
         realm=None, secret=None):
     token = AccessToken(access_token, secret=secret, realm=realm)
     token.client = Client.query.filter_by(client_key=client_key).one()
     req_token = RequestToken.query.filter_by(token=request_token).one()
     token.resource_owner = req_token.resource_owner
     token.realm = req_token.realm
     db_session.add(token)
     db_session.commit()
开发者ID:felixhummel,项目名称:flask-oauthprovider,代码行数:9,代码来源:provider.py


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