Ejemplo n.º 1
0
class PersonApiHandler(ApiSecureHandler):
    object_cls = Person
    def after_save(self,data_dict):
        if hasattr(self.object,'is_new') and self.object.is_new:
            self._queue_actions.update({'new_user':{'user_id':self.object.id}})
    
    def object_load_dict(self,o,data_dict):
        'http post handle args'
        if 'attributes' in data_dict:
            attr_list = []
            if isinstance(data_dict['attributes'],list):
                attr_list = data_dict['attributes']
            elif isinstance(data_dict['attributes'],dict):
                attr_list = [data_dict['attributes']]
            for attr in attr_list:
                object_type = "attribute" if not 'object_type' in attr else attr['object_type']
                category = "attribute"  if not 'category' in attr else attr['category']
                encoding = 'str' if not 'encoding' in attr else attr['encoding']
                o.add_attribute(attr['name'],attr['value'],object_type=object_type,
                    encoding=encoding,category=category)
            data_dict.pop('attributes')
        if 'delete_attributes' in data_dict:
            for attr in data_dict['delete_attributes']:
                ua = o.get_attribute(attr['name'])
                log.debug('deletting attribute = id=%s, name=%s' % (ua.id, ua.name))
                ua.delete()
            data_dict.pop('delete_attributes')
        return data_dict
    
    def change_email(self):
        self.handle_post()
    
    def delete_by_get(self):
        self.action_get_object(self.id)
        if self.object and hasattr(self.object,'delete'):
            url = self.request.full_url()
            log.debug("DELETE id=%s for url=%s" % (self.id,url))
            self.object.delete()
            cache.cache.delete(cache.cache_key(url))
            self.object = None
            self.qry = []
            self.set_status(204)
        else:
            log.error("not found?   %s, %s" % (self.noun, self.id))
    
    def action_get_object(self,id, data_dict = {}):
        if isinstance(self.id,int) and self.id > 0:
            #meta.DBSession.close()
            #meta.DBSession()
            self.object = Person.get(self.site.id,self.id)
            if not self.object:
                # ??
                self.object = Person.by_foreignid(self.site.id,self.id)
        elif isinstance(self.id,int) and self.id == 0 and 'email' in data_dict:
            self.object = Person.by_email(self.site.id,data_dict['email'].lower())
        elif 'foreign_id' in data_dict:
            self.object = Person.by_foreignid(self.site.id,data_dict['foreign_id'])
        else:
            id = urllib.unquote_plus(self.id)
            if mailsrch.match(id):
                self.object = Person.by_email(self.site.id,id)
            else:
                self.object = Person.by_hashedemail(self.site.id,id)
            log.debug('getting by hashed/email:  %s, %s' % (id, self.object))
        if self.object:
            self.qry = [self.object]
    
    def json_formatter(self,o):
        if o:
            return o.to_dict_api()
        return None
    
    def action_get_list(self,q=None):
        if q:
            qry = self.db.session.query(Person).filter(and_(
                Person.name.like('%' + q + '%'),Person.is_anonymous==1))
        else:
            qry = self.db.session.query(Person).filter(and_(Person.site_id==self.site.id))
        self.qry = qry
    
    def pre_init_user(self):
        """A push to pre-initiate session (step 1) optional
        body of json to add/update user"""
        user = None
        user_dict = {}
        if self.request.method == 'POST':
            if self.is_json_post():
                user_dict = json.loads(self.request.body)
            else:
                user_dict = self.args_todict()
            log.debug("Loaded data user_dict=%s" % user_dict)
            self.action_get_object(self.id, user_dict)
            if not self.object:
                log.debug("creating new user, not found %s dict=%s" % (self.id,user_dict))
                self.object = Person(site_id=self.site.id,foreign_id=self.id)
            
            if self.object:
                self.object.from_dict(user_dict,allowed_keys=Person._allowed_api_keys)
                self.object.save()
                if hasattr(self.object,'is_new') and self.object.is_new:
                    self._queue_actions.update({'new_user':{'user_id':self.object.id}})
            
        else:
            self.action_get_object(self.id)
        
        if self.object:
            user_key = self.object.id
            log.debug("setting cache = %s, %s" % (str(user_key),self.site.key))
            self.db.cache.set(str(user_key),self.site.key,120) # 2 minutes only
            site_key = self.db.cache.get(str(user_key))
            log.debug("site_key, self.site.key = %s, %s" % (site_key, self.site.key))
            assert site_key == self.site.key
            
            self.qry = [self.object]
    
    def options(self,site_slug='',format='json'):
        log.debug("in person api OPTIONS")