Package library :: Package pyjamas :: Module HTTPRequest
[hide private]
[frames] | no frames]

Source Code for Module library.pyjamas.HTTPRequest

  1  # This is the gtk-dependent HTTPRequest module. 
  2  # For the pyjamas/javascript version, see platform/HTTPRequestPyJS.py 
  3   
  4  import pyjd 
  5  import pygwt 
  6  from __pyjamas__ import JS 
  7  if pyjd.is_desktop: 
  8      from __pyjamas__ import get_main_frame 
  9  import sys # needed by __browser__/pyjamas/HTTPRequest.py 
 10  handlers = {} 
 11   
12 -class XULrunnerHackCallback(object):
13 - def __init__(self, htr, mode, user, pwd, url, postData=None, handler=None, 14 return_xml=False, content_type=None, headers = None):
15 pass
16
17 - def callback(self):
18 return self.htr.asyncImpl(self.mode, self.user, self.pwd, self.url, 19 self.postData, self.handler, self.return_xml, 20 self.content_type, self.headers)
21 22
23 -class HTTPRequest(object):
24 - def asyncGet(self, url, handler, returnxml=False, 25 content_type=None, headers=None, user=None, pwd=None):
26 postData = None 27 if not hasattr(handler, 'onCompletion'): 28 raise RuntimeError("Invalid call to asyncGet: handler is not a valid request handler") 29 return self.asyncImpl('GET', user, pwd, url, postData, handler, 30 returnxml, content_type, headers)
31
32 - def asyncPost(self, url, postData, handler, returnxml=False, 33 content_type=None, headers=None, user=None, pwd=None):
34 if not hasattr(handler, 'onCompletion'): 35 raise RuntimeError("Invalid call to asyncPost: handler is not a valid request handler") 36 return self.asyncImpl('POST', user, pwd, url, postData, handler, 37 returnxml, content_type, headers)
38
39 - def asyncDelete(self, url, handler, returnxml=False, 40 content_type=None, headers=None, user=None, pwd=None):
41 postData = None 42 if not hasattr(handler, 'onCompletion'): 43 raise RuntimeError("Invalid call to asyncDelete: handler is not a valid request handler") 44 return self.asyncImpl('DELETE', user, pwd, url, postData, handler, 45 returnxml, content_type, headers)
46
47 - def asyncPut(self, url, postData, handler, returnxml=False, 48 content_type=None, headers=None, user=None, pwd=None):
49 if not hasattr(handler, 'onCompletion'): 50 raise RuntimeError("Invalid call to asyncPut: handler is not a valid request handler") 51 return self.asyncImpl('PUT', user, pwd, url, postData, handler, 52 returnxml, content_type, headers)
53
54 - def createXmlHTTPRequest(self):
55 return self.doCreateXmlHTTPRequest()
56
57 - def doCreateXmlHTTPRequest(self):
58 return get_main_frame().getXmlHttpRequest()
59
60 - def onProgress(self, sender, event, ignorearg):
61 xmlHttp = event.target 62 localHandler = handlers.get(xmlHttp) 63 if hasattr(localHandler, "onProgress"): 64 localHandler.onProgress(event)
65
66 - def onLoad(self, sender, event, ignorearg):
67 xmlHttp = event.target 68 localHandler = handlers.get(xmlHttp) 69 del handlers[xmlHttp] 70 responseText = xmlHttp.responseText 71 status = xmlHttp.status 72 handler = None 73 xmlHttp = None 74 # XXX HACK! webkit wrapper returns 0 not 200! 75 if status == 0: 76 print "HACK ALERT! webkit wrapper returns 0 not 200!" 77 if status == 200 or status == 0: 78 localHandler.onCompletion(responseText) 79 else : 80 localHandler.onError(responseText, status)
81
82 - def onReadyStateChange(self, xmlHttp, event, ignorearg):
83 try: 84 xmlHttp = get_main_frame().gobject_wrap(xmlHttp) # HACK! 85 except: 86 pass # hula / XUL 87 #print xmlHttp.readyState 88 if xmlHttp.readyState != 4: 89 return 90 # TODO - delete xmlHttp.onreadystatechange 91 localHandler = handlers.get(xmlHttp) 92 del handlers[xmlHttp] 93 responseText = xmlHttp.responseText 94 #print "headers", xmlHttp.getAllResponseHeaders() 95 status = xmlHttp.status 96 handler = None 97 xmlHttp = None 98 #print "status", status 99 #print "local handler", localHandler 100 # XXX HACK! webkit wrapper returns 0 not 200! 101 #if status == 0: 102 # print "HACK ALERT! webkit wrapper returns 0 not 200!" 103 if status == 200 or status == 0: 104 localHandler.onCompletion(responseText) 105 else : 106 localHandler.onError(responseText, status)
107
108 - def _convertUrlToAbsolute(self, url):
109 110 uri = pygwt.getModuleBaseURL() 111 if url[0] == '/': 112 # url is /somewhere. 113 sep = uri.find('://') 114 if not uri.startswith('file://'): 115 116 slash = uri.find('/', sep+3) 117 if slash > 0: 118 uri = uri[:slash] 119 120 return "%s%s" % (uri, url) 121 122 else: 123 if url[:7] != 'file://' and url[:7] != 'http://' and \ 124 url[:8] != 'https://': 125 slash = uri.rfind('/') 126 return uri[:slash+1] + url 127 128 return url
129
130 - def asyncImpl(self, method, user, pwd, url, postData, handler, 131 returnxml=False, content_type=None, headers=None):
132 if headers is None: 133 headers = {} 134 if user and pwd and not "Authorization" in headers: 135 import base64 136 headers["Authorization"] = 'Basic %s' % (base64.b64encode('%s:%s' % (user, pwd))) 137 138 mf = get_main_frame() 139 if content_type is not None: 140 headers["Content-Type"] = content_type 141 if not "Content-Type" in headers: 142 if returnxml: 143 headers["Content-Type"] = "application/xml; charset=utf-8" 144 else: 145 headers["Content-Type"] = "text/plain; charset=utf-8" 146 147 #for c in Cookies.get_crumbs(): 148 # xmlHttp.setRequestHeader("Set-Cookie", c) 149 # print "setting cookie", c 150 151 xmlHttp = self.doCreateXmlHTTPRequest() 152 url = self._convertUrlToAbsolute(url) 153 154 #print "xmlHttp", method, user, pwd, url, postData, handler, dir(xmlHttp) 155 156 if mf.platform == 'webkit': 157 mf._addXMLHttpRequestEventListener( 158 xmlHttp, "readystatechange", self.onReadyStateChange, 159 ) 160 elif mf.platform == 'mshtml': 161 mf._addXMLHttpRequestEventListener( 162 xmlHttp, "onreadystatechange", self.onReadyStateChange, 163 ) 164 else: 165 mf._addXMLHttpRequestEventListener( 166 xmlHttp, "load", self.onLoad, 167 ) 168 169 if mf.platform != 'mshtml' and mf.platform != 'ie6': 170 mf._addXMLHttpRequestEventListener( 171 xmlHttp, "progress", self.onProgress, 172 ) 173 174 #try : 175 if mf.platform == 'webkit' or mf.platform == 'mshtml': 176 xmlHttp.open(method, url, True, '', '') 177 else: 178 # EEK! xmlhttprequest.open in xpcom is a miserable bastard. 179 try: 180 res = xmlHttp.open(method, url, True, '', '') 181 except: 182 res = xmlHttp.open(method, url) 183 #print url, res 184 for h in headers: 185 if isinstance(headers[h], basestring): 186 xmlHttp.setRequestHeader(h, headers[h]) 187 else: 188 hval = ';'.join([str(i) for i in headers[h]]) 189 xmlHttp.setRequestHeader(h, hval) 190 #if not "Set-Cookie" in headers: 191 # headers["Set-Cookie"] = [] 192 #for c in Cookies.get_crumbs(): 193 # headers["Set-Cookie"].append(c) 194 # print "setting cookie", c 195 196 handlers[xmlHttp] = handler 197 try: 198 xmlHttp.send(postData or '') 199 except: 200 handler.onError("xmlHttp.send error", -1) 201 202 return xmlHttp 203 204 #except: 205 #del xmlHttp.onreadystatechange 206 handler = None 207 xmlHttp = None 208 localHandler.onError(str(e)) 209 return None
210