1 # Copyright 2013 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
8 def __init__(self
, path
, host
, headers
):
9 self
.path
= path
.lstrip('/')
10 self
.host
= host
.rstrip('/')
11 self
.headers
= headers
14 def ForTest(path
, host
='http://developer.chrome.com', headers
=None):
15 return Request(path
, host
, headers
or {})
18 return 'Request(path=%s, host=%s, headers=%s)' % (
19 self
.path
, self
.host
, self
.headers
)
24 class _ContentBuilder(object):
25 '''Builds the response content.
30 def Append(self
, content
):
31 if isinstance(content
, unicode):
32 content
= content
.encode('utf-8', 'replace')
33 self
._buf
.append(content
)
40 return self
.ToString()
43 return len(self
.ToString())
46 self
._buf
= [''.join(self
._buf
)]
48 class Response(object):
49 '''The response from Get().
51 def __init__(self
, content
=None, headers
=None, status
=None):
52 self
.content
= _ContentBuilder()
53 if content
is not None:
54 self
.content
.Append(content
)
56 if headers
is not None:
57 self
.headers
.update(headers
)
61 def Ok(content
, headers
=None):
62 '''Returns an OK (200) response.
64 return Response(content
=content
, headers
=headers
, status
=200)
67 def Redirect(url
, permanent
=False):
68 '''Returns a redirect (301 or 302) response.
70 status
= 301 if permanent
else 302
71 return Response(headers
={'Location': url
}, status
=status
)
74 def NotFound(content
, headers
=None):
75 '''Returns a not found (404) response.
77 return Response(content
=content
, headers
=headers
, status
=404)
80 def InternalError(content
, headers
=None):
81 '''Returns an internal error (500) response.
83 return Response(content
=content
, headers
=headers
, status
=500)
85 def Append(self
, content
):
86 '''Appends |content| to the response content.
88 self
.content
.append(content
)
90 def AddHeader(self
, key
, value
):
91 '''Adds a header to the response.
93 self
.headers
[key
] = value
95 def AddHeaders(self
, headers
):
96 '''Adds several headers to the response.
98 self
.headers
.update(headers
)
100 def SetStatus(self
, status
):
103 def GetRedirect(self
):
104 if self
.headers
.get('Location') is None:
106 return (self
.headers
.get('Location'), self
.status
== 301)
108 def IsNotFound(self
):
109 return self
.status
== 404
111 def __eq__(self
, other
):
112 return (isinstance(other
, self
.__class
__) and
113 str(other
.content
) == str(self
.content
) and
114 other
.headers
== self
.headers
and
115 other
.status
== self
.status
)
117 def __ne__(self
, other
):
118 return not (self
== other
)
121 return 'Response(content=%s bytes, status=%s, headers=%s)' % (
122 len(self
.content
), self
.status
, self
.headers
)
127 class Servlet(object):
128 def __init__(self
, request
):
129 self
._request
= request
132 '''Returns a Response.
134 raise NotImplemented()