コード例 #1
0
ファイル: base.py プロジェクト: mijdavis2/weppy
 def validate_and_update(self, **update_fields):
     tablename = self.db._adapter.get_table(self.query)
     table = self.db[tablename]
     current._dbvalidation_record_id_ = None
     if table._unique_fields_validation_ and self.count() == 1:
         if any(
             table._unique_fields_validation_.get(fieldname)
             for fieldname in iterkeys(update_fields)
         ):
             current._dbvalidation_record_id_ = \
                 self.select(table.id).first().id
     response = Row()
     response.errors = Row()
     new_fields = copy.copy(update_fields)
     for key, value in iteritems(update_fields):
         value, error = self.db[tablename][key].validate(value)
         if error:
             response.errors[key] = '%s' % error
         else:
             new_fields[key] = value
     del current._dbvalidation_record_id_
     if response.errors:
         response.updated = None
     else:
         if not any(f(self, new_fields) for f in table._before_update):
             table._attempt_upload(new_fields)
             fields = table._listify(new_fields, update=True)
             if not fields:
                 raise SyntaxError("No fields to update")
             ret = self.db._adapter.update(tablename, self.query, fields)
             ret and [f(self, new_fields) for f in table._after_update]
         else:
             ret = 0
         response.updated = ret
     return response
コード例 #2
0
 def login_user(self, user):
     """
     login the user = db.auth_user(id)
     """
     user = Row(user)
     for key, value in user.items():
         if callable(value) or key == 'password':
             delattr(user, key)
     session.auth = sdict(user=user,
                          last_visit=request.now,
                          expiration=self.settings.expiration,
                          hmac_key=uuid())
コード例 #3
0
ファイル: engine.py プロジェクト: kooksee/weppy
 def login_user(self, user):
     """
     login the user = db.auth_user(id)
     """
     user = Row(user)
     for key, value in list(user.items()):
         if callable(value) or key == 'password':
             delattr(user, key)
     session.auth = sdict(
         user=user,
         last_visit=request.now,
         expiration=self.settings.expiration,
         hmac_key=uuid())
コード例 #4
0
 def _update_session_user(self, user):
     if global_settings.web2py_runtime_gae:
         user = Row(self.table_user()._filter_fields(user, id=True))
         delattr(user, self.settings.password_field)
     else:
         user = Row(user)
         for key in list(user.keys()):
             value = user[key]
             if callable(value) or key == self.settings.password_field:
                 delattr(user, key)
     current.session.auth = Storage(user=user,
                                    last_visit=current.request.now,
                                    expiration=self.settings.expiration,
                                    hmac_key=web2py_uuid())
     return user
コード例 #5
0
ファイル: authapi.py プロジェクト: laminko/web2py
 def _update_session_user(self, user):
     if global_settings.web2py_runtime_gae:
         user = Row(self.table_user()._filter_fields(user, id=True))
         delattr(user, self.settings.password_field)
     else:
         user = Row(user)
         for key in list(user.keys()):
             value = user[key]
             if callable(value) or key == self.settings.password_field:
                 delattr(user, key)
     current.session.auth = Storage(user=user,
                                    last_visit=current.request.now,
                                    expiration=self.settings.expiration,
                                    hmac_key=web2py_uuid())
     return user
コード例 #6
0
 def get_participante_as_row(self, id_participante):
     """
     Este método retorna um dicionário contendo os dados referentes ao participante convertidos para o formato compatível
     com o modelo no web2py.
     :param id_participante: integer,
     :return: gluon.pydal.objects.Row contendo as informações, None caso não exista participante com a id informada/erro.
     """
     if id_participante:
         participante = self.get_participante(id_participante)
         if participante:
             participante_to_row = campos_sie_lower([participante])[0]
             participante_to_row['id'] = participante_to_row['id_participante']
             # participante_to_row['carga_horaria'] = '20'; #dummy
             # participante_to_row['link_lattes'] = '???'; #dummy
             participante_to_row['descr_mail'] = participante_to_row['descr_mail'].strip()
             participante_to_row['funcao'] = participante_to_row['funcao_item']
             participante_to_row['dt_final'] = datetime.strptime(participante_to_row['dt_final'].strip(),
                                                                 '%Y-%m-%d').date() if participante_to_row[
                 'dt_final'] else None
             participante_to_row['dt_inicial'] = datetime.strptime(participante_to_row['dt_inicial'].strip(),
                                                                   '%Y-%m-%d').date() if participante_to_row[
                 'dt_inicial'] else None
             participante_row = Row(**participante_to_row)
         else:
             participante_row = None
     else:
         participante_row = None
     return participante_row
コード例 #7
0
ファイル: base.py プロジェクト: mulonemartin/weppy
 def validate_and_update(self, **update_fields):
     tablename = self.db._adapter.get_table(self.query)
     table = self.db[tablename]
     current._dbvalidation_record_id_ = None
     if table._unique_fields_validation_ and self.count() == 1:
         if any(
                 table._unique_fields_validation_.get(fieldname)
                 for fieldname in iterkeys(update_fields)):
             current._dbvalidation_record_id_ = \
                 self.select(table.id).first().id
     response = Row()
     response.errors = Row()
     new_fields = copy.copy(update_fields)
     for key, value in iteritems(update_fields):
         value, error = self.db[tablename][key].validate(value)
         if error:
             response.errors[key] = '%s' % error
         else:
             new_fields[key] = value
     del current._dbvalidation_record_id_
     if response.errors:
         response.updated = None
     else:
         if not any(f(self, new_fields) for f in table._before_update):
             table._attempt_upload(new_fields)
             fields = table._listify(new_fields, update=True)
             if not fields:
                 raise SyntaxError("No fields to update")
             ret = self.db._adapter.update(tablename, self.query, fields)
             ret and [f(self, new_fields) for f in table._after_update]
         else:
             ret = 0
         response.updated = ret
     return response
コード例 #8
0
ファイル: models.py プロジェクト: mulonemartin/weppy
 def new(cls, **attributes):
     row = Row()
     for field in cls.table.fields:
         val = attributes.get(field, cls.table[field].default)
         if callable(val):
             val = val()
         row[field] = val
     cls._inject_virtuals_on_row(row)
     return row
コード例 #9
0
 def login_user(self, user, remember=False):
     user = Row(user)
     try:
         del user.password
     except:
         pass
     expiration = remember and self.settings.long_expiration or \
         self.settings.expiration
     session.auth = sdict(user=user,
                          last_visit=request.now,
                          last_dbcheck=request.now,
                          expiration=expiration,
                          remember=remember,
                          hmac_key=uuid())
コード例 #10
0
    def get_projeto_as_row(self, id_projeto):
        """
        Este método retorna um dicionário contendo os dados referentes ao projeto convertidos para o formato compatível
        com o web2py.
        :param id_projeto: integer, id do projeto
        :return: gluon.pydal.objects.Row contendo as informações, None caso não exista projeto com a id informada/erro.
        """
        if id_projeto:
            projeto_bd = self.get_projeto(id_projeto)
            if projeto_bd:
                arquivosDAO = SIEArquivosProj()
                termo = arquivosDAO.get_termo_outorga(id_projeto)
                ata = arquivosDAO.get_ata_departamento(id_projeto)
                arquivo_proj = arquivosDAO.get_arquivo_projeto(id_projeto)
                agencia_fomento = self.get_agencia_fomento(id_projeto)

                projeto = {
                    'id_documento': projeto_bd['ID_DOCUMENTO'],
                    'num_processo': projeto_bd['NUM_PROCESSO'],
                    'titulo': projeto_bd[u'TITULO'].encode('utf-8'),
                    'resumo': projeto_bd[u'RESUMO'].encode('utf-8'),
                    'keyword_1': projeto_bd[u'PALAVRA_CHAVE01'].encode('utf-8'),
                    'keyword_2': projeto_bd[u'PALAVRA_CHAVE02'].encode('utf-8'),
                    'keyword_3': projeto_bd[u'PALAVRA_CHAVE03'].encode('utf-8') if projeto_bd[
                                                                                       u'PALAVRA_CHAVE03'] is not None else "",
                    'keyword_4': projeto_bd[u'PALAVRA_CHAVE04'].encode('utf-8') if projeto_bd[
                                                                                       u'PALAVRA_CHAVE04'] is not None else "",
                    "financeiro_apoio_financeiro": int(bool(agencia_fomento)), #agencia de fomento é uma linha de orgaos do projeto. a representacao na pagina espera um int (0 ou 1).
                # TODO Lógica cheia de gambiarra de lidar com fundações.
                    "carga_horaria": projeto_bd[u'CARGA_HORARIA'],
                    "financeiro_termo_outorga": termo,  # TODO
                    "financeiro_valor_previsto": agencia_fomento["VL_CONTRIBUICAO"] if agencia_fomento else "",
                    "financeiro_agencia_fomento": agencia_fomento["NOME_UNIDADE"].encode(
                        'utf-8').strip() if agencia_fomento else "",
                    "financeiro_id_orgao_projeto": agencia_fomento["ID_ORGAO_PROJETO"] if agencia_fomento else "",
                    "financeiro_id_origem": agencia_fomento["ID_ORIGEM"] if agencia_fomento else "",
                    "financeiro_origem": agencia_fomento["ORIGEM"] if agencia_fomento else "",
                    "ata_departamento": ata,  # TODO
                    "arquivo_projeto": arquivo_proj,  # TODO
                    'vigencia_inicio': datetime.strptime(projeto_bd[u'DT_INICIAL'], '%Y-%m-%d').date() if projeto_bd[
                        u'DT_INICIAL'] else None,
                    'vigencia_final': datetime.strptime(projeto_bd[u'DT_CONCLUSAO'], '%Y-%m-%d').date() if projeto_bd[
                        u'DT_CONCLUSAO'] else None,
                    'id': projeto_bd[u"ID_PROJETO"]
                }
                return Row(**projeto)
            else:
                return None
        return None
コード例 #11
0
 def get_orgao_as_row(self, id_orgao_projeto):
     # todo Gera dependencia de pydal. Isso realmente deveria estar aqui?
     if id_orgao_projeto:
         orgao_bd = self.get_orgao(id_orgao_projeto)
         if orgao_bd:
             orgao_dict = {
                 'nome': orgao_bd[u'NOME_UNIDADE'].encode('utf-8'),
                 'descricao_origem': "UNIRIO" if orgao_bd[u"ORIGEM"] == "ID_UNIDADE" else "Externo",
                 'funcao_orgao': orgao_bd[u"FUNCAO_ORG_ITEM"],
                 "valor": orgao_bd[u'VL_CONTRIBUICAO'],
                 'participacao_inicio': datetime.strptime(orgao_bd[u'DT_INICIAL'], '%Y-%m-%d').date() if orgao_bd[
                     u'DT_INICIAL'] else None,
                 'participacao_fim': datetime.strptime(orgao_bd[u'DT_FINAL'], '%Y-%m-%d').date() if orgao_bd[
                     u'DT_FINAL'] else None,
                 'observacao': orgao_bd[u'OBS_ORG_PROJETO'].encode('utf-8'),
                 'id': orgao_bd[u"ID_ORGAO_PROJETO"]
             }
             orgao_row = Row(**orgao_dict)
             return orgao_row
     return None
コード例 #12
0
    def _login_with_handler(self, handler, env=None):
        if not issubclass(handler, AuthLoginHandler):
            raise RuntimeError('Provided handler for login is invalid')

        settings = self.settings
        passfield = settings.password_field
        log = self.messages['login_log']

        # redirect user if it's already logged in
        if self.user:
            redirect(self.settings.login_next or self.url('profile'))

        handler = handler(self, env)

        # use session for federated login
        snext = get_vars_next()
        if snext:
            session._auth_next = snext
        elif session._auth_next:
            snext = session._auth_next

        if handler.next is None:
            unext = settings.login_next or self.url('profile')
            if snext:
                unext = snext
        else:
            unext = handler.next

        #: init handler form if required
        #  note: we need to load the form before calling `get_user()`, as the
        #        handler could use the form itself to init the user var
        loginform = None
        if hasattr(handler, 'login_form'):
            loginform = handler.login_form()
        #: get user from handler
        user = handler.get_user()
        if user:
            if not handler.store_password:
                user[passfield] = None
            if handler.create_user_onlogin:
                user = self.get_or_create_user(
                    self.table_user._filter_fields(user),
                    settings.update_fields)
        #: return form if required
        elif loginform is not None:
            return loginform
        #: use external login url
        else:
            redirect(handler.login_url(unext))

        #: process authenticated users
        user = Row(self.table_user._filter_fields(user, id=True))
        self.login_user(user)
        #: use the right session expiration
        session.auth.expiration = \
            request.vars.get('remember', False) and \
            settings.long_expiration or \
            settings.expiration
        session.auth.remember = 'remember' in request.vars
        #: log login
        self.log_event(log, user)
        #: handler callback
        handler.onsuccess()

        #: clean session next
        if unext == session._auth_next:
            del session._auth_next
        #: proceed
        redirect(unext)
コード例 #13
0
ファイル: base.py プロジェクト: mulonemartin/weppy
 def insert(self, position, obj):
     row = Row({self.compact_tablename: obj}) if self.compact else obj
     self.records.insert(position, row)
コード例 #14
0
ファイル: base.py プロジェクト: mulonemartin/weppy
 def append(self, obj):
     row = Row({self.compact_tablename: obj}) if self.compact else obj
     self.records.append(row)