Example #1
0
    def get_response(self):
        '''
        Sends the request and returns an HTTP response object.
        @return: Response
        '''
        if self.method in HTTP_METHODS_WITH_DATA and not self.data:
            raise Exception("%s requests must carry data." %
                            self.method.upper())

        headers = self.__serialize_headers()
        headers.update({
            "Accept": "application/json",
            "User-Agent": "Greendizer Pyzer Library/1.0",
            "Accept-Encoding": "gzip, deflate",
            "Cache-Control": "no-cache"
        })

        #X-HTTP-Method-Override support
        method = self.method.lower()
        if ((HTTP_POST_ONLY and self.method in HTTP_METHODS_WITH_DATA) or
            self.method == "patch"):
            headers["X-HTTP-Method-Override"] = self.method.upper()
            method = "post"

        #Data encoding and compression for POST, PUT and PATCH requests
        data = self.data
        if method in HTTP_METHODS_WITH_DATA:
            headers["Content-Type"] = self.__content_type + "; charset=utf-8"

            #URL encoding
            if self.__content_type == "application/x-www-form-urlencoded":
                data = to_byte_string(urllib.urlencode(data))


            #GZip compression
            if not greendizer.DEBUG and USE_GZIP:
                headers["Content-Encoding"] = COMPRESSION_GZIP
                data = self.__gzip_content(to_byte_string(data))

        request = Request.HttpRequest(self.uri.geturl(),
                                      data=data,
                                      method=method, headers=headers)

        try:
            response = urllib2.urlopen(request)
            return Response(self, 200, response.read(),
                            response.info())

        except(urllib2.HTTPError), e:
            instance = Response(self, e.code, e.read(), e.info())
            if e.code not in [201, 202, 204, 206, 304, 409, 416]:
                raise ApiException(instance)

            return instance
Example #2
0
 def __createElementNS(self, root, uri, name, value):
     '''
     Creates and returns an element with a qualified name and a name space
     @param root:Element Parent element
     @param uri:str Namespace URI
     @param tag:str Tag name.
     '''
     tag = root.ownerDocument.createElementNS(to_byte_string(uri),
                                              to_byte_string(name))
     tag.appendChild(root.ownerDocument
                     .createCDATASection(to_byte_string(value)))
     return root.appendChild(tag)
Example #3
0
    def _create_text_node(self, root, name, value, cdata=False):
        '''
        Creates and adds a text node
        @param root:Element Root element
        @param name:str Tag name
        @param value:object Text value
        @param cdata:bool A value indicating whether to use CDATA or not.
        @return:Node
        '''
        if is_empty_or_none(value):
            return

        if isinstance(value, date):
            value = date_to_string(value)

        if isinstance(value, datetime):
            value = datetime_to_string(value)

        if isinstance(value, Decimal):
            value = "0" if not value else str(value)

        tag = root.ownerDocument.createElement(name)
        value = to_byte_string(value)
        if cdata:
            tag.appendChild(root.ownerDocument.createCDATASection(value))
        else:
            tag.appendChild(root.ownerDocument.createTextNode(value))

        return root.appendChild(tag)
Example #4
0
    def to_xml(self, name):
        '''
        Returns a DOM representation of the line treatment.
        @return: Element
        '''
        for n, v in { "rate_type": self.rate_type,
                     "rate": self.rate,
                     "name": self.name,
                     "description":self.description }.items():
            if is_empty_or_none(v):
                raise ValueError("'%s' attribute cannot be empty or None." % n)

        doc = Document()
        root = doc.createElement(name)
        root.setAttribute("type", self.rate_type)
        root.setAttribute("name", to_byte_string(self.name))
        root.setAttribute("description", to_byte_string(self.description))
        root.setAttribute("base", self.interval) if self.interval else ""
        root.appendChild(doc.createTextNode(to_byte_string(self.rate)))
        return root
    def send(self, xmli, signature=True):
        '''
        Sends an invoice
        @param xmli:str Invoice XML representation.
        @return: InvoiceReport
        '''
        xmli = to_byte_string(xmli)
        if not xmli:
            raise ValueError("Invalid XMLi")

        '''
        XMLdsig: required PyCrypto + lxml
        '''
        private_key, public_key = self.email.client.keys
        if signature and private_key and public_key:
            from greendizer import xmldsig
            xmli = xmldsig.sign(xmli, private_key, public_key)

        size = 0
        try:
            from os import sys
            size = sys.getsizeof(xmli)
        except AttributeError:
            import base64 #2.5 and older...
            size = len(base64.encodestring(xmli)) #1 ASCII = 1 byte

        if size > MAX_CONTENT_LENGTH:
            raise ValueError("XMLi's size is limited to %skb."
                             % MAX_CONTENT_LENGTH / 1024)

        request = Request(self.email.client, method="POST", data=xmli,
                          uri=self._uri, content_type="application/xml")

        response = request.get_response()
        if response.status_code == 202: #Accepted
            return InvoiceReport(self.email,
                                 extract_id_from_uri(response["Location"]))