예제 #1
0
파일: gae_storage.py 프로젝트: ddossot/glu
 def writeResourceToStorage(self, resource_name, resource_def):
     """
     Store a resource definition.
     
     No return value, but raises GluException if there is an issue.
     
     @param resource_name: The storage name for this resource
     @type  resource_name: string
     
     @param resource_def: The dictionary containing the resource definition.
     @type  resource_def: dict
     
     @raise GluException: If the resource cannot be stored.
         
     """
     try:
         existing_resources = ResourceStorage.gql("WHERE name = :1", resource_name)
         try:
             # Make sure we update old ones
             resource = existing_resources[0]
         except Exception, e:
             # No old ones? Make a new one.
             resource = ResourceStorage()
         resource.name = resource_name
         resource.data = json.dumps(resource_def)
         resource.put()
         return "No error"
예제 #2
0
파일: jsonrenderer.py 프로젝트: ddossot/glu
    def render(self, data, top_level=False):
        """
        Render the provided data for output.
        
        @param data:        An object containing the data to be rendered.
        @param data:        object
        
        @param top_level:   Flag indicating whether this we are at the
                            top level for output (this function is called
                            recursively and therefore may not always find
                            itself at the top level). This is important for
                            some renderers, since they can insert any framing
                            elements that might be required at the top level.
                            However, for the JSON renderer this is just
                            ignored.
        @param top_level:   boolean
        
        @return:            Output buffer with completed representation.
        @rtype:             string
        
        """
        # simplejson can only handle some of the base Python datatypes.
        # Since we also have other types in the output dictionaries (URIs
        # for example), we need to provide a 'default' method, which
        # simplejson calls in case it doesn't know what to do.

        # Need to use our newly defined Url encoder, since otherwise
        # json wouldn't know how to encode a URL
        if PLATFORM == PLATFORM_GAE:
            # That doesn't seem to be supported when running in
            # GAE, though. So, in that case we first perform a very
            # manual fixup of the object, replacing all occurrances
            # of unusual types with their string representations.
            data = _recursive_type_fixer(data)
            out = json.dumps(data, sort_keys=True, indent=4)
        else:
            out = json.dumps(data, default=_default, sort_keys=True, indent=4)

        return out
예제 #3
0
 def writeResourceToStorage(self, resource_name, resource_def):
     """
     Store a resource definition.
     
     No return value, but raises GluException if there is an issue.
     
     @param resource_name: The storage name for this resource
     @type  resource_name: string
     
     @param resource_def: The dictionary containing the resource definition.
     @type  resource_def: dict
     
     @raise GluException: If the resource cannot be stored.
         
     """
     try:
         buf = json.dumps(resource_def, indent=4)
         self.storeFile(resource_name, buf)
     except Exception, e:
         raise GluException("Problems storing new resource: " + str(e))
예제 #4
0
    def orders(self, request, input, params, method):
        """
        Stored or retrieves data from the storage bucket for Marakana orders.
        
        @param request:    Information about the HTTP request.
        @type request:     BaseHttpRequest
        
        @param input:      Any data that came in the body of the request.
        @type input:       string
        
        @param params:     Dictionary of parameter values.
        @type params:      dict
        
        @param method:     The HTTP request method.
        @type method:      string
        
        @return:           The output data of this service.
        @rtype:            string
        
        """
        # Access to our storage bucket
        storage   = self.getFileStorage()

        # Get my parameters
        param_order_id = params.get('id')
        code = 200
        if not param_order_id  and  not input:
            # User didn't specify a specific order (and also doesn't POST a new order object),
            # which means we should generate a list of all the orders we have stored.
            data = self.__get_order_list(storage)
        else:
            if method == "DELETE":
                if param_order_id:
                    storage.deleteFile(param_order_id)
                    data = "File deleted"
                else:
                    code = 400
                    data = "Missing order id"
            else:
                if input:
                    # Parse the input into JSON
                    d = self.__xml_to_dict(input)
                    # Sanity check
                    try:
                        if 'product-order' in d['spark-domain']:
                            is_product_order = True
                            doc_name         = 'product-order'
                            self.__dict_struct_compare(d, self.__PRODUCT_ORDER_TEMPLATE)
                            order_id = d['spark-domain']['product-order']['__attributes']['id']
                        else:
                            is_product_order = False
                            doc_name         = 'registration-order'
                            self.__dict_struct_compare(d, self.__REGISTRATION_ORDER_TEMPLATE)
                            order_id = d['spark-domain']['registration-order']['__attributes']['id']
                    except Exception, e:
                        return 400, "Malformed request  body: " + str(e)
                    
                    # Creating or updating order
                    location_str = "%s/orders/%s" % (self.getMyResourceUri(), order_id)
                    if param_order_id:
                        if param_order_id != order_id:
                            return 400, "Order ID in URL and message body do not match (%s vs. %s)" % (param_order_id, order_id)
                        # Update an already existing order? Throws exception if it does not
                        # exist, which is exactly what we want.
                        dummy_data = storage.loadFile(order_id)
                        code       = 200
                        data       = "Successfully updated: %s" % location_str
                    else:
                        # Creating a new order? We need to extract the order id.
                        if request:
                            request.setResponseHeader("Location", location_str)
                        code = 201
                        data = "Successfully stored: %s" % location_str

                    # Store the data, but only the dictionary that contains the actual order info.
                    # We store it in a dictionary that contains a single key and this data, since
                    # that makes it look ... nice.
                    storage.storeFile(order_id, json.dumps({ doc_name : d['spark-domain'][doc_name] }))
                else:
                    # Just want to retrieve an existing order
                    data = json.loads(storage.loadFile(param_order_id))
예제 #5
0
파일: testglu.py 프로젝트: ddossot/glu
def _send_data(relative_url, obj):
    """
    Helper method that POSTs an object to URL as JSON.

    @param relative_url: The relative URL on the server. A starting slash may be
                         specified, but either way, it's always interpreted to be
                         relative to "/".
    @type  relative_url: string

    @param obj:          The object to be parsed to JSON and sent.
    @type obj:           object

    @return:             The JSON interpreted data and the response object as a tuple.
    @rtype               tuple

    """
    if relative_url.startswith("/"):
        relative_url = relative_url[1:]
    resp = http.urlopen("POST", SERVER_URL + "/" + relative_url, headers={"Accept" : "application/json"}, data=json.dumps(obj))
    buf = resp.read()
    if resp.getStatus() >= 200 and resp.getStatus() <= 300:
        data = json.loads(buf)
    else:
        data = buf
    return (data, resp)
예제 #6
0
파일: testglu.py 프로젝트: ddossot/glu
def _pretty_json(obj):
    """
    Output an object as pretty-printed JSON.

    """
    return json.dumps(obj, indent=4)