How to call python script file from wso2 proxy services

自闭症网瘾萝莉.ら 提交于 2019-12-06 15:52:10

You can use a class mediator and execute a python script from there. Following is a sample class mediator that would do this.

public boolean mediate(MessageContext context) { 
        String command = "python /path/to/script.py";
        try {
            Process p = Runtime.getRuntime().exec(command);
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String ret = in.readLine();
            System.out.println("value is : "+ret);
        } catch (IOException e) {
            // handle exception
        }
        return true;
    }

You can refer Running a .py file from Java

WSO2 EI has the inbuilt capability to execute a python script using the Script mediator. Following is a sample configuration.

**sample api configuration** 

<api xmlns="http://ws.apache.org/ns/synapse" name="api" context="/api-context">
   <resource methods="POST GET">
      <inSequence>
         <log level="full">
            <property name="Message" value="Before transformation"/>
         </log>
         <script language="py" key="conf:/repository/script/stockquoteTransformResponse.py" function="transformRequest"/>
         <log level="full">
            <property name="Message" value="After transformation"/>
         </log>
         <respond/>
      </inSequence>
   </resource>
</api>

**stockquoteTransformResponse.py file saved in carbon registry.**

from org.apache.synapse.util.xpath import SynapseXPath

def transformRequest(mc):
    symbolXPath = SynapseXPath("//*[local-name()='Code']/text()")
    symbol = symbolXPath.stringValueOf(mc)
    mc.setPayloadXML('''
	<m:getQuote xmlns:m="http://services.samples">
		<m:request>
			<m:symbol>''' + symbol + '''</m:symbol>
		</m:request>
	</m:getQuote>''')

We need to add the jython jar to WSO2EI_HOME/lib directory. This was tested with jython-2.2.1.jar from http://central.maven.org/maven2/org/python/jython/2.2.1/jython-2.2.1.jar

Following output can be seen once we invoke the above api.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!