コード例 #1
0
    def __init__(self):
        """Create a new empty Response object
        """

        # Set the default status to "200 OK"
        self._status = "200 OK"

        # The statuscode is also set to 200
        self._statuscode = 200

        # The body is initialized as a empty unicode string which should be utf-8 encoded
        self._body = ""
        self._charset = "utf-8"

        # The content-type is by default set to text/html
        self.content_type = "text/html"

        # The headers (this is a MultiDict because headers with the same key can occur)
        self.headers = MultiDict()

        # The cookies to be set are stored in a dictionary for each key a cookie will be created
        # with the value
        self.cookies = CookieDict()

        # Set server data
        self.headers["Server"] = "Simplendi OpenSource Framework"
コード例 #2
0
    def _parseBody(self):
        """Parses the body of the request into a dictionary. At the moment only 
        application/x-www-form-urlencoded is supported!
        """
        
        # If the content_type is defined and the content has a length try to parse the body
        if self.content_type and self.content_length:
            if self.content_type.startswith('application/x-www-form-urlencoded'):
                self.body = MultiDict()
                
                # Read the body from the virtual file
                self._replaceBody()
                body = self.environment["wsgi.input"].read(self.content_length)
                self._resetBody()
                
                # Decode the body from its latin-1 decoding to a python string
                body = body.decode('latin-1')
                
                # Split the body into strings containing one key and one value
                pairs = body.split('&')
                
                # For each key value pair split it and decode it from urlencoded strings to a string
                for pair in pairs:
                    (key, _, value) = pair.partition('=');
                    
                    # Add key/value to MultiDict 
                    self.body.append(unquote_plus(key), unquote_plus(value))

            elif self.content_type.startswith("multipart/form-data"):
                self._replaceBody()
                self.body = cgi.FieldStorage(fp=self.environment["wsgi.input"], environ=self.environment)
                self._resetBody()

            elif self.content_type.startswith("application/json"):
                if "charset" in self.content_type:
                    try:
                        charset = self.content_type[self.content_type.find("charset"):].rpartition("=")[2]
                    except:
                        charset = "UTF8"
                else:
                    charset = "UTF8"

                # Read the body from the virtual file
                self._replaceBody()
                body = self.environment["wsgi.input"].read(self.content_length)
                self._resetBody()

                # Decode the body
                body = body.decode(charset)

                self.body = json.loads(body)
                
        elif self.content_length:
            self._replaceBody()
            self.body = self.environment["wsgi.input"].read(self.content_length)
            self._resetBody()
        else:
            self.body = None
コード例 #3
0
ファイル: response.py プロジェクト: Simplendi/SimpleFramework
    def __init__(self):
        """Create a new empty Response object
        """
        
        # Set the default status to "200 OK"
        self._status = "200 OK"
        
        # The statuscode is also set to 200
        self._statuscode = 200
        
        # The body is initialized as a empty unicode string which should be utf-8 encoded
        self._body = ""
        self._charset = "utf-8"
        
        # The content-type is by default set to text/html
        self.content_type = "text/html"
        
        # The headers (this is a MultiDict because headers with the same key can occur)
        self.headers = MultiDict()

        # The cookies to be set are stored in a dictionary for each key a cookie will be created 
        # with the value
        self.cookies = CookieDict()
        
        # Set server data
        self.headers["Server"] = "Simplendi OpenSource Framework"
コード例 #4
0
 def _parseQuery(self):
     """Parses the query strings that can be present in a request into a dictionary
     """
     
     self.query = MultiDict()
     
     # Get the query string
     query_string = self.environment.get("QUERY_STRING")
     
     # The seperator per key/value-pair is & so we split on that
     pairs = query_string.split('&')
     
     # Parse the key/value-string-pairs into a dictionary
     for pair in pairs:
         (key, _, value)  = pair.partition('=')
         
         # Add key/value to MultiDict
         self.query.append(unquote_plus(key), unquote_plus(value))
コード例 #5
0
ファイル: request.py プロジェクト: Simplendi/SimpleFramework
    def _parseBody(self):
        """Parses the body of the request into a dictionary. At the moment only 
        application/x-www-form-urlencoded is supported!
        """
        
        # If the content_type is defined and the content has a length try to parse the body
        if self.content_type and self.content_length:
            if self.content_type.startswith('application/x-www-form-urlencoded'):
                self.body = MultiDict()
                
                # Read the body from the virtual file
                body = self.environment["wsgi.input"].read(self.content_length)
                
                # Decode the body from its latin-1 decoding to a python string
                body = body.decode('latin-1')
                
                # Split the body into strings containing one key and one value
                pairs = body.split('&')
                
                # For each key value pair split it and decode it from urlencoded strings to a string
                for pair in pairs:
                    (key, _, value) = pair.partition('=');
                    
                    # Add key/value to MultiDict 
                    self.body.append(unquote_plus(key), unquote_plus(value))

            elif self.content_type.startswith("multipart/form-data"):
                self.body = cgi.FieldStorage(fp=self.environment["wsgi.input"], environ=self.environment)

            elif self.content_type.startswith("application/json"):
                if "charset" in self.content_type:
                    try:
                        charset = self.content_type[self.content_type.find("charset"):].rpartition("=")[2]
                    except:
                        charset = "UTF8"
                else:
                    charset = "UTF8"

                # Read the body from the virtual file
                body = self.environment["wsgi.input"].read(self.content_length)

                # Decode the body
                body = body.decode(charset)

                self.body = json.loads(body)
                
        elif self.content_length:
            self.body = self.environment["wsgi.input"].read(self.content_length)
            ß
        else:
            self.body = None
コード例 #6
0
ファイル: request.py プロジェクト: Simplendi/SimpleFramework
 def _parseQuery(self):
     """Parses the query strings that can be present in a request into a dictionary
     """
     
     self.query = MultiDict()
     
     # Get the query string
     query_string = self.environment.get("QUERY_STRING")
     
     # The seperator per key/value-pair is & so we split on that
     pairs = query_string.split('&')
     
     # Parse the key/value-string-pairs into a dictionary
     for pair in pairs:
         (key, _, value)  = pair.partition('=')
         
         # Add key/value to MultiDict
         self.query.append(unquote_plus(key), unquote_plus(value))
コード例 #7
0
ファイル: response.py プロジェクト: Simplendi/SimpleFramework
class Response(object):

    def __init__(self):
        """Create a new empty Response object
        """
        
        # Set the default status to "200 OK"
        self._status = "200 OK"
        
        # The statuscode is also set to 200
        self._statuscode = 200
        
        # The body is initialized as a empty unicode string which should be utf-8 encoded
        self._body = ""
        self._charset = "utf-8"
        
        # The content-type is by default set to text/html
        self.content_type = "text/html"
        
        # The headers (this is a MultiDict because headers with the same key can occur)
        self.headers = MultiDict()

        # The cookies to be set are stored in a dictionary for each key a cookie will be created 
        # with the value
        self.cookies = CookieDict()
        
        # Set server data
        self.headers["Server"] = "Simplendi OpenSource Framework"
    

    def _getBody(self):
        return self._body
    
    def _setBody(self, data):
        self._body = data
       
    body = property(_getBody, _setBody,
    """The body is a readable and writable property.
    """)      

    def _getCharset(self):
        return self._charset
    
    def _setCharset(self, value):
        self._charset = value
    
    charset = property(_getCharset, _setCharset,
    """The charset is a readable and writable property.
    """)
    
    def _getContentLength(self):
        if self._charset:
            return len(self._body.encode(self._charset))
        else:
            return len(self._body)
    
    content_length = property(_getContentLength, None,
    """The content length is a read-only property
    """)
       
    def _setStatus(self, value):
        try:
            self._statuscode = int(value[0:3])
        except ValueError:
            raise ValueError("Non valid statuscode")
        self._status = value
        
    def _getStatus(self):
        return self._status
    
    status = property(_getStatus, _setStatus, None,
    """Status is a readable and writable string which should begin with three digits. The statuscode
    is modified on modification
    """)
    
    def _setStatusCode(self, value):
        try:
            self._statuscode = int(value)
        except ValueError:
            raise ValueError("Non valid statuscode")

        self._status = httpstatusforcode[self._statuscode]
            
    def _getStatusCode(self):
        return self._statuscode
    
    statuscode = property(_getStatusCode, _setStatusCode, None,
    """Statuscode is a readable and writable intereger. The status is modified for known statuscodes
    if a not know statuscode is used, use status
    """)
    
    def generateCookieHeaders(self):
        """Convert the cookies into Set-Cookie HTTP headers
        """
        for cookie_key in self.cookies:
            self.headers.append("Set-Cookie", self.cookies.getSetCookieHeader(cookie_key))
            
    def setJsonBody(self, body = None):
        """Set the content-type to json and optionally set the body
        """
        self.content_type = "application/json"
        if body:
            self.body = body
            
    def setRedirect(self, url, response_code = 302):
        self.statuscode = 302
        self.headers.append("Location", url)
コード例 #8
0
class Request():
    
    def __init__(self, environment):
        """Create a Request object from the environment-dictionary.
        """
        
        # Store envirnment for futher reference
        self.environment = environment
        
        # Get REQUEST_METHOD (Required)
        self.method = environment['REQUEST_METHOD']
        
        # Get SERVER_PORT (Required)
        self.port = environment['SERVER_PORT']
        
        # Get HTTP_HOST (Optional)
        self.host = environment.get('HTTP_HOST')
        
        # Get SCRIPT_NAME (Can be empty)
        self.script_name = environment.get('SCRIPT_NAME', '')
        
        # Get PATH_INFO (Can be empty)
        self.path_info = environment.get('PATH_INFO','')
        
        # Get HTTP_USER_AGENT (Can be empty)
        self.user_agent = environment.get('HTTP_USER_AGENT', '')
        
        # Get HTTP_ACCEPT (Is AcceptContainer)
        self.accept = AcceptContainer(environment.get('HTTP_ACCEPT'))
        
        # Get HTTP_ACCEPT_LANGUAGE (Is AcceptContainer)
        self.accept_language = AcceptContainer(environment.get('HTTP_ACCEPT_LANGUAGE'))
        
        # Get HTTP_ACCEPT_ENCODING (Is AcceptContainer)
        self.accept_encoding = AcceptContainer(environment.get('HTTP_ACCEPT_ENCODING'))
        
        # Get HTTP_ACCEPT_CHARSET (Is AcceptContainer)
        self.accept_charset = AcceptContainer(environment.get('HTTP_ACCEPT_CHARSET'))
        
        # Get COOKIES
        self.cookies = CookieDict(environment.get('HTTP_COOKIE'))

        # Get CONTENT_LENGTH
        try:
            self.content_length = int(self.environment.get('CONTENT_LENGTH'))
        except ValueError:
            self.content_length = None

        # Get CONTENT_TYPE
        self.content_type = self.environment.get('CONTENT_TYPE', '')
        
        # Parse body
        self._parseBody()
        
        # Parse query
        self._parseQuery()
    
    def _parseBody(self):
        """Parses the body of the request into a dictionary. At the moment only 
        application/x-www-form-urlencoded is supported!
        """
        
        # If the content_type is defined and the content has a length try to parse the body
        if self.content_type and self.content_length:
            if self.content_type.startswith('application/x-www-form-urlencoded'):
                self.body = MultiDict()
                
                # Read the body from the virtual file
                self._replaceBody()
                body = self.environment["wsgi.input"].read(self.content_length)
                self._resetBody()
                
                # Decode the body from its latin-1 decoding to a python string
                body = body.decode('latin-1')
                
                # Split the body into strings containing one key and one value
                pairs = body.split('&')
                
                # For each key value pair split it and decode it from urlencoded strings to a string
                for pair in pairs:
                    (key, _, value) = pair.partition('=');
                    
                    # Add key/value to MultiDict 
                    self.body.append(unquote_plus(key), unquote_plus(value))

            elif self.content_type.startswith("multipart/form-data"):
                self._replaceBody()
                self.body = cgi.FieldStorage(fp=self.environment["wsgi.input"], environ=self.environment)
                self._resetBody()

            elif self.content_type.startswith("application/json"):
                if "charset" in self.content_type:
                    try:
                        charset = self.content_type[self.content_type.find("charset"):].rpartition("=")[2]
                    except:
                        charset = "UTF8"
                else:
                    charset = "UTF8"

                # Read the body from the virtual file
                self._replaceBody()
                body = self.environment["wsgi.input"].read(self.content_length)
                self._resetBody()

                # Decode the body
                body = body.decode(charset)

                self.body = json.loads(body)
                
        elif self.content_length:
            self._replaceBody()
            self.body = self.environment["wsgi.input"].read(self.content_length)
            self._resetBody()
        else:
            self.body = None

    def _replaceBody(self):
        rep = io.BytesIO()
        buf = self.environment["wsgi.input"].read(self.content_length)
        rep.write(buf)
        self.environment["wsgi.input"] = rep
        rep.seek(0)

    def _resetBody(self):
        self.environment["wsgi.input"].seek(0)


    def _parseQuery(self):
        """Parses the query strings that can be present in a request into a dictionary
        """
        
        self.query = MultiDict()
        
        # Get the query string
        query_string = self.environment.get("QUERY_STRING")
        
        # The seperator per key/value-pair is & so we split on that
        pairs = query_string.split('&')
        
        # Parse the key/value-string-pairs into a dictionary
        for pair in pairs:
            (key, _, value)  = pair.partition('=')
            
            # Add key/value to MultiDict
            self.query.append(unquote_plus(key), unquote_plus(value))
            
    def isGet(self):
        """Test to see if the request method is GET
        """
        return self.method == "GET"
    
    def isPost(self):
        """Test to see if the request method is POST
        """
        return self.method == "POST"
        
    def isJson(self):
        """Test to see if the request is a JSON request
        """
        return self.environment.get("HTTP_X_REQUESTED_WITH", "") == "XMLHttpRequest"
        
        
        
コード例 #9
0
class Response(object):
    def __init__(self):
        """Create a new empty Response object
        """

        # Set the default status to "200 OK"
        self._status = "200 OK"

        # The statuscode is also set to 200
        self._statuscode = 200

        # The body is initialized as a empty unicode string which should be utf-8 encoded
        self._body = ""
        self._charset = "utf-8"

        # The content-type is by default set to text/html
        self.content_type = "text/html"

        # The headers (this is a MultiDict because headers with the same key can occur)
        self.headers = MultiDict()

        # The cookies to be set are stored in a dictionary for each key a cookie will be created
        # with the value
        self.cookies = CookieDict()

        # Set server data
        self.headers["Server"] = "Simplendi OpenSource Framework"

    def _getBody(self):
        return self._body

    def _setBody(self, data):
        self._body = data

    body = property(_getBody, _setBody,
                    """The body is a readable and writable property.
    """)

    def _getCharset(self):
        return self._charset

    def _setCharset(self, value):
        self._charset = value

    charset = property(
        _getCharset, _setCharset,
        """The charset is a readable and writable property.
    """)

    def _getContentLength(self):
        if self._charset:
            return len(self._body.encode(self._charset))
        else:
            return len(self._body)

    content_length = property(
        _getContentLength, None, """The content length is a read-only property
    """)

    def _setStatus(self, value):
        try:
            self._statuscode = int(value[0:3])
        except ValueError:
            raise ValueError("Non valid statuscode")
        self._status = value

    def _getStatus(self):
        return self._status

    status = property(
        _getStatus, _setStatus, None,
        """Status is a readable and writable string which should begin with three digits. The statuscode
    is modified on modification
    """)

    def _setStatusCode(self, value):
        try:
            self._statuscode = int(value)
        except ValueError:
            raise ValueError("Non valid statuscode")

        self._status = httpstatusforcode[self._statuscode]

    def _getStatusCode(self):
        return self._statuscode

    statuscode = property(
        _getStatusCode, _setStatusCode, None,
        """Statuscode is a readable and writable intereger. The status is modified for known statuscodes
    if a not know statuscode is used, use status
    """)

    def generateCookieHeaders(self):
        """Convert the cookies into Set-Cookie HTTP headers
        """
        for cookie_key in self.cookies:
            self.headers.append("Set-Cookie",
                                self.cookies.getSetCookieHeader(cookie_key))

    def setJsonBody(self, body=None):
        """Set the content-type to json and optionally set the body
        """
        self.content_type = "application/json"
        if body:
            self.body = body

    def setRedirect(self, url, response_code=302):
        self.statuscode = 302
        self.headers.append("Location", url)
コード例 #10
0
ファイル: request.py プロジェクト: Simplendi/SimpleFramework
class Request():
    
    def __init__(self, environment):
        """Create a Request object from the environment-dictionary.
        """
        
        # Store envirnment for futher reference
        self.environment = environment
        
        # Get REQUEST_METHOD (Required)
        self.method = environment['REQUEST_METHOD']
        
        # Get SERVER_PORT (Required)
        self.port = environment['SERVER_PORT']
        
        # Get HTTP_HOST (Optional)
        self.host = environment.get('HTTP_HOST')
        
        # Get SCRIPT_NAME (Can be empty)
        self.script_name = environment.get('SCRIPT_NAME', '')
        
        # Get PATH_INFO (Can be empty)
        self.path_info = environment.get('PATH_INFO','')
        
        # Get HTTP_USER_AGENT (Can be empty)
        self.user_agent = environment.get('HTTP_USER_AGENT', '')
        
        # Get HTTP_ACCEPT (Is AcceptContainer)
        self.accept = AcceptContainer(environment.get('HTTP_ACCEPT'))
        
        # Get HTTP_ACCEPT_LANGUAGE (Is AcceptContainer)
        self.accept_language = AcceptContainer(environment.get('HTTP_ACCEPT_LANGUAGE'))
        
        # Get HTTP_ACCEPT_ENCODING (Is AcceptContainer)
        self.accept_encoding = AcceptContainer(environment.get('HTTP_ACCEPT_ENCODING'))
        
        # Get HTTP_ACCEPT_CHARSET (Is AcceptContainer)
        self.accept_charset = AcceptContainer(environment.get('HTTP_ACCEPT_CHARSET'))
        
        # Get COOKIES
        self.cookies = CookieDict(environment.get('HTTP_COOKIE'))

        # Get CONTENT_LENGTH
        try:
            self.content_length = int(self.environment.get('CONTENT_LENGTH'))
        except ValueError:
            self.content_length = None

        # Get CONTENT_TYPE
        self.content_type = self.environment.get('CONTENT_TYPE', '')
        
        # Parse body
        self._parseBody()
        
        # Parse query
        self._parseQuery()
    
    def _parseBody(self):
        """Parses the body of the request into a dictionary. At the moment only 
        application/x-www-form-urlencoded is supported!
        """
        
        # If the content_type is defined and the content has a length try to parse the body
        if self.content_type and self.content_length:
            if self.content_type.startswith('application/x-www-form-urlencoded'):
                self.body = MultiDict()
                
                # Read the body from the virtual file
                body = self.environment["wsgi.input"].read(self.content_length)
                
                # Decode the body from its latin-1 decoding to a python string
                body = body.decode('latin-1')
                
                # Split the body into strings containing one key and one value
                pairs = body.split('&')
                
                # For each key value pair split it and decode it from urlencoded strings to a string
                for pair in pairs:
                    (key, _, value) = pair.partition('=');
                    
                    # Add key/value to MultiDict 
                    self.body.append(unquote_plus(key), unquote_plus(value))

            elif self.content_type.startswith("multipart/form-data"):
                self.body = cgi.FieldStorage(fp=self.environment["wsgi.input"], environ=self.environment)

            elif self.content_type.startswith("application/json"):
                if "charset" in self.content_type:
                    try:
                        charset = self.content_type[self.content_type.find("charset"):].rpartition("=")[2]
                    except:
                        charset = "UTF8"
                else:
                    charset = "UTF8"

                # Read the body from the virtual file
                body = self.environment["wsgi.input"].read(self.content_length)

                # Decode the body
                body = body.decode(charset)

                self.body = json.loads(body)
                
        elif self.content_length:
            self.body = self.environment["wsgi.input"].read(self.content_length)
            ß
        else:
            self.body = None

    def _parseQuery(self):
        """Parses the query strings that can be present in a request into a dictionary
        """
        
        self.query = MultiDict()
        
        # Get the query string
        query_string = self.environment.get("QUERY_STRING")
        
        # The seperator per key/value-pair is & so we split on that
        pairs = query_string.split('&')
        
        # Parse the key/value-string-pairs into a dictionary
        for pair in pairs:
            (key, _, value)  = pair.partition('=')
            
            # Add key/value to MultiDict
            self.query.append(unquote_plus(key), unquote_plus(value))
            
    def isGet(self):
        """Test to see if the request method is GET
        """
        return self.method == "GET"
    
    def isPost(self):
        """Test to see if the request method is POST
        """
        return self.method == "POST"
        
    def isJson(self):
        """Test to see if the request is a JSON request
        """
        return self.environment.get("HTTP_X_REQUESTED_WITH", "") == "XMLHttpRequest"