def start_new_job(ip, alphabet, n, p, H, dist, comment=""): session = Session() H = simplify(H) dist = simplify(dist) log.info("SOAP start new job: %s, %s, %d, %d, %s, %s, %s" % ( ip, alphabet, n, p, H, dist, comment )) job = SufprefJob( ip, alphabet, n, p, json.loads(H), json.loads(dist), comment) session.add(job) session.commit() return job.id
def do_POST(self): global _contexts status = 500 try: if self.server.config.dumpHeadersIn: s = 'Incoming HTTP headers' debugHeader(s) print(self.raw_requestline.strip()) print("\n".join([x.strip() for x in self.headers.headers])) debugFooter(s) data = self.rfile.read(int(self.headers["Content-length"])) if self.server.config.dumpSOAPIn: s = 'Incoming SOAP' debugHeader(s) print(data, end=' ') if data[-1] != '\n': print() debugFooter(s) (r, header, body, attrs) = \ parseSOAPRPC(data, header = 1, body = 1, attrs = 1, ignore_ext=self.ignore_ext) method = r._name args = r._aslist() kw = r._asdict() if self.server.config.simplify_objects: args = simplify(args) kw = simplify(kw) # Handle mixed named and unnamed arguments by assuming # that all arguments with names of the form "v[0-9]+" # are unnamed and should be passed in numeric order, # other arguments are named and should be passed using # this name. # This is a non-standard exension to the SOAP protocol, # but is supported by Apache AXIS. # It is enabled by default. To disable, set # Config.specialArgs to False. ordered_args = {} named_args = {} if self.server.config.specialArgs: for (k, v) in list(kw.items()): if k[0] == "v": try: i = int(k[1:]) ordered_args[i] = v except ValueError: named_args[str(k)] = v else: named_args[str(k)] = v # We have to decide namespace precedence # I'm happy with the following scenario # if r._ns is specified use it, if not check for # a path, if it's specified convert it and use it as the # namespace. If both are specified, use r._ns. ns = r._ns if len(self.path) > 1 and not ns: ns = self.path.replace("/", ":") if ns[0] == ":": ns = ns[1:] # authorization method a = None keylist = list(ordered_args.keys()) keylist.sort() # create list in proper order w/o names tmp = [ordered_args[x] for x in keylist] ordered_args = tmp #print '<-> Argument Matching Yielded:' #print '<-> Ordered Arguments:' + str(ordered_args) #print '<-> Named Arguments :' + str(named_args) resp = "" # For fault messages if ns: nsmethod = "%s:%s" % (ns, method) else: nsmethod = method try: # First look for registered functions if ns in self.server.funcmap and \ method in self.server.funcmap[ns]: f = self.server.funcmap[ns][method] # look for the authorization method if self.server.config.authMethod != None: authmethod = self.server.config.authMethod if ns in self.server.funcmap and \ authmethod in self.server.funcmap[ns]: a = self.server.funcmap[ns][authmethod] else: # Now look at registered objects # Check for nested attributes. This works even if # there are none, because the split will return # [method] f = self.server.objmap[ns] # Look for the authorization method if self.server.config.authMethod != None: authmethod = self.server.config.authMethod if hasattr(f, authmethod): a = getattr(f, authmethod) # then continue looking for the method l = method.split(".") for i in l: f = getattr(f, i) except: info = sys.exc_info() try: resp = buildSOAP(faultType( "%s:Client" % NS.ENV_T, "Method Not Found", "%s : %s %s %s" % (nsmethod, info[0], info[1], info[2])), encoding=self.server.encoding, config=self.server.config) finally: del info status = 500 else: try: if header: x = HeaderHandler(header, attrs) fr = 1 # call context book keeping # We're stuffing the method into the soapaction if there # isn't one, someday, we'll set that on the client # and it won't be necessary here # for now we're doing both if "SOAPAction".lower() not in list(self.headers.keys()) or \ self.headers["SOAPAction"] == "\"\"": self.headers["SOAPAction"] = method thread_id = _thread.get_ident() _contexts[thread_id] = SOAPContext( header, body, attrs, data, self.connection, self.headers, self.headers["SOAPAction"]) # Do an authorization check if a != None: if not a(*(), **{"_SOAPContext": _contexts[thread_id] }): raise faultType("%s:Server" % NS.ENV_T, "Authorization failed.", "%s" % nsmethod) # If it's wrapped, some special action may be needed if isinstance(f, MethodSig): c = None if f.context: # retrieve context object c = _contexts[thread_id] if self.server.config.specialArgs: if c: named_args["_SOAPContext"] = c fr = f(*ordered_args, **named_args) elif f.keywords: # This is lame, but have to de-unicode # keywords strkw = {} for (k, v) in list(kw.items()): strkw[str(k)] = v if c: strkw["_SOAPContext"] = c fr = f(*(), **strkw) elif c: fr = f(*args, **{'_SOAPContext': c}) else: fr = f(*args, **{}) else: if self.server.config.specialArgs: fr = f(*ordered_args, **named_args) else: fr = f(*args, **{}) if type(fr) == type(self) and \ isinstance(fr, voidType): resp = buildSOAP(kw={'%sResponse' % method: fr}, encoding=self.server.encoding, config=self.server.config) else: resp = buildSOAP( kw={'%sResponse' % method: { 'Result': fr }}, encoding=self.server.encoding, config=self.server.config) # Clean up _contexts if thread_id in _contexts: del _contexts[thread_id] except Exception as e: import traceback info = sys.exc_info() try: if self.server.config.dumpFaultInfo: s = 'Method %s exception' % nsmethod debugHeader(s) traceback.print_exception(info[0], info[1], info[2]) debugFooter(s) if isinstance(e, faultType): f = e else: f = faultType("%s:Server" % NS.ENV_T, "Method Failed", "%s" % nsmethod) if self.server.config.returnFaultInfo: f._setDetail("".join( traceback.format_exception( info[0], info[1], info[2]))) elif not hasattr(f, 'detail'): f._setDetail("%s %s" % (info[0], info[1])) finally: del info resp = buildSOAP(f, encoding=self.server.encoding, config=self.server.config) status = 500 else: status = 200 except faultType as e: import traceback info = sys.exc_info() try: if self.server.config.dumpFaultInfo: s = 'Received fault exception' debugHeader(s) traceback.print_exception(info[0], info[1], info[2]) debugFooter(s) if self.server.config.returnFaultInfo: e._setDetail("".join( traceback.format_exception(info[0], info[1], info[2]))) elif not hasattr(e, 'detail'): e._setDetail("%s %s" % (info[0], info[1])) finally: del info resp = buildSOAP(e, encoding=self.server.encoding, config=self.server.config) status = 500 except Exception as e: # internal error, report as HTTP server error if self.server.config.dumpFaultInfo: s = 'Internal exception %s' % e import traceback debugHeader(s) info = sys.exc_info() try: traceback.print_exception(info[0], info[1], info[2]) finally: del info debugFooter(s) self.send_response(500) self.end_headers() if self.server.config.dumpHeadersOut and \ self.request_version != 'HTTP/0.9': s = 'Outgoing HTTP headers' debugHeader(s) if status in self.responses: s = ' ' + self.responses[status][0] else: s = '' print("%s %d%s" % (self.protocol_version, 500, s)) print("Server:", self.version_string()) print("Date:", self.__last_date_time_string) debugFooter(s) else: # got a valid SOAP response self.send_response(status) t = 'text/xml' if self.server.encoding != None: t += '; charset=%s' % self.server.encoding self.send_header("Content-type", t) self.send_header("Content-length", str(len(resp))) self.end_headers() if self.server.config.dumpHeadersOut and \ self.request_version != 'HTTP/0.9': s = 'Outgoing HTTP headers' debugHeader(s) if status in self.responses: s = ' ' + self.responses[status][0] else: s = '' print("%s %d%s" % (self.protocol_version, status, s)) print("Server:", self.version_string()) print("Date:", self.__last_date_time_string) print("Content-type:", t) print("Content-length:", len(resp)) debugFooter(s) if self.server.config.dumpSOAPOut: s = 'Outgoing SOAP' debugHeader(s) print(resp, end=' ') if resp[-1] != '\n': print() debugFooter(s) self.wfile.write(resp) self.wfile.flush() # We should be able to shut down both a regular and an SSL # connection, but under Python 2.1, calling shutdown on an # SSL connections drops the output, so this work-around. # This should be investigated more someday. if self.server.config.SSLserver and \ isinstance(self.connection, SSL.Connection): self.connection.set_shutdown(SSL.SSL_SENT_SHUTDOWN | SSL.SSL_RECEIVED_SHUTDOWN) else: self.connection.shutdown(1) def do_GET(self): #print 'command ', self.command #print 'path ', self.path #print 'request_version', self.request_version #print 'headers' #print ' type ', self.headers.type #print ' maintype', self.headers.maintype #print ' subtype ', self.headers.subtype #print ' params ', self.headers.plist path = self.path.lower() if path.endswith('wsdl'): method = 'wsdl' function = namespace = None if namespace in self.server.funcmap \ and method in self.server.funcmap[namespace]: function = self.server.funcmap[namespace][method] else: if namespace in list(self.server.objmap.keys()): function = self.server.objmap[namespace] l = method.split(".") for i in l: function = getattr(function, i) if function: self.send_response(200) self.send_header("Content-type", 'text/plain') self.end_headers() response = function(*()) self.wfile.write(str(response)) return # return error self.send_response(200) self.send_header("Content-type", 'text/html') self.end_headers() self.wfile.write('''\ <title> <head>Error!</head> </title> <body> <h1>Oops!</h1> <p> This server supports HTTP GET requests only for the the purpose of obtaining Web Services Description Language (WSDL) for a specific service. Either you requested an URL that does not end in "wsdl" or this server does not implement a wsdl method. </p> </body>''')
except: id = 0 error = "Can't connect to SOAP service" error = error.replace("<", "<").replace(">", ">").replace(" ", " ") response = { "success": len(error)==0, "error": error, "id": id } print "Content-Type: text/html" print print json.dumps(response) elif method=="get_report": id = int(form["id"].value) res = server.get_result(id) simplify(res) report = unicode(res["result"]) print "Content-Type: application/json" print print report elif method=="get_report_as_file": id = int(form["id"].value) res = server.get_result(id) res = json.loads(simplify(res)["result"]) data = "start;end;score\r\n" for row in res: data += "%d;%d;%d\r\n" % (row["start"], row["end"], row["score"]) filename = "rna_id"+str(id)+".csv" print "Content-Type: text/csv" print "Content-Disposition: attachment; filename="+filename print
comment = form["comment"].value else: comment = "" alphabet = form["alphabet"].value textlength = int(form["textlength"].value) occurences = int(form["occurences"].value) model_data = form.getvalue("model") pattern_data = form.getvalue("pattern") id = server.start_new_job(ip, alphabet, textlength, occurences, pattern_data, model_data, comment) print "Content-Type: application/json" print print json.dumps({"status": "OK", "id": int(id)}) elif method=="get_report_as_string": id = int(form["id"].value) res = server.get_result(id) simplify(res) report = unicode(res["report"]).encode('utf-8') print "Content-Type: text/plain" print print report elif method=="get_report_as_file": id = int(form["id"].value) res = server.get_result(id) simplify(res) report = unicode(res["report"]).encode('utf-8') filename = "sufpref_id"+str(id)+".txt" print "Content-Type: text/plain" print "Content-Disposition: attachment; filename="+filename print "Content-Length: "+str(len(report)) print print report
def __call(self, name, args, kw, ns=None, sa=None, hd=None, ma=None): ns = ns or self.namespace ma = ma or self.methodattrs if sa: # Get soapaction if type(sa) == TupleType: sa = sa[0] else: if self.soapaction: sa = self.soapaction else: sa = name if hd: # Get header if type(hd) == TupleType: hd = hd[0] else: hd = self.header hd = hd or self.header if ma: # Get methodattrs if type(ma) == TupleType: ma = ma[0] else: ma = self.methodattrs ma = ma or self.methodattrs m = buildSOAP(args=args, kw=kw, method=name, namespace=ns, header=hd, methodattrs=ma, encoding=self.encoding, config=self.config, noroot=self.noroot) call_retry = 0 try: r, self.namespace = self.transport.call(self.proxy, m, ns, sa, encoding=self.encoding, http_proxy=self.http_proxy, config=self.config, timeout=self.timeout) except socket.timeout: raise SOAPTimeoutError except Exception as ex: # # Call failed. # # See if we have a fault handling vector installed in our # config. If we do, invoke it. If it returns a true value, # retry the call. # # In any circumstance other than the fault handler returning # true, reraise the exception. This keeps the semantics of this # code the same as without the faultHandler code. # if hasattr(self.config, "faultHandler"): if isinstance(self.config.faultHandler, collections.Callable): call_retry = self.config.faultHandler(self.proxy, ex) if not call_retry: raise else: raise else: raise if call_retry: try: r, self.namespace = self.transport.call( self.proxy, m, ns, sa, encoding=self.encoding, http_proxy=self.http_proxy, config=self.config, timeout=self.timeout) except socket.timeout: raise SOAPTimeoutError p, attrs = parseSOAPRPC(r, attrs=1) try: throw_struct = self.throw_faults and \ isinstance (p, faultType) except: throw_struct = 0 if throw_struct: if self.config.debug: print(p) raise p # If unwrap_results=1 and there is only element in the struct, # SOAPProxy will assume that this element is the result # and return it rather than the struct containing it. # Otherwise SOAPproxy will return the struct with all the # elements as attributes. if self.unwrap_results: try: count = 0 for i in list(p.__dict__.keys()): if i[0] != "_": # don't count the private stuff count += 1 t = getattr(p, i) if count == 1: # Only one piece of data, bubble it up p = t except: pass # Automatically simplfy SOAP complex types into the # corresponding python types. (structType --> dict, # arrayType --> array, etc.) if self.simplify_objects: p = simplify(p) if self.config.returnAllAttrs: return p, attrs return p