A simple tutorial on web development using javastapi in Python

Source: Internet
Author: User
Tags xslt
This article mainly introduces a simple tutorial on web development using the javastapi in Python. This article is from the IBM official website technical documentation. if you need it, refer Soap endpoint of the Kafka style

The Kafka-xsl soap toolkit developed by Christopher Dix (see references) is an XSLT framework used to construct SOAP endpoints. It only covers SOAP 1.1, but the Kafka endpoint demonstrates the ability to pass the UserLand SOAP Validator (UserLand SOAP Validator), and it does not seem too difficult to update it based on SOAP 1.2. Listing 1 shows a sample Kafka endpoint: a soap server that calculates the sum of two numbers (a typical and simple SOAP sample ).

Listing 1. Evaluate the Kafka SOAP endpoint of the sum of two numbers

<?xml version="1.0" encoding="UTF-8"?>
   
    
    
    
    
    
  
   Add
    
  
   http://www.topxml.com/</xsl:variable>  
     
     
      
       
         
          
          
          
          
           
            
            
           
        
      
     
  
 

The XSLT endpoint imports the SOAP framework (file kafka/soap. xsl), set the parameters to be used by the framework, and set the template to be assigned during the process of processing the XML document that constitutes the SOAP message. The global variables Method and MethodNS declare the XML elements that constitute the message. After processing the SOAP envelope, the framework calls the ProcessPayload template, which is passed into the XML entity's payload. Xsl: for-each is a standard technique for switching context to the desired node. Parameters A and B are read from this element using simple XPaths, and the framework is called again to help write response parameters. The WriteParameter template allows you to specify the element name, data type, and value of each output parameter. The response value in this example is the result of adding two input parameters.

Deploying this endpoint as a server is equivalent to setting an HTTP Listener. The BaseHTTPServer module of Python provides you with the required mechanism to easily process the HTTP part of the protocol. See List 2.

Listing 2. Python HTTP framework used for the Kafka SOAP endpoint implemented in listing 1

#HTTP Listener code for SOAP serverimport BaseHTTPServer#The processor class is the core of the XSLT APIfrom Ft.Xml.Xslt import Processor#4XSLT uses an InputSource system for reading XMLfrom Ft.Xml import InputSourceSOAP_IMPL_FILE = "add.xsl"class KafkaSoapHandler(BaseHTTPServer.BaseHTTPRequestHandler):  def init(cls):    from Ft.Lib import Uri    #Set up a processor instance to use    KafkaSoapHandler.processor = Processor.Processor()    #Load it with add.xsl    add_uri = Uri.OsPathToUri(SOAP_IMPL_FILE, attemptAbsolute=1)    transform = InputSource.DefaultFactory.fromUri(add_uri)    KafkaSoapHandler.processor.appendStylesheet(transform)    #Now the processor is prepped with a transform and can be used    #over and over for the same transform    return  #Make init() a static method of the class  init = classmethod(init)  def do_POST(self):    clen = self.headers.getheader('content-length')    if clen:      clen = int(clen)    else:      print 'POST ERROR: missing content-length'      return    if self.path != '/add':      self.send_error(404)    input_body = self.rfile.read(clen)    #input_body is the request SOAP envelope and contents    response_body = self._run_through_kafka(input_body)    #response_body is the response SOAP envelope and contents    self._send_response(200, 'OK', response_body)    return  def _run_through_kafka(self, body):    #In 4Suite all InputSources have base URIs in case they refer to    #other URIs in some way and resolution is required.    #The SOAP messages will not have any such URI references,    #So use a dummy base URI    source = InputSource.DefaultFactory.fromString(body, "urn:dummy")    response = self.processor.run(source)    return response  def _send_response(self, code, msg, body):    #Prepare a normal response    self.send_response(200, 'OK')    #Send standard HTP headers    self.send_header('Content-type','text/html; charset=utf-8')    self.send_header("Connection", "close")    self.send_header("Accept-Ranges", "bytes")    self.send_header('Content-length', len(body)-1)    self.end_headers()    #Send the response prepared by the SOAP end point    self.wfile.write(body)    return listen_on_port = 8888#Set up to run on local machineserver_address = ('127.0.0.1', listen_on_port)KafkaSoapHandler.init()httpd = BaseHTTPServer.HTTPServer(server_address, KafkaSoapHandler)print "Listening on port", listen_on_port#Go into a the main event loophttpd.serve_forever()

The list is commented out in detail, so it should be easy to understand. Please note that this code is very simple because it only needs to process the HTTP part of the protocol and hand over the XML and SOAP parts to the Kafka framework. The server is dedicated to an endpoint, so it only needs to parse and set the XSLT conversion once, and then it can simply run the conversion repeatedly for each new request. This is the reason for migrating the processor settings to a special class method. the handler immediately calls this method as soon as it registers to the server. The built-in classmethod method is a new feature in Python 2.2. In fact, this version is required for this and later examples. It provides an implicit class object (cls), you can attach static data (such as prepared processor instances) to this object, then, the data can be referenced by the self instance in a common method.

We tested this endpoint using the latest release of SOAPpy 0.10.1 (see references), which has many great new features and will be discussed later in this column. Listing 3 shows the SOAPpy client that uses this endpoint. Open a shell and run python listing2.py for the server. Open another shell and run python listing3.py. this command will report the correct response, as shown in Add result: 7.0.

Listing 3: SOAPpy client used to calculate the sum of two numbers

import SOAPpyENDPOINT = "http://localhost:8888/add"ADD_NS = "http://www.topxml.com/" remote = SOAPpy.SOAPProxy(ENDPOINT, namespace=ADD_NS)print "Add result:", remote.Add(A=3, B=4)

Usage description

As we mentioned earlier, not only does the XML server load balancer provide useful Web service features, but also describes useful features. Listing 4 is a WSDL file used to add services. it is obtained by modifying the original file of Christopher Dix. It is in the WSDL 1.1 version.

Listing 4. WSDL used to add a service

<?xml version="1.0" encoding="UTF-8"?>
  
    
     
    
   
    
    
   
    
      
       
      
    
   
    
     
      
       
        
          
        
          
    
   
    
      
      
    
  
 

Listing 5 provides an XSLT script that displays useful information for the endpoint user. It is adapted from a conversion developed in the previous developerWorks article "WSDL processing with XSLT" (see references. It uses many free methods (liberty) and shortcuts (especially when it processes qualified names in the WSDL context), but it may be used for most of the currently used WSDL 1.1 files.

Listing 5. XSLT script

<?xml version="1.0" encoding="utf-8"?>
  
   
   
   
   
   
   
         
   Service summary: <xsl:value-of select='wsdl:definitions/@name'/>      
           Service summary: 
           
   

Service " " hosted at

Operation " " message details:

Generally, it is convenient to provide a user-friendly WSDL description on the host where the Web service is located. Listing 6 is a variant of listing 2, which also completes this task. It actually provides three functions:

  1. For GET requests on port 9000: provides an easy-to-understand description of the Web service call message
  2. For GET requests on port 8888: provide unprocessed WSDL files
  3. For POST requests on port 8888: execute SOAP requests.

Listing 6. variants of listing 2

#HTTP Listener code for SOAP serverimport BaseHTTPServer#The processor class is the core of the XSLT APIfrom Ft.Xml.Xslt import Processor#4XSLT uses an InputSource system for reading XMLfrom Ft.Xml import InputSourceSOAP_IMPL_FILE = "add.xsl"WSDL_FILE = "listing4.xml"HTML_VIEW_TRANSFORM = "listing5.xslt"class KafkaSoapHandler(BaseHTTPServer.BaseHTTPRequestHandler):  def init(cls):    from Ft.Lib import Uri    #Set up a processor instance to use    cls.processor = Processor.Processor()    #Load it with add.xsl    add_uri = Uri.OsPathToUri(SOAP_IMPL_FILE, attemptAbsolute=1)    transform = InputSource.DefaultFactory.fromUri(add_uri)    cls.processor.appendStylesheet(transform)    #Now the processor is prepped with a transform and can be used    #over and over for the same transform    #Prep for WSDL requests    cls.wsdl = open(WSDL_FILE).read()    return  #Make init() a static method of the class  init = classmethod(init)  def do_POST(self):    clen = self.headers.getheader('content-length')    if clen:      clen = int(clen)    else:      print 'POST ERROR: missing content-length'      return    if self.path != '/add':      self.send_error(404)    input_body = self.rfile.read(clen)    #input_body is the request SOAP envelope and contents    response_body = self._run_through_kafka(input_body)    #response_body is the response SOAP envelope and contents    _send_response(self, 200, 'OK', response_body)    return  def do_GET(self):    #response_body is the WSDL file    _send_response(self, 200, 'OK', self.wsdl)    return    def _run_through_kafka(self, body):    #In 4Suite all InputSources have base URIs in case they refer to    #other URIs in some way and resolution is required.    #The SOAP messages will not have any such URI references,    #So use a dummy base URI    source = InputSource.DefaultFactory.fromString(body, "urn:dummy")    response = self.processor.run(source)    return responseclass HtmlHandler(BaseHTTPServer.BaseHTTPRequestHandler):  def init(cls):    from Ft.Lib import Uri    #Perform the transform once and store the result    processor = Processor.Processor()    html_desc_uri = Uri.OsPathToUri(HTML_VIEW_TRANSFORM,                    attemptAbsolute=1)    transform = InputSource.DefaultFactory.fromUri(html_desc_uri)    processor.appendStylesheet(transform)    wsdl_uri = Uri.OsPathToUri(WSDL_FILE, attemptAbsolute=1)    source = InputSource.DefaultFactory.fromUri(wsdl_uri)    cls.html_desc = processor.run(source)    return  #Make init() a static class method  init = classmethod(init)  def do_GET(self):    #response_body is the WSDL file    _send_response(self, 200, 'OK', self.html_desc)    return#Turn _send_response into a global function#for sharing between the classesdef _send_response(handler, code, msg, body):    #Prepare a normal response    handler.send_response(200, 'OK')    #Send standard HTP headers    handler.send_header('Content-type', 'text/html; charset=utf-8')    handler.send_header("Connection", "close")    handler.send_header("Accept-Ranges", "bytes")    handler.send_header('Content-length', len(body)-1)    handler.end_headers()    #Send the response prepared by the SOAP end point    handler.wfile.write(body)    return def soap_listener_function():  listen_on_port = 8888  #Set up to run on local machine  server_address = ('127.0.0.1', listen_on_port)  KafkaSoapHandler.init()  httpd = BaseHTTPServer.HTTPServer(server_address, KafkaSoapHandler)  print "Listening for GET and POST on port", listen_on_port  #Go into a the main event loop  httpd.serve_forever()def html_listener_function():  listen_on_port = 9000  #Set up to run on local machine  server_address = ('127.0.0.1', listen_on_port)  HtmlHandler.init()  httpd = BaseHTTPServer.HTTPServer(server_address, HtmlHandler)  print "Listening for GET on port", listen_on_port  #Go into a the main event loop  httpd.serve_forever()  returnimport timefrom threading import Threadsoap_thread = Thread(None, soap_listener_function)html_thread = Thread(None, html_listener_function)soap_thread.start()#Pause before spawning the next threadtime.sleep(1)html_thread.start()

By defining do_GET and do_POST on the server, you can process GET and POST requests on a single server instance, but because of the nature of the simple event loop, you can use the thread technology to listen on different ports. This allows you to run two server instances at the same time. Thread Technology is one of the methods, while using asynchronous event handlers is another method. Python 2.2 introduces the asyncore module to more easily support the latter technology. we introduced this method in the previous article in this column (see references ). This time we will illustrate the usage of thread technology. Regarding the use of thread technology or the use of asynchronous technology, Python 2.2 provides good suggestions.

The [asynchronous method] is actually practical only when your program is largely limited by I/O. If your program is restricted by the processor, the preemptive scheduling thread may be what you really need. However, network servers are rarely limited by processors.

Figure 1 shows a browser view of easy-to-understand Web service descriptions.

Conclusion

Think of all this as lab material. Kafka is quite outdated-it seems that it has not been maintained since 2001, and it uses a rather bad XSLT style (the author admitted frankly that he is an XSLT Cainiao ). But its ideas are very useful and valuable. You only need to make a small effort to update it to SOAP 1.2 and expand its capabilities. The WSDL representation conversion we provide is also a starting point. You can also update it to WSDL 1.2 and expand it to display more information about Web services. It should also be updated to take advantage of the namespace axis and Other XSLT functions for better processing.

XSLT is a sandbox where developers in various languages and environments can use their skills. Kafka is developed by a strong. NET Developer, but we can quickly learn about it and use it. This is the power of lingua franca, a universal language that can process both XML and Web services. We expect that the fields that can use the XSLT module for Web services will continue to expand. If so, the basic technologies provided in this article may prompt Python programmers to use these useful technologies immediately.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.