Beispiel #1
0
 def get(self, user_id):
     from google.appengine.api.urlfetch import fetch
     token = self.request.get('fb_token')
     user = SFUser.user_by_user_id_and_fb_token(user_id, token)
     if user is not None:
         self.respond({'secret': user.secret, 'status': True})
     else:
         try:
             response = fetch('https://graph.facebook.com/me?access_token=%s' % token)
             me_data = JSONDecoder().decode(response.content)
             if me_data.get('id', None) is not None:
                 if me_data.get('id') == user_id:
                     user = SFUser.user_by_id(user_id)
                     if user is None:
                         user = SFUser.create(user_id, token, SFUser.create_secret())
                     else:
                         user.fb_token = token
                         user.put()
                     self.respond({'secret': user.secret, 'status': True})
                 else:
                     raise FBUserTokenError, "User id mismatch"
             else:
                 self.bail_with_message(None,
                                        {'status': False, 'message': 'Facebook API said: %s' % response.content},
                                        response.status_code)
         except Exception, err:
             self.bail_with_message(err, {'status': False, 'message': 'Error while validating Facebook token'})
Beispiel #2
0
    def _build_full_capabilities(self):
        # Iteratively build capabilities list
        capabilities = [self.json_capabilities]
        parent = self
        while parent.id != 'generic':
            parent = self.__class__.objects.get(id=parent.fall_back)
            capabilities.append(parent.json_capabilities)

        # JSON decoder
        d = JSONDecoder()
        
        # Reverse the device order (root parent device on down to child device)
        capabilities.reverse()
        
        # red_cap combines grouped capability dictionaries from two devices
        # x is assumed to be a parent of y (as per the WURFL fallback scheme)
        def red_cap(x,y):
            # For each group in y, check if group exists in x
            for group in iter(y):
                if group in x:
                    # If the group already exists in x, update the corresponding capability dictionary
                    x[group].update(y[group])
                else:
                    # Otherwise create a group in x with y's capability dictionary
                    x[group] = y[group]
            
            return x
        
        self.capabilities = reduce(red_cap, [d.decode(c) for c in capabilities])
Beispiel #3
0
def custom_open_file(filepath, name):
    """
    Returns 
    """
    try:
        json_dec = JSONDecoder()
        f = file(os.path.join(filepath, name), 'r')
        param = json_dec.decode(f.read())
        f.close()
    except Exception, ex:
        logger.exception(ex)
        raise
Beispiel #4
0
def custom_open_file(filepath, name):
    """
    Returns 
    """
    try:
        json_dec = JSONDecoder()
        f = file(os.path.join(filepath, name), 'r')
        param = json_dec.decode(f.read())
        f.close()
    except Exception, ex:
        logger.exception(ex)
        raise
Beispiel #5
0
    def merge_json_capabilities(self, merge):
        d = JSONDecoder()
        e = JSONEncoder()

        capabilities = d.decode(self.json_capabilities)
        capabilities_merge = d.decode(merge)

        for (group, props) in capabilities_merge.items():
            if capabilities.has_key(group):
                capabilities[group].update(props)
            else:
                capabilities[group] = props

        self.json_capabilities = e.encode(capabilities)
Beispiel #6
0
    def login(self):
        """
        Login application
        - parameters: 
            - self.
        -returns: True if login is established, false else.

        """

        params = urllib.urlencode({
            'api_key': self.api_key,
            'user_name': self.username,
            'password': self.password
        })
        logger.error("params %s" % params)
        self.conn.request('POST', '/api/login/', params)
        response = self.conn.getresponse()
        logger.error("response %s" % response)
        json_data = response.read()
        data = JSONDecoder().decode(json_data)
        try:
            self.secret = data['secret']
            self.sessionid = data['session_id']
            self.userid = data['user_id']
            self.loggedin = True
            return True
        except:
            raise Exception, "Login Filed"
Beispiel #7
0
    def _build_full_capabilities(self):
        # Iteratively build capabilities list
        capabilities = [self.json_capabilities]
        parent = self
        while parent.id != "generic":
            parent = self.__class__.objects.get(id=parent.fall_back)
            capabilities.append(parent.json_capabilities)

        # JSON decoder
        d = JSONDecoder()
        capabilities.reverse()

        def red_cap(x, y):
            x.update(y)
            return x

        self.capabilities = reduce(red_cap, [d.decode(c) for c in capabilities])
Beispiel #8
0
    def _call_server(self, method, url, *args, **kwargs):
        """
        -parameter:
                 url: url string for the server
               *args: list of arguments
            **kwargs: dict of argument
        -return:
            data return the application
        """
        p = {'api_key': self.api_key, 'user_id': self.userid}

        logger.debug("%s" % url)

        if kwargs:
            p.update(kwargs)
        elif args:
            p = p.items()
            p.extend(args)
            p.extend(kwargs.items())

        logger.error("params: %s " % p)
        logger.error("%s" % url)

        p = self._add_checksum_new(p)
        params = urllib.urlencode(p)
        logger.error("---------------params: %s" % params)
        if method == 'POST':
            self.conn.request(method, url, params)
        elif method == 'GET':
            self.conn.request(method, "%s?%s" % (url, params))
        else:
            raise Exception, "method %s unknown" % method

        response = self.conn.getresponse()
        json_data = response.read()
        logger.debug('response xxxx: %s' % json_data)
        if json_data != '':
            data = JSONDecoder().decode(json_data)
            return data
        else:
            return ''
Beispiel #9
0
                and cls is None and indent is None and separators is None
                and encoding == 'utf-8' and default is None and not kw):
            return _default_encoder.encode(obj)
        if cls is None:
            cls = JSONEncoder
        return cls(skipkeys=skipkeys,
                   ensure_ascii=ensure_ascii,
                   check_circular=check_circular,
                   allow_nan=allow_nan,
                   indent=indent,
                   separators=separators,
                   encoding=encoding,
                   default=default,
                   **kw).encode(obj)

    _default_decoder = JSONDecoder(encoding=None, object_hook=None)

    def load(fp,
             encoding=None,
             cls=None,
             object_hook=None,
             parse_float=None,
             parse_int=None,
             parse_constant=None,
             **kw):
        """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
        a JSON document) to a Python object.

        If the contents of ``fp`` is encoded with an ASCII based encoding other
        than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
        be specified. Encodings that are not ASCII based (such as UCS-2) are
from django.utils.simplejson.decoder import JSONDecoder

from django.utils.safestring import mark_safe
from django.contrib import admin
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.conf.urls.defaults import patterns
from django.http import HttpResponseRedirect, Http404
from django.db.models import F

from django.conf import settings

j = JSONDecoder()
j.ensure_ascii = False
    
class TreeNodeAdminMixIn(admin.ModelAdmin):
    actions = ['run_tree_structure']
    
    def response_action(self, request, queryset):
        if request.POST.get("action", None) == 'run_tree_structure':
            return self.run_tree_structure(None, None, None)
        return super(TreeNodeAdmin, self).response_action(request, queryset)
    
    def run_tree_structure(self, modeladmin, request, queryset):
        return HttpResponseRedirect("tree_structure/")
    run_tree_structure.short_description = "Re-order"
    
    def get_urls(self):
        return patterns('',
            (r'^tree_structure/$', self.tree_structure)
        ) + super(TreeNodeAdminMixIn, self).get_urls()