1 #!/usr/bin/env python 2 3 """ 4 Webware classes. 5 """ 6 7 import Generic 8 from cgi import parse_qs 9 import StringIO 10 from Helpers import Environment 11 from Helpers.Request import Cookie 12 from Helpers.Response import ConvertingStream 13 14 class Transaction(Generic.Transaction): 15 16 """ 17 Webware transaction interface. 18 """ 19 20 def __init__(self, trans): 21 22 "Initialise the transaction using the Webware transaction 'trans'." 23 24 self.trans = trans 25 self.user = None 26 self.content_type = None 27 28 # Request-related methods. 29 30 def get_request_stream(self): 31 32 """ 33 Returns the request stream for the transaction. 34 """ 35 36 request = self.trans.request() 37 try: 38 stream = request.rawInput(rewind=1) 39 if stream is None: 40 return StringIO.StringIO("") 41 42 # NOTE: Dubious catch-all situation, but it is difficult to control 43 # NOTE: cases where Webware's internals themselves fail. 44 45 except: 46 return StringIO.StringIO("") 47 48 return stream 49 50 def get_request_method(self): 51 52 """ 53 Returns the request method. 54 """ 55 56 return self.trans.request().method() 57 58 def get_headers(self): 59 60 """ 61 Returns all request headers as a dictionary-like object mapping header 62 names to values. 63 64 NOTE: If duplicate header names are permitted, then this interface will 65 NOTE: need to change. 66 """ 67 68 # Use the Webware environment and some assumptions about variable names. 69 # NOTE: Using lower case for the header names. 70 71 env = self.trans.request().environ() 72 return Environment.get_headers(env) 73 74 def get_header_values(self, key): 75 76 """ 77 Returns a list of all request header values associated with the given 78 'key'. Note that according to RFC 2616, 'key' is treated as a 79 case-insensitive string. 80 """ 81 82 # Use the Webware environment and some assumptions about variable names. 83 84 env = self.trans.request().environ() 85 cgi_key = "HTTP_" + key.replace("-", "_").upper() 86 if env.has_key(cgi_key): 87 return [env[cgi_key]] 88 else: 89 return [] 90 91 def get_content_type(self): 92 93 """ 94 Returns the content type specified on the request, along with the 95 charset employed. 96 """ 97 98 return self.parse_content_type(self.trans.request().contentType()) 99 100 def get_content_charsets(self): 101 102 """ 103 Returns the character set preferences. 104 NOTE: Requires enhancements to HTTPRequest. 105 """ 106 107 return self.trans.request().contentCharsets() 108 109 def get_content_languages(self): 110 111 """ 112 Returns extracted language information from the transaction. 113 NOTE: Requires enhancements to HTTPRequest. 114 """ 115 116 return self.trans.request().contentLanguages() 117 118 def get_path(self): 119 120 """ 121 Returns the entire path from the request. 122 """ 123 124 return self.trans.request().uri() 125 126 def get_path_without_query(self): 127 128 """ 129 Returns the entire path from the request minus the query string. 130 """ 131 132 return self.get_path().split("?")[0] 133 134 def get_path_info(self): 135 136 """ 137 Returns the "path info" (the part of the URL after the resource name 138 handling the current request) from the request. 139 """ 140 141 return self.trans.request().extraURLPath() 142 143 def get_query_string(self): 144 145 """ 146 Returns the query string from the path in the request. 147 """ 148 149 return self.trans.request().queryString() 150 151 # Higher level request-related methods. 152 153 def get_fields_from_path(self): 154 155 """ 156 Extracts the form fields from the path specified in the transaction. The 157 underlying framework may refuse to supply fields from the path if 158 handling a POST transaction. 159 160 Returns a dictionary mapping field names to lists of values (even if a 161 single value is associated with any given field name). 162 """ 163 164 return parse_qs(self.get_query_string(), keep_blank_values=1) 165 166 def get_fields_from_body(self, encoding=None): 167 168 """ 169 Extracts the form fields from the message body in the transaction. The 170 optional 'encoding' parameter specifies the character encoding of the 171 message body for cases where no such information is available, but where 172 the default encoding is to be overridden. 173 174 Returns a dictionary mapping field names to lists of values (even if a 175 single value is associated with any given field name). 176 """ 177 178 encoding = self.get_content_type().charset or encoding or "iso-8859-1" 179 180 # Fix the non-list results. 181 182 fields = {} 183 for field_name, field_values in self.trans.request().fields().items(): 184 if type(field_values) == type([]): 185 fields[field_name] = [] 186 for field_value in field_values: 187 fields[field_name].append(unicode(field_value, encoding)) 188 else: 189 fields[field_name] = [unicode(field_values, encoding)] 190 return fields 191 192 def get_user(self): 193 194 """ 195 Extracts user information from the transaction. 196 197 Returns a username as a string or None if no user is defined. 198 """ 199 200 # NOTE: Webware relies entirely on a CGI-style environment where the 201 # NOTE: actual headers are not available. Therefore, the Web server must 202 # NOTE: itself be set up to provide user support. 203 204 if self.user is not None: 205 return self.user 206 207 try: 208 return self.trans.request().remoteUser() 209 except KeyError, exc: 210 return None 211 212 def get_cookies(self): 213 214 """ 215 Obtains cookie information from the request. 216 217 Returns a dictionary mapping cookie names to cookie objects. 218 """ 219 220 cookies = {} 221 for name, value in self.trans.request().cookies().items(): 222 cookies[name] = Cookie(name, value) 223 return cookies 224 225 def get_cookie(self, cookie_name): 226 227 """ 228 Obtains cookie information from the request. 229 230 Returns a cookie object for the given 'cookie_name' or None if no such 231 cookie exists. 232 """ 233 234 try: 235 return Cookie(cookie_name, self.trans.request().cookie(cookie_name)) 236 except KeyError: 237 return None 238 239 # Response-related methods. 240 241 def get_response_stream(self): 242 243 """ 244 Returns the response stream for the transaction. 245 """ 246 247 # Unicode can upset this operation. Using either the specified charset, 248 # the same charset as that used in the request, or a default encoding. 249 250 encoding = self.get_content_type().charset or "utf-8" 251 if self.content_type: 252 encoding = self.content_type.charset or encoding 253 return ConvertingStream(self.trans.response(), encoding) 254 255 def get_response_code(self): 256 257 """ 258 Get the response code associated with the transaction. If no response 259 code is defined, None is returned. 260 """ 261 262 # NOTE: Webware treats the response code as just another header. 263 264 status = self.trans.response().header("Status", None) 265 try: 266 if status is not None: 267 return int(status) 268 else: 269 return None 270 except ValueError: 271 return None 272 273 def set_response_code(self, response_code): 274 275 """ 276 Set the 'response_code' using a numeric constant defined in the HTTP 277 specification. 278 """ 279 280 self.trans.response().setStatus(response_code) 281 282 def set_header_value(self, header, value): 283 284 """ 285 Set the HTTP 'header' with the given 'value'. 286 """ 287 288 self.trans.response().setHeader(self.format_header_value(header), self.format_header_value(value)) 289 290 def set_content_type(self, content_type): 291 292 """ 293 Sets the 'content_type' for the response. 294 """ 295 296 # Remember the content type for encoding purposes later. 297 298 self.content_type = content_type 299 return self.trans.response().setHeader("Content-Type", self.format_content_type(content_type)) 300 301 # Higher level response-related methods. 302 303 def set_cookie(self, cookie): 304 305 """ 306 Stores the given 'cookie' object in the response. 307 """ 308 309 self.trans.response().addCookie(cookie) 310 311 def set_cookie_value(self, name, value, path=None, expires=None): 312 313 """ 314 Stores a cookie with the given 'name' and 'value' in the response. 315 316 The optional 'path' is a string which specifies the scope of the cookie, 317 and the optional 'expires' parameter is a value compatible with the 318 time.time function, and indicates the expiry date/time of the cookie. 319 """ 320 321 self.trans.response().setCookie(name, value, path, expires) 322 323 def delete_cookie(self, cookie_name): 324 325 """ 326 Adds to the response a request that the cookie with the given 327 'cookie_name' be deleted/discarded by the client. 328 """ 329 330 self.trans.response().delCookie(cookie_name) 331 332 # Session-related methods. 333 334 def get_session(self, create=1): 335 336 """ 337 Gets a session corresponding to an identifier supplied in the 338 transaction. 339 340 If no session has yet been established according to information 341 provided in the transaction then the optional 'create' parameter 342 determines whether a new session will be established. 343 344 Where no session has been established and where 'create' is set to 0 345 then None is returned. In all other cases, a session object is created 346 (where appropriate) and returned. 347 """ 348 349 # NOTE: Should really use Webware's hasSession method. 350 351 session = self.trans.session() 352 return Session(session) 353 354 def expire_session(self): 355 356 """ 357 Expires any session established according to information provided in the 358 transaction. 359 """ 360 361 self.trans.request().setSessionExpired(1) 362 363 # Application-specific methods. 364 365 def set_user(self, username): 366 367 """ 368 An application-specific method which sets the user information with 369 'username' in the transaction. This affects subsequent calls to 370 'get_user'. 371 """ 372 373 self.user = username 374 375 class Session: 376 377 "A more dictionary-like session object than the one Webware provides." 378 379 def __init__(self, session): 380 self.session = session 381 382 def items(self): 383 return self.session.values().items() 384 385 def __getattr__(self, name): 386 return getattr(self.__dict__["session"], name) 387 388 # vim: tabstop=4 expandtab shiftwidth=4