def loadPageList(self): HTTPRequest().asyncGet("sidebar.html", PageLoader(self, "sidebar", "contents")) HTTPRequest().asyncGet("header.html", PageLoader(self, "header", "contents")) HTTPRequest().asyncGet("footer.html", PageLoader(self, "footer", "contents")) HTTPRequest().asyncGet("contents.txt", PageListLoader(self, "contents"))
def __init__(self, host, url, method="GET"): """ Initialize the instance with the host, the request URL, and the method ("GET" or "POST") """ logging.Handler.__init__(self) method = method.upper() if method not in ["GET", "POST"]: raise ValueError, "method must be GET or POST" self.host = host self.url = url self.method = method self.httpRequest = HTTPRequest()
def do_test(self, output, name): handler = GetTestOutput(self, self.current_test_name, output) if name: fname = "%s.%s.txt" % (self.current_test_name, name) else: fname = "%s.txt" % self.current_test_name HTTPRequest().asyncGet(fname, handler)
def onShow(self): if self.loaded: return name = self.name.replace(" ", "_") name = name.lower() HTTPRequest().asyncGet("%s.txt" % name, SlideLoader(self))
def LoadStaticObjects(self): params = urllib.urlencode({"edgeids": []}) HTTPRequest().asyncPost( url="/StaticObjects", handler=self, returnxml=False, postData=params, content_type="application/x-www-form-urlencoded")
def onShow(self): if self.loaded: return self.name = self.name.replace(" ", "_") self.name = self.name.lower() HTTPRequest().asyncGet("%s.txt" % self.name, ChapterLoader(self))
def createPage(self, title, purpose, text): #log.debug("create page %s %s %s", title, purpose, text) if purpose == 'faq': self.faq_pages[title] = text log.debug("%d %d", len(self.faq_pages), len(self.faq_list)) #log.debug(self.faq_pages.keys()) #log.debug(self.faq_list) if len(self.faq_pages) != len(self.faq_list): return faq = self.page_widgets['FAQ'] for l in self.faq_list: question = l[0] answer = self.faq_pages[question] html = faq.getHTML() html += "<h3>%s</h3>\n" % question html += "\n%s\n\n" % answer faq.setHTML(html) html = "<div class='faq'>\n%s</div>\n" % html faq.setHTML(html) faq.replaceLinks(use_page_href=False) return if title == 'header': self.header.setHTML(text) return elif title == 'footer': self.footer.setHTML(text) return elif title == 'sidebar': self.sidebar.setHTML(text) return # Main content case - tabs etc. self.pages[title] = text if len(self.pages) != len(self.page_list): return self.page_widgets = {} self.tab_index = {} for (idx, l) in enumerate(self.page_list): title = l[0] text = self.pages[title] self.tab_index[title] = idx widget = HTMLLinkPanel(text) self.fTabs.add(widget, title, True) self.page_widgets[title] = widget if title == 'FAQ': HTTPRequest().asyncGet("faq/questions.txt", PageListLoader(self, "faq")) else: widget.replaceLinks(use_page_href=False) self.fTabs.selectTab(0) History.addHistoryListener(self) initToken = History.getToken() log.debug("initial token: '%s'", initToken) self.onHistoryChanged(initToken) self.fTabs.addTabListener(self)
def downvote(): data = {} data['movie_id'] = str(mainpage.mid) data['rating'] = '1' data['apikey'] = '9GQWe8XVSy' text = dumps(data) HTTPRequest().asyncPut( "http://student02.cse.nd.edu:40001/recommendations/156", text, PutCtrl(self))
def doCommand(self): params = urllib.urlencode({"requestsize": self.requestsize}) HTTPRequest().asyncPost( url="/GetUUIDs", handler=self, returnxml=False, postData=params, content_type="application/x-www-form-urlencoded", headers={})
class PyjamasExternalModule: PyjamasExternalModule.http = HTTPRequest() def __init__(self, mod_name): self.base = 'http://' + JS('''__location.host''') req = '{"method":"methods","params":["%s"],"id":1}' % (mod_name) res = PyjamasExternalModule.http.syncPost(self.base + '/obj/handler', req) self.methods = self.__parseJSON(res)['result'] self.module = mod_name for method in self.methods: self.__createMethod(method) def __encodeJSON(self, obj): JS(''' var t = typeof(@{{obj}}); if(@{{obj}}==null) { return 'null'; }else if(t=='number') { return ''+@{{obj}}; }else if(t=='string'){ return '"'+@{{obj}}+'"' }else if(@{{isinstance}}([@{{obj}},@{{list}}],{})) { var parts = []; for(var i=0; i<@{{obj}}.length; i++) { parts.append([ @{{self}}.__encodeJSON([@{{obj}}[i]],{}) ],{}); } return "[" + ','.join([parts],{}) + "]"; }else{ throw "Dicts and Objectss can not be jsoned !"; } ''') def __parseJSON(self, str): JS(r""" try { return (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(@{{str}})) && eval('(' + @{{str}} + ')'); } catch (e) { return false; } """) def __createMethod(self, method): def inner(*args, **kargs): params = self.__encodeJSON(args) req = '{"method":"call","params":["%s", "%s", %s],"id":2}' % ( self.module, method, params) res = PyjamasExternalModule.http.syncPost( self.base + '/obj/handler', req) return self.__parseJSON(res)['result'] JS(""" @{{self}}[@{{method}}] = @{{inner}}; """)
def run(self): edgeids = JSONEncoder( DocumentCollection.documentcollection.GetAllEdgeIDs()) params = urllib.urlencode({"edgeids": edgeids}) HTTPRequest().asyncPost( url="/StaticObjects", handler=self, returnxml=False, postData=params, content_type="application/x-www-form-urlencoded")
def findRating(inp): try: int(inp) INT = 1 except ValueError: INT = 0 if INT == 1: HTTPRequest().asyncGet( "http://student02.cse.nd.edu:40001/ratings/" + str(inp), currentRating(self))
def findMovie(inp): try: int(inp) INT = 1 except ValueError: INT = 0 if INT == 1: HTTPRequest().asyncGet( "http://student02.cse.nd.edu:40001/movies/" + str(inp), currentMovie(self)) else: movie.setText("Movie not Found. Please Enter an Integer ID")
def run(self): assert isinstance(self.edges, list) if len(self.edges) == 0: return #Another schuled task send our edges so do nothin params = urllib.urlencode({"edges": JSONEncoder(self.edges)}) HTTPRequest().asyncPost( url="/UploadEdges", handler=self, returnxml=False, postData=params, content_type="application/x-www-form-urlencoded") del self.edges[:] #delete the contents of the edge queue
def loadPages(self, pages, purpose): if purpose == 'contents': self.pages = {} self.page_list = pages elif purpose == 'faq': self.faq_pages = {} self.faq_list = pages for l in pages: title = l[0] desc = l[1] HTTPRequest().asyncGet(desc, PageLoader(self, title, purpose))
def saveTemplateText(self, html): """ Save the text. This method can be overridden to use a different save method. The default is to POST to the template save URL, passing a single parameter "content" with the html string. To change the target of the POST, override getTemplateSaveUrl(). To preprocess the html, override this method in a subclass and perform processing there. """ HTTPRequest().asyncPost(self.getTemplateSaveUrl(self.templateName), "content=" + encodeURIComponent(html), ContentSaveHandler(self))
def createPage(self, title, purpose, text): if purpose == 'faq': self.faq_pages[title] = text if len(self.faq_pages) != len(self.faq_list): return faq = self.page_widgets['FAQ'] for l in self.faq_list: question = l[0] answer = self.faq_pages[question] html = faq.getHTML() html += "<h3>%s</h3>\n" % question html += "\n%s\n\n" % answer faq.setHTML(html) html = "<div class='faq'>\n%s</div>\n" % html faq.setHTML(html) faq.replaceLinks(use_page_href=False) return if title == 'header': self.header.setHTML(text) return elif title == 'footer': self.footer.setHTML(text) return elif title == 'sidebar': self.sidebar.setHTML(text) return self.pages[title] = text if len(self.pages) != len(self.page_list): return self.page_widgets = {} self.tab_index = {} for (idx, l) in enumerate(self.page_list): title = l[0] text = self.pages[title] self.tab_index[title] = idx widget = HTMLLinkPanel(text) self.fTabs.add(widget, title, True) self.page_widgets[title] = widget if title == 'FAQ': HTTPRequest().asyncGet("faq/questions.txt", PageListLoader(self, "faq")) else: widget.replaceLinks(use_page_href=False) self.fTabs.selectTab(0)
def onRemoteResponse(self, response, request_info): '''When we got data from JSON proxy fire up another method on the service that returns something. ''' msg = response['msg'] if msg == 'send_data': HTTPRequest().asyncGet('/success/', self, content_type='text/html') if msg == 'get_active_projects': data = json.loads(response['data']) proj_list = self.view.proj_row.widget() for row in data: proj_list.addItem(row[1]) if msg == 'get_active_milestones': data = json.loads(response['data']) milestone_names = [] milestone_dates = [] for row in data: milestone_names.append(row[1]) milestone_dates.append(row[4]) self.view.dev_fields.milestone_names = milestone_names self.view.dev_fields.milestone_dates = milestone_dates if msg == 'get_report_for_project': data = json.loads(response['data']) # TODO: set data here all_milestones = data['all_milestones'] milestone_names = [] milestone_dates = [] for row in all_milestones: milestone_names.append(row[1]) milestone_dates.append(row[4]) self.view.dev_fields.milestone_names = milestone_names self.view.dev_fields.milestone_dates = milestone_dates if data is not None: self._populate_fields(data)
class TemplatePanel(ComplexPanel): """ Panel which allows you to attach or insert widgets into a pre-defined template. We don't do any caching of our own, since the browser will do caching for us, and probably more efficiently. """ templateRoot = "" # XXX What is this text expression supposed to do? It won't be # added to the docstring as it is. """Set staticRoot to change the base path of all the templates that are loaded; templateRoot should have a trailing slash""" def __init__(self, templateName, allowEdit=False): ComplexPanel.__init__(self) self.loaded = False # Set after widgets are attached self.widgetsAttached = False self.id = None self.templateName = None self.title = None self.elementsById = {} self.metaTags = {} self.body = None self.links = [] self.forms = [] self.metaTagList = [] self.loadListeners = [] self.toAttach = [] self.toInsert = [] self.setElement(DOM.createDiv()) self.editor = None self.allowEdit = allowEdit if templateName: self.loadTemplate(templateName) def getTemplatePath(self, templateName): return self.templateRoot+'tpl/'+templateName+'.html' def loadTemplate(self, templateName): self.templateName = templateName self.id = templateName + str(hash(self)) self.httpReq = HTTPRequest() self.httpReq.asyncGet(self.getTemplatePath(templateName), TemplateLoader(self)) def getCurrentTemplate(self): """Return the template that is currently loaded, or is loading.""" return self.templateName def isLoaded(self): """Return True if the template is finished loading.""" return self.loaded def areWidgetsAttached(self): """Return True if the template is loaded and attachWidgets() has been called.""" return self.widgetsAttached def setTemplateText(self, text): """ Set the template text; if the template is not HTML, a subclass could override this to pre-process the text into HTML before passing it to the default implementation. """ if self.allowEdit: self.originalText = text # If we have children, remove them all first since we are # trashing their DOM for child in List(self.children): self.remove(child) DOM.setInnerHTML(self.getElement(), text) self.elementsById = {} self.links = [] self.metaTags = {} self.forms = [] self.metaTagList = [] # Make the ids unique and store a pointer to each named element for node in DOM.walkChildren(self.getElement()): #console.log("Passing node with name %s", node.nodeName) if node.nodeName == "META": name = node.getAttribute("name") content = node.getAttribute("content") console.log("Found meta %o name %s content %s", node, name, content) self.metaTags[name] = content self.metaTagList.append(node) elif node.nodeName == "BODY": self.body = node elif node.nodeName == "TITLE": self.title = DOM.getInnerText(node) elif node.nodeName == "FORM": self.forms.append(node) nodeId = DOM.getAttribute(node, "id") if nodeId: self.elementsById[nodeId] = node DOM.setAttribute(node, "id", self.id + ":" + node.id) nodeHref = DOM.getAttribute(node, "href") if nodeHref: self.links.append(node) self.loaded = True if self.attached: self.attachWidgets() self.widgetsAttached = True if self.allowEdit: self.editor = None self.editButton = Label("edit "+unescape(self.templateName)) self.editButton.addStyleName("link") self.editButton.addStyleName("ContentPanelEditLink") self.editButton.addClickListener(EventDelegate("onClick", self, self.onEditContentClick)) ComplexPanel.insert(self, self.editButton, self.getElement(), len(self.children)) self.notifyLoadListeners() def onError(self, html, statusCode): if statusCode == 404 and self.allowEdit: self.editor = None self.originalText = "" DOM.setInnerHTML(self.getElement(), '') self.editButton = Label("create "+unescape(self.templateName)) self.editButton.addStyleName("link") self.editButton.addStyleName("ContentPanelEditLink") self.editButton.addClickListener(EventDelegate("onClick", self, self.onEditContentClick)) ComplexPanel.insert(self, self.editButton, self.getElement(), len(self.children)) return # Show the page we got in an iframe, which will hopefully show # the error better than we can. # DOM.setInnerHTML(self.getElement(), '<iframe src="'+self.getTemplatePath(self.templateName)+'"/>') def onTimeout(self, text): self.onError("Page loading timed out: "+text) def getElementsById(self): """Return a dict mapping an id to an element with that id inside the template; useful for post-processing.""" return self.elementsById def getLinks(self): """Return a list of all the A HREF= elements found in the template.""" return self.links def getForms(self): """Return a list of all the FORM elements found in the template.""" return self.forms def onAttach(self): if not self.attached: SimplePanel.onAttach(self) if self.loaded and not self.widgetsAttached: self.attachWidgets() self.widgetsAttached = True def attachWidgets(self): """ Attach and insert widgets into the DOM now that it has been loaded. If any widgets were attached before loading, they will have been queued and the default implementation will attach them. Override this in subclasses to attach your own widgets after loading. """ for attach in self.toAttach: self.attach(attach.name, attach.widget) for insert in self.toInsert: self.insert(insert.name, insert.widget) def getElementById(self, id): return self.elementsById[id] def insert(self, id, widget): """ Insert a widget into the element with the given id, at the end of its children. """ if not self.loaded: self.toInsert.append(PendingAttachOrInsert(id, widget)) else: element = self.getElementById(id) if element: self.adopt(widget, element) self.children.append(widget) else: console.error("Page error: No such element " + id) return widget def attachToElement(self, element, widget): events = DOM.getEventsSunk(widget.getElement()) widget.unsinkEvents(events) widget.setElement(element) widget.sinkEvents(events) self.adopt(widget, None) self.children.append(widget) def replaceElement(self, element, widget): """Replace an existing element with the given widget.""" DOM.getParent(element).replaceChild(widget.getElement(), element) self.adopt(widget, None) self.children.append(widget) def attach(self, id, widget): """ Attach a widget onto the element with the given id; the element currently associated with the widget is discarded. """ if not self.loaded: self.toAttach.append(PendingAttachOrInsert(id, widget)) else: element = self.getElementById(id) if element: self.attachToElement(element, widget) else: console.error("Page error: No such element " + id) return widget def getMeta(self, name): """ Get the value of a meta-variable found in the template, or None if no meta tags were found with the given name. """ return self.metaTags.get(name) def getTitle(self): """Return a user-friendly title for the page.""" if self.title: return self.title else: return self.templateName def addLoadListener(self, listener): """ The listener should be a function or an object implementing onTemplateLoaded. It will be called this TemplatePanel instance after the template has been loaded and after attachWidgets() is called. """ self.loadListeners.append(listener) def removeLoadListener(self, listener): self.loadListeners.remove(listener) def notifyLoadListeners(self): for listener in self.loadListeners: if listener.onTemplateLoaded: listener.onTemplateLoaded(self) else: listener(self) def onEditContentClick(self, sender): if self.editor: editor = self.editor self.editor = None ComplexPanel.remove(self, editor) self.editButton.setText("edit " + unescape(self.templateName)) else: self.editor = RichTextEditor(self.originalText) self.editor.addSaveListener(self) ComplexPanel.insert(self, self.editor, self.getElement(), len(self.children)) self.editButton.setText("close editor") def getTemplateSaveUrl(self, templateName): """ Get the URL to post a template to when it is saved in the editor. """ return self.getTemplatePath(templateName) def saveTemplateText(self, html): """ Save the text. This method can be overridden to use a different save method. The default is to POST to the template save URL, passing a single parameter "content" with the html string. To change the target of the POST, override getTemplateSaveUrl(). To preprocess the html, override this method in a subclass and perform processing there. """ HTTPRequest().asyncPost(self.getTemplateSaveUrl(self.templateName), "content=" + encodeURIComponent(html), ContentSaveHandler(self)) def onSave(self, sender): """Called when the user clicks save in the content editor.""" html = self.editor.getHTML() self.saveTemplateText(html) def onSaveComplete(self): """ Called when the template was successfully POSTed to the server; it reloads the template. Subclasses which don't use the default method of saving may want to call this after they successfully save the template. """ self.loadTemplate(self.templateName)
def onModuleLoad(self): HTTPRequest().asyncGet( "address_form.ui", XMLloader(self), )
def onCompletion(self, text): HTTPRequest().asyncGet( "http://student02.cse.nd.edu:40001/recommendations/156", getRec(self))
def loadTemplate(self, templateName): self.templateName = templateName self.id = templateName + str(hash(self)) self.httpReq = HTTPRequest() self.httpReq.asyncGet(self.getTemplatePath(templateName), TemplateLoader(self))
def get_request(after, file_name=file_name): handler = SlideListLoader(after) HTTPRequest().asyncGet(file_name, handler)
def post_request(content): HTTPRequest().asyncPost("http://api.myjson.com/bins/", dumps(content), SlideListLoader(IO.apos), headers={'Content-Type': 'application/json'})
class HTTPHandler(logging.Handler): """ A class which sends records to a Web server, using either GET or POST semantics. """ def __init__(self, host, url, method="GET"): """ Initialize the instance with the host, the request URL, and the method ("GET" or "POST") """ logging.Handler.__init__(self) method = method.upper() if method not in ["GET", "POST"]: raise ValueError, "method must be GET or POST" self.host = host self.url = url self.method = method self.httpRequest = HTTPRequest() def onCompletion(self, response): pass def onError(self, response, status): pass def mapLogRecord(self, record): """ Default implementation of mapping the log record into a dict that is sent as the CGI data. Overwrite in your class. Contributed by Franz Glasner. """ return record.toDict() def emit(self, record): """ Emit a record. Send the record to the Web server as an URL-encoded dictionary """ try: host = self.host url = self.url data = urllib.urlencode(self.mapLogRecord(record)) if self.method == "GET": if (url.find('?') >= 0): sep = '&' else: sep = '?' url = url + "%c%s" % (sep, data) # support multiple hosts on one IP address... # need to strip optional :port from host, if present i = host.find(":") if i >= 0: host = host[:i] headers = {} headers["Host"] = host if self.method == "POST": self.httpRequest.asyncPost( url, data, self, content_type="application/x-www-form-urlencoded", headers=headers) else: self.httpRequest.asyncGet(url, self) except: self.handleError(record)
def loadPage(self, filename): HTTPRequest().asyncGet(filename + ".txt", SlideLoader(self))
def put_request(content, file_name=file_name): HTTPRequest().asyncPut(file_name, dumps(content), SlideListLoader(IO.apos), headers={'Content-Type': 'application/json'})
class HTTPHandler(logging.Handler): """ A class which sends records to a Web server, using either GET or POST semantics. """ def __init__(self, host, url, method="GET"): """ Initialize the instance with the host, the request URL, and the method ("GET" or "POST") """ logging.Handler.__init__(self) method = method.upper() if method not in ["GET", "POST"]: raise ValueError, "method must be GET or POST" self.host = host self.url = url self.method = method self.httpRequest = HTTPRequest() def onCompletion(self, response): pass def onError(self, response, status): pass def mapLogRecord(self, record): """ Default implementation of mapping the log record into a dict that is sent as the CGI data. Overwrite in your class. Contributed by Franz Glasner. """ return record.toDict() def emit(self, record): """ Emit a record. Send the record to the Web server as an URL-encoded dictionary """ try: host = self.host url = self.url data = urllib.urlencode(self.mapLogRecord(record)) if self.method == "GET": if (url.find('?') >= 0): sep = '&' else: sep = '?' url = url + "%c%s" % (sep, data) # support multiple hosts on one IP address... # need to strip optional :port from host, if present i = host.find(":") if i >= 0: host = host[:i] headers = {} headers["Host"] = host if self.method == "POST": self.httpRequest.asyncPost(url, data, self, content_type="application/x-www-form-urlencoded", headers=headers) else: self.httpRequest.asyncGet(url, self) except: self.handleError(record)
def loadSinks(self): HTTPRequest().asyncGet("contents.txt", ChapterListLoader(self))
def loadSinks(self): HTTPRequest().asyncGet("slides.txt", SlideListLoader(self))
def load(self, xml_file): HTTPRequest().asyncGet(xml_file, self)