##// END OF EJS Templates
request: coerce content-type to native str...
Augie Fackler -
r34515:528b21b8 default
parent child Browse files
Show More
@@ -1,152 +1,155 b''
1 1 # hgweb/request.py - An http request from either CGI or the standalone server.
2 2 #
3 3 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
4 4 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
5 5 #
6 6 # This software may be used and distributed according to the terms of the
7 7 # GNU General Public License version 2 or any later version.
8 8
9 9 from __future__ import absolute_import
10 10
11 11 import cgi
12 12 import errno
13 13 import socket
14 14
15 15 from .common import (
16 16 ErrorResponse,
17 17 HTTP_NOT_MODIFIED,
18 18 statusmessage,
19 19 )
20 20
21 21 from .. import (
22 pycompat,
22 23 util,
23 24 )
24 25
25 26 shortcuts = {
26 27 'cl': [('cmd', ['changelog']), ('rev', None)],
27 28 'sl': [('cmd', ['shortlog']), ('rev', None)],
28 29 'cs': [('cmd', ['changeset']), ('node', None)],
29 30 'f': [('cmd', ['file']), ('filenode', None)],
30 31 'fl': [('cmd', ['filelog']), ('filenode', None)],
31 32 'fd': [('cmd', ['filediff']), ('node', None)],
32 33 'fa': [('cmd', ['annotate']), ('filenode', None)],
33 34 'mf': [('cmd', ['manifest']), ('manifest', None)],
34 35 'ca': [('cmd', ['archive']), ('node', None)],
35 36 'tags': [('cmd', ['tags'])],
36 37 'tip': [('cmd', ['changeset']), ('node', ['tip'])],
37 38 'static': [('cmd', ['static']), ('file', None)]
38 39 }
39 40
40 41 def normalize(form):
41 42 # first expand the shortcuts
42 43 for k in shortcuts:
43 44 if k in form:
44 45 for name, value in shortcuts[k]:
45 46 if value is None:
46 47 value = form[k]
47 48 form[name] = value
48 49 del form[k]
49 50 # And strip the values
50 51 for k, v in form.iteritems():
51 52 form[k] = [i.strip() for i in v]
52 53 return form
53 54
54 55 class wsgirequest(object):
55 56 """Higher-level API for a WSGI request.
56 57
57 58 WSGI applications are invoked with 2 arguments. They are used to
58 59 instantiate instances of this class, which provides higher-level APIs
59 60 for obtaining request parameters, writing HTTP output, etc.
60 61 """
61 62 def __init__(self, wsgienv, start_response):
62 63 version = wsgienv[r'wsgi.version']
63 64 if (version < (1, 0)) or (version >= (2, 0)):
64 65 raise RuntimeError("Unknown and unsupported WSGI version %d.%d"
65 66 % version)
66 67 self.inp = wsgienv[r'wsgi.input']
67 68 self.err = wsgienv[r'wsgi.errors']
68 69 self.threaded = wsgienv[r'wsgi.multithread']
69 70 self.multiprocess = wsgienv[r'wsgi.multiprocess']
70 71 self.run_once = wsgienv[r'wsgi.run_once']
71 72 self.env = wsgienv
72 73 self.form = normalize(cgi.parse(self.inp,
73 74 self.env,
74 75 keep_blank_values=1))
75 76 self._start_response = start_response
76 77 self.server_write = None
77 78 self.headers = []
78 79
79 80 def __iter__(self):
80 81 return iter([])
81 82
82 83 def read(self, count=-1):
83 84 return self.inp.read(count)
84 85
85 86 def drain(self):
86 87 '''need to read all data from request, httplib is half-duplex'''
87 88 length = int(self.env.get('CONTENT_LENGTH') or 0)
88 89 for s in util.filechunkiter(self.inp, limit=length):
89 90 pass
90 91
91 92 def respond(self, status, type, filename=None, body=None):
93 if not isinstance(type, str):
94 type = pycompat.sysstr(type)
92 95 if self._start_response is not None:
93 96 self.headers.append(('Content-Type', type))
94 97 if filename:
95 98 filename = (filename.rpartition('/')[-1]
96 99 .replace('\\', '\\\\').replace('"', '\\"'))
97 100 self.headers.append(('Content-Disposition',
98 101 'inline; filename="%s"' % filename))
99 102 if body is not None:
100 103 self.headers.append(('Content-Length', str(len(body))))
101 104
102 105 for k, v in self.headers:
103 106 if not isinstance(v, str):
104 107 raise TypeError('header value must be string: %r' % (v,))
105 108
106 109 if isinstance(status, ErrorResponse):
107 110 self.headers.extend(status.headers)
108 111 if status.code == HTTP_NOT_MODIFIED:
109 112 # RFC 2616 Section 10.3.5: 304 Not Modified has cases where
110 113 # it MUST NOT include any headers other than these and no
111 114 # body
112 115 self.headers = [(k, v) for (k, v) in self.headers if
113 116 k in ('Date', 'ETag', 'Expires',
114 117 'Cache-Control', 'Vary')]
115 118 status = statusmessage(status.code, str(status))
116 119 elif status == 200:
117 120 status = '200 Script output follows'
118 121 elif isinstance(status, int):
119 122 status = statusmessage(status)
120 123
121 124 self.server_write = self._start_response(status, self.headers)
122 125 self._start_response = None
123 126 self.headers = []
124 127 if body is not None:
125 128 self.write(body)
126 129 self.server_write = None
127 130
128 131 def write(self, thing):
129 132 if thing:
130 133 try:
131 134 self.server_write(thing)
132 135 except socket.error as inst:
133 136 if inst[0] != errno.ECONNRESET:
134 137 raise
135 138
136 139 def writelines(self, lines):
137 140 for line in lines:
138 141 self.write(line)
139 142
140 143 def flush(self):
141 144 return None
142 145
143 146 def close(self):
144 147 return None
145 148
146 149 def wsgiapplication(app_maker):
147 150 '''For compatibility with old CGI scripts. A plain hgweb() or hgwebdir()
148 151 can and should now be used as a WSGI application.'''
149 152 application = app_maker()
150 153 def run_wsgi(env, respond):
151 154 return application(env, respond)
152 155 return run_wsgi
General Comments 0
You need to be logged in to leave comments. Login now