Exemple #1
0
 def test_add(self):
     cd = CookieDict()
     cd.add(name='test', value='something', expires=60, path='/home', domain='test.com', secure=True, httponly=True, comment='Blah')
     cookie = cd['test']
     assert cookie.value == 'something'
     assert cookie['expires'] == 60
     assert cookie['path'] == '/home'
     assert cookie['domain'] == 'test.com'
     assert cookie['secure'] == True
     assert cookie['httponly'] == True
Exemple #2
0
 def test_expire(self):
     cd = CookieDict()
     cd.add('test', 'something')
     cd.add('blah', 'test')
     cd.expire()
     assert cd['test']['expires'] == -1
     assert cd['blah']['expires'] == -1
Exemple #3
0
def split_headers_server_vars(environ):
    """Splits the environ into headers and server pairs.
    """
    headers = HeaderDict()
    server = MultiDict()
    cookies = CookieDict()
    for key in environ:
        if is_header(key):
            headers.add(http_header(key), environ[key])
            if key == 'HTTP_COOKIE':
                cookies = CookieDict(environ[key])
                cookies.modified = False
        else:
            server[key] = environ[key]
    return headers, server, cookies
Exemple #4
0
    def __init__(self,
                 method,
                 get=None,
                 post=None,
                 files=None,
                 headers=None,
                 server=None,
                 cookies=None,
                 body=''):
        """Creates a new instance of the Request object.

        Args:
            method: The Http request method
            get: A watson.datastructures.MultiDict containing GET variables
            post: A watson.datastructures.MultiDict containing POST variables
            files: A watson.datastructures.MultiDict containing FieldStorage objects
            headers: A watson.http.headers.HeaderDict containing valid Http headers
            server: A watson.datastructures.MultiDict containing server variables
            cookies: A watson.http.cookies.CookieDict containing watson.http.cookies.TastyMorsel objects
            body: The content of the request
        """
        super(Request, self).__init__(body=body, headers=headers)
        self._method = str(method).upper()
        if self.method not in REQUEST_METHODS:
            raise TypeError('Not a valid Http Request method.')
        self._get = get or MultiDict()
        self._post = post or MultiDict()
        self._files = files or MultiDict()
        self._server = server or MultiDict()
        self._cookies = cookies or CookieDict()
        self.headers = headers or HeaderDict()
Exemple #5
0
 def test_add(self):
     cd = CookieDict()
     cd.add(name='test',
            value='something',
            expires=60,
            path='/home',
            domain='test.com',
            secure=True,
            httponly=True,
            comment='Blah')
     cookie = cd['test']
     assert cookie.value == 'something'
     assert cookie['expires'] == 60
     assert cookie['path'] == '/home'
     assert cookie['domain'] == 'test.com'
     assert cookie['secure']
     assert cookie['httponly']
Exemple #6
0
 def test_expire(self):
     cd = CookieDict()
     cd.add('test', 'something')
     cd.add('blah', 'test')
     cd.expire()
     assert cd['test']['expires'] == -1
     assert cd['blah']['expires'] == -1
Exemple #7
0
 def __copy__(self):
     return Request(self.method,
                    get=copy(self.get),
                    post=copy(self.post),
                    files=copy(self.files),
                    headers=HeaderDict(copy(self.headers)),
                    server=copy(self.server),
                    cookies=CookieDict(copy(self.cookies)),
                    body=copy(self.body))
Exemple #8
0
 def test_output(self):
     cd = CookieDict()
     cd.add('test', 'something')
     cd.add('blah', 'test')
     assert str(cd) == 'blah=test; Path=/\r\ntest=something; Path=/'
Exemple #9
0
 def test_delete(self):
     cd = CookieDict()
     cd.add('test', 'something')
     cd.delete('test')
     assert cd['test']['expires'] == -1
Exemple #10
0
 def test_output(self):
     cd = CookieDict()
     cd.add('test', 'something')
     cd.add('blah', 'test')
     assert str(cd) == 'blah=test; Path=/\r\ntest=something; Path=/'
Exemple #11
0
 def test_delete(self):
     cd = CookieDict()
     cd.add('test', 'something')
     cd.delete('test')
     assert cd['test']['expires'] == -1
Exemple #12
0
 def cookies(self):
     """Returns the cookies associated with the Response.
     """
     if not self._cookies:
         self.cookies = CookieDict()
     return self._cookies
Exemple #13
0
class Response(MessageMixin):

    """Provides a simple and usable interface for dealing with Http Responses.

    See:
        - http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html

    Example:

    .. code-block:: python

        def app(environ, start_response):
            response = Response(200, body='<h1>Hello World!</h1>')
            response.headers.add('Content-Type', 'text/html', charset='utf-8')
            response.cookies.add('something', 'test')
            start_response(*response.start())
            return [response()]
    """
    _status_code = None
    _cookies = None
    _body = None
    _prepared = False

    def __init__(self, status_code=None, headers=None, body=None, version=None):
        """
        Args:
            status_code (int): The status code for the Response
            headers (watson.http.headers.HeaderCollection): Valid response headers.
            body (string): The content for the response
            version (string): The Http version for the response
        """
        self.status_code = status_code
        self._headers = headers or HeaderCollection()
        if version:
            self.version = version
        if body:
            self.body = body

    @property
    def headers(self):
        return self._headers

    @headers.setter
    def headers(self, headers):
        if not isinstance(headers, HeaderCollection):
            headers = HeaderCollection(headers)
        self._headers = headers

    @property
    def raw_body(self):
        if self._body:
            return self._body
        return b''

    @property
    def body(self):
        """Returns the decoded body based on the response encoding type.
        """
        return self.raw_body.decode(self.encoding)

    @body.setter
    def body(self, body):
        """Set the body of the Request.

        Args:
            body (string): The body of the request.
        """
        self._body = body.encode(self.encoding)

    @property
    def status_code(self):
        """The status code for the Response.
        """
        return self._status_code or 200

    @status_code.setter
    def status_code(self, code):
        """
        Args:
            Code: an int representing the status code for the Response
        """
        self._status_code = code

    @property
    def status_line(self):
        """The formatted status line including the status code and message.
        """
        return (
            '{0} {1}'.format(
                self.status_code, STATUS_CODES.get(self.status_code)))

    @property
    def cookies(self):
        """Returns the cookies associated with the Response.
        """
        if not self._cookies:
            self.cookies = CookieDict()
        return self._cookies

    @cookies.setter
    def cookies(self, cookies):
        """Sets the cookies associated with the Response.

        Args:
            cookies (CookieDict): The cookies to add to the response.
        """
        self._cookies = cookies

    @property
    def encoding(self):
        """Retrieve the encoding for the response from the headers, defaults to
        UTF-8.
        """
        return self.headers.get_option('Content-Type', 'charset', 'utf-8')

    def start(self):
        """Return the status_line and headers of the response for use in a WSGI
        application.

        Returns:
            The status line and headers of the response.
        """
        self._prepare()
        return self.status_line, self.headers()

    def raw(self):
        """Return the raw encoded output for the response.
        """
        return str(self).encode(self.encoding)

    def __str__(self):
        self._prepare()
        return 'HTTP/{0} {1}\r\n{2}\r\n\r\n{3}'.format(self.version,
                                                       self.status_line,
                                                       self.headers,
                                                       self.body)

    def _prepare(self):
        if not self._prepared:
            if self._cookies:
                for cookie, morsel in self.cookies.items():
                    self.headers.add('Set-Cookie', str(morsel))
            self._prepared = True

    def __call__(self, start_response):
        """Execute the start_response method and return the response body.

        Args:
            start_response (callable): The start_response function from a WSGI
                                       callable.
        """
        start_response(*self.start())
        return [self.raw_body]
Exemple #14
0
 def cookies(self, cookies):
     """Sets the cookies associated with the Response.
     """
     if not isinstance(cookies, CookieDict):
         cookies = CookieDict(cookies)
     self._cookies = cookies
Exemple #15
0
 def cookies(self):
     """Returns the cookies associated with the Response.
     """
     if not self._cookies:
         self._cookies = CookieDict()
     return self._cookies