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


Python DBSession.add方法代码示例

本文整理汇总了Python中alchemist.models.base.DBSession.add方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.add方法的具体用法?Python DBSession.add怎么用?Python DBSession.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在alchemist.models.base.DBSession的用法示例。


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

示例1: setUp

# 需要导入模块: from alchemist.models.base import DBSession [as 别名]
# 或者: from alchemist.models.base.DBSession import add [as 别名]
    def setUp(self):
        from sqlalchemy import create_engine

        engine = create_engine('sqlite://')
        try:
            # nosetest vs pycharm test runner, lets flex
            settings = get_appsettings('../tests.ini')
        except:
            settings = get_appsettings('tests.ini')
        self.config = testing.setUp(settings=settings)
        DBSession.configure(bind=engine)
        Base.metadata.create_all(engine)
        with transaction.manager:
            self.founder = User(username='founder', password='apass', email='[email protected]', activated=True,
                                active=True, firstname='founder1_firstname', lastname='founder1_lastname',
                                city='founder1_city', state='founder1_state', title='founder1_title')
            self.company = BaseCompany(name='testcompany', founded=2015, description='company_desc',
                                       startup_teamdescription='company_team_desc', website='company_website',
                                       linkedin='company_linkedin', twitterhandle='company_twitter',
                                       angelcoprofile='company_angellist')
            self.admin = User(username='admin', password='apass', email=settings.get('admin_mail'), activated=False,
                              groups='admin')
            DBSession.add(self.founder)
            DBSession.add(self.company)
            DBSession.add(self.admin)
            for k, v in Settings.settings.iteritems():
                if type(v) == dict:
                    DBSession.add(Settings(key=unicode(k), value=unicode(v['value'])))
                else:
                    if isinstance(v, basestring) and v.startswith('app_config.'):
                        v = settings.get(v[len('app_config.'):])
                    DBSession.add(Settings(key=unicode(k), value=unicode(v)))
            DBSession.flush()
            self.user_id = self.founder.user_id
        self.founders_created = []
开发者ID:umar93132,项目名称:portal,代码行数:37,代码来源:tests.py

示例2: handle_if_company

# 需要导入模块: from alchemist.models.base import DBSession [as 别名]
# 或者: from alchemist.models.base.DBSession import add [as 别名]
def handle_if_company(k, v, required=True, request=False):
    from alchemist.models.base import DBSession
    from alchemist.models.company import BaseCompany
    from alchemist.models.settings import Settings

    if k in ['company', 'company_id']:
        is_name = False
        try:
            company_id = int(v)
            company = DBSession.query(BaseCompany).get(company_id)
        except:
            v = v.replace(new_company_text, '')
            company = DBSession.query(BaseCompany).filter(BaseCompany.name == v).first()
            if not company:
                company = DBSession.query(BaseCompany).filter(BaseCompany.name.startswith(v.strip())).first()
            is_name = True
        assert not required or company, 'The company does not exist.'
        if not company and is_name:
            company = BaseCompany()
            company.name = v
            if request and request.referer and 'add/founder' in request.referer:
                company.is_alchemist = True
                company.alchemistclass = int(Settings.get('alchemistclass'))
                company.companytype = 'startup'
            DBSession.add(company)
            DBSession.flush()
        return company.id if k == 'company_id' else company
    return v
开发者ID:umar93132,项目名称:portal,代码行数:30,代码来源:misc.py

示例3: add_empty_connection

# 需要导入模块: from alchemist.models.base import DBSession [as 别名]
# 或者: from alchemist.models.base.DBSession import add [as 别名]
def add_empty_connection(request):
    user = User(primary_type='base')
    user.activated = True
    user.login_enabled = False
    DBSession.add(user)
    DBSession.flush()
    return HTTPFound('/base/%s' % user.id)
开发者ID:RaHus,项目名称:portal,代码行数:9,代码来源:administration.py

示例4: create_conn

# 需要导入模块: from alchemist.models.base import DBSession [as 别名]
# 或者: from alchemist.models.base.DBSession import add [as 别名]
def create_conn(by_user_id, to_id):
    try:
        conn = Connection(by_user_id=by_user_id, user_id=to_id)
    except:
        logging.error('Please specify by_user_id and to_id fields', exc_info=1)
        return
    DBSession.add(conn)
    DBSession.flush()
    _, conn.code = gen_ver_code(conn.id, 14)
    return conn
开发者ID:RaHus,项目名称:portal,代码行数:12,代码来源:connect_me.py

示例5: company

# 需要导入模块: from alchemist.models.base import DBSession [as 别名]
# 或者: from alchemist.models.base.DBSession import add [as 别名]
 def company(self, value):
     if self.company and value and self.company.id == value.id:
         return
     if self.company:
         DBSession.query(UserXCompany).filter(UserXCompany.company == self.company,
                                              UserXCompany.user == self,
                                              UserXCompany.end_date == None). \
             update({'end_date': utcnow().datetime})
     DBSession.add(UserXCompany(company=value, user=self, start_date=utcnow().datetime,
                                relation=TypeOfRelation.employee))
开发者ID:RaHus,项目名称:portal,代码行数:12,代码来源:user.py

示例6: mark_unwanted

# 需要导入模块: from alchemist.models.base import DBSession [as 别名]
# 或者: from alchemist.models.base.DBSession import add [as 别名]
def mark_unwanted(request):
    unwanted_user = int(request.matchdict.get('user_id'))
    weekly_focus = request.user.weekly_focus.lower().replace(' ', '_')
    rp = request.POST.get
    DBSession.add(UnWanted(by_user=request.user, user_id=unwanted_user,
                           weekly_focus=weekly_focus, connected=rp('connected') == 'true',
                           rating=rp('rating'), feedback=rp('feedback')))
    cache = get_region('main')
    cache.invalidate()
    return HTTPFound(request.referer or '/')
开发者ID:umar93132,项目名称:portal,代码行数:12,代码来源:actions.py

示例7: vote_to_answer

# 需要导入模块: from alchemist.models.base import DBSession [as 别名]
# 或者: from alchemist.models.base.DBSession import add [as 别名]
def vote_to_answer(request):
    aid = request.POST.get('aid', -1)
    answer = DBSession.query(Answers).filter(Answers.id == aid).first()
    vote = DBSession.query(AnswerVotes).filter(AnswerVotes.answer_id == aid).filter(
        AnswerVotes.user_id == request.user.id).first()
    if vote is not None:
        DBSession.delete(vote)
    else:
        vote = AnswerVotes(answer=answer, user=request.user)
        DBSession.add(vote)
    vote_count = DBSession.query(func.count(AnswerVotes.id)).filter(AnswerVotes.answer_id == aid).scalar()
    return {'votes': vote_count}
开发者ID:RaHus,项目名称:portal,代码行数:14,代码来源:questions.py

示例8: add_company_to_notablecustomers_view

# 需要导入模块: from alchemist.models.base import DBSession [as 别名]
# 或者: from alchemist.models.base.DBSession import add [as 别名]
def add_company_to_notablecustomers_view(request):
    if request.method == 'POST':
        current_company_id = request.POST.get('company_id', False)
        current_company = DBSession.query(BaseCompany).filter(BaseCompany.id == current_company_id).first()
        assert current_company, 'The company you are trying to edit does not exist'
        new_company_name = request.POST.get('name')
        new_company = BaseCompany(name=new_company_name)
        DBSession.add(new_company)
        current_company.notablecustomers.append(new_company)
        return {'item': current_company,
                'is_my_comp': request.user and request.user.company_id and
                              request.user.company_id == current_company.id}
开发者ID:RaHus,项目名称:portal,代码行数:14,代码来源:administration.py

示例9: add_user_view

# 需要导入模块: from alchemist.models.base import DBSession [as 别名]
# 或者: from alchemist.models.base.DBSession import add [as 别名]
def add_user_view(request):
    utype = request.matchdict.get('type')
    user = {'type': utype}
    company_match = False
    if request.method == 'POST':
        try:
            user = User()
            for k, v in request.POST.iteritems():
                if v == 'on':
                    v = True
                v = {'true': True, 'false': False}.get(v, v)
                v = Tag.handle_if_tags(k, v)
                if k == 'company_id' or k == 'company':
                    try:
                        company_match = getattr(request.user, k) == int(v)
                    except:
                        company_match = request.user.company.name == v.strip() if request.user.company else False
                        v = v.replace(' - Add new company', '')
                    assert company_match or request.user.is_admin, \
                        'You just tried to add an user to a company You don\'t have access to. You can\'t do that!'
                    k = 'company'
                v = handle_if_company(k, v, required=False, request=request)
                v = handle_file_save('%s_adm_cr_%s' % (getattr(user, 'nicename', user.id),
                                                       request.authenticated_userid), v)
                setattr(user, k, v)

            plain_pass, _ = gen_ver_code(user.nicename)
            user.password = plain_pass
            user.activated = True
            user.login_enabled = False
            user.primary_type = utype
            if not user.username:
                user.username = user.email
            _, user.ver_code = gen_ver_code('signup_%s' % user.id)

            DBSession.add(user)
            DBSession.flush()
            admin_emails = Settings.get('admin_mail')
            send_mail(admin_emails, 'roleadd', request, {'user': user,
                                                         'new_role': utype})
            user.send_mail('invite', request, {'plain_pass': plain_pass,
                                               'user_id': user.id,
                                               'hash': user.ver_code})
            request.session.flash('Successfully added a new %s' % (
                'Team Member' if company_match else str(user.primary_type).capitalize()))
            url = '/%s/%s' % (user.primary_type, user.id)
            return HTTPFound(url)
        except Exception, e:
            request.session.flash('Error: %s' % e.message, 'error')
            if request.referer:
                return HTTPFound(request.referer)
            raise
开发者ID:RaHus,项目名称:portal,代码行数:54,代码来源:administration.py

示例10: addto_track

# 需要导入模块: from alchemist.models.base import DBSession [as 别名]
# 或者: from alchemist.models.base.DBSession import add [as 别名]
def addto_track(request):
    qid = request.POST.get('qid', -1)
    question = DBSession.query(Questions).filter(Questions.id == qid).first()
    bookmark_ = (request.POST.get('type') == 'bookmark')
    existed = DBSession.query(Trackers).filter(Trackers.questions_id == qid).filter(
        Trackers.tracker_id == request.user.id,
        Trackers.is_bookmark == bookmark_).first()
    if existed:
        DBSession.delete(existed)
        return {'type': 'removed'}
    else:
        tracker = Trackers(tracker=request.user, question=question, is_bookmark=bookmark_)
        DBSession.add(tracker)
        return {'type': 'added'}
开发者ID:RaHus,项目名称:portal,代码行数:16,代码来源:questions.py

示例11: add_answer

# 需要导入模块: from alchemist.models.base import DBSession [as 别名]
# 或者: from alchemist.models.base.DBSession import add [as 别名]
def add_answer(request):
    editor_tags = ['ul', 'li', 'ol', 'strong', 'em', 'p', 'hr', 'span', 'del', 'a', 'br']
    answer_text = bleach.clean(request.POST.get('answer', ''), editor_tags, {
        "*": ["style"],
        "img": ["src", "width", "height"],
    }, styles=['text-align'])
    qid = request.POST.get('qid', -1)
    question = DBSession.query(Questions).filter(Questions.id == qid).first()
    had_answers = len(question.answers)
    answer = Answers(user=request.user, question=question, text=answer_text)
    answer.created_at = datetime.now()  # TODO put as default (also for question)
    DBSession.add(answer)
    DBSession.flush()
    scheduler.add_job(send_emails_immediate_answer, next_run_time=now(scheduler.timezone).replace(seconds=+30).datetime,
                      kwargs={'answer_id': answer.id, 'attr_name': 'answer_notification',
                              'nice_type': 'New Answer', 'type': 'Answer'})
    return HTTPFound('/exchange/%s/show%s' % (qid, '?first_answer=1' if had_answers == 0 else '?answered=1'))
开发者ID:RaHus,项目名称:portal,代码行数:19,代码来源:questions.py

示例12: add_question

# 需要导入模块: from alchemist.models.base import DBSession [as 别名]
# 或者: from alchemist.models.base.DBSession import add [as 别名]
def add_question(request):
    question = {}
    if request.method == 'POST':
        questiontext = bleach.clean(request.POST.get('questiontext'), strip=True)
        str_tags = request.POST.get('hidTags')
        question = Questions(text=questiontext, user=request.user)
        question.tags = Tag.handle_if_tags('tags', str_tags)
        question.created_at = datetime.now()
        DBSession.add(question)
        tracker = Trackers(tracker=request.user, question=question, is_bookmark=False)
        DBSession.add(tracker)
        DBSession.flush()  # make sure there's no DB Errors before sending out the emails
        scheduler.add_job(send_emails_immediate_question,
                          next_run_time=now(scheduler.timezone).replace(seconds=+30).datetime,
                          kwargs={'question_id': question.id, 'attr_name': 'question_notification',
                                  'nice_type': 'New Question Asked', 'type': 'Question'})

    return {'question': question, 'now': now(request.registry.settings.get('scheduler.timezone'))}
开发者ID:RaHus,项目名称:portal,代码行数:20,代码来源:questions.py

示例13: __getattribute__

# 需要导入模块: from alchemist.models.base import DBSession [as 别名]
# 或者: from alchemist.models.base.DBSession import add [as 别名]
 def __getattribute__(self, name):
     if 'tags' in name:
         name = 'tags'
     try:
         return super(UserMixin, self).__getattribute__(name)
     except AttributeError:
         if not self._user and self.user_id:
             self._user = User.bid(self.user_id)
         if not self._user:
             self._user = User()
             DBSession.add(self._user)
             DBSession.flush()
             self.user_id = self._user.id
         if name == 'type':
             return self._user.type.split(',')
         return getattr(self._user, name)
     except DetachedInstanceError:
         DBSession.add(self._user)
         return super(UserMixin, self).__getattribute__(name)
开发者ID:umar93132,项目名称:portal,代码行数:21,代码来源:user.py

示例14: __setattr__

# 需要导入模块: from alchemist.models.base import DBSession [as 别名]
# 或者: from alchemist.models.base.DBSession import add [as 别名]
 def __setattr__(self, name, value):
     if name == 'user_id':
         if not self._user:
             self._user = DBSession.query(User).get(value)
         types = self._user.type.split(',')
         types.append(self.__tablename__)
         self._user.type = ','.join(set(types))
         return super(UserMixin, self).__setattr__(name, value)
     if 'tags' in name:
         name = 'tags'
     if hasattr(User, name):
         if not self._user and self.user_id:
             self._user = DBSession.query(User).get(self.user_id)
         if not self._user:
             _user = User()
             DBSession.add(_user)
             DBSession.flush()
             self.user_id = _user.id
         else:
             DBSession.add(self._user)
         try:
             return setattr(self._user, name, value)
         except DetachedInstanceError:
             DBSession.add(self._user)
             return setattr(self._user, name, value)
     else:
         return super(UserMixin, self).__setattr__(name, value)
开发者ID:umar93132,项目名称:portal,代码行数:29,代码来源:user.py

示例15: main

# 需要导入模块: from alchemist.models.base import DBSession [as 别名]
# 或者: from alchemist.models.base.DBSession import add [as 别名]
def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)
    with transaction.manager:
        user = User(username='admin', password='apass', email=settings.get('admin_mail'), activated=True,
                    groups='admin')
        DBSession.add(user)
        DBSession.flush()
        for k, v in Settings.settings.iteritems():
            if type(v) == dict:
                DBSession.add(Settings(key=unicode(k), value=unicode(v['value'])))
            else:
                if isinstance(v, basestring) and v.startswith('app_config.'):
                    v = settings.get(v[len('app_config.'):])
                DBSession.add(Settings(key=unicode(k), value=unicode(v)))

        DBSession.flush()
开发者ID:RaHus,项目名称:portal,代码行数:27,代码来源:initializedb.py


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