統計與計量‎ > ‎

Tomcat 整合 Python 調用 R

回首頁

Tomcat 目錄規劃

Tomcat (web.xml) Python 設定

<servlet>
  <servlet-name>
    default
  </servlet-name>
  <servlet-class>
    org.apache.catalina.servlets.DefaultServlet
  </servlet-class>
  <init-param>
    <param-name>
      debug
    </param-name>
    <param-value>
      0
    </param-value>
  </init-param>
  <init-param>
    <param-name>
      listings
    </param-name>
    <param-value>
      false
    </param-value>
  </init-param>
  <load-on-startup>
    1
  </load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>
    default
  </servlet-name>
  <url-pattern>
    /
  </url-pattern>
</servlet-mapping>

<session-config>
  <session-timeout>
    30
  </session-timeout>
</session-config>

<welcome-file-list>
  <welcome-file>
    index.html
  </welcome-file>
  <welcome-file>
    index.htm
  </welcome-file>
  <welcome-file>
    index.cgi
  </welcome-file>
</welcome-file-list>
<servlet>
  <servlet-name>
    cgi
  </servlet-name>
  <servlet-class>
    org.apache.catalina.servlets.CGIServlet
  </servlet-class>
  <init-param>
    <param-name>
      debug
    </param-name>
    <param-value>
      1
    </param-value>
  </init-param>
  <init-param>
    <param-name>
      cgiPathPrefix
    </param-name>
    <param-value>
      WEB-INF/cgi-bin
    </param-value>
  </init-param>
  <init-param>
    <param-name>
      executable
    </param-name>
    <param-value>
      C:\Python27\python.exe
    </param-value>
  </init-param>
  <init-param>
    <param-name>
      passShellEnvironment
    </param-name>
    <param-value>
      true
    </param-value>
  </init-param>
  <load-on-startup>
    5
  </load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>
    cgi
  </servlet-name>
  <url-pattern>
    /cgi-bin/*
  </url-pattern>
</servlet-mapping>

安裝 R 程式庫 (Rserve)

  • install.packages("Rserve")
  • library(Rserve)
  • Rserve(port=9000)

Python 調用 R 程式庫

# -*- coding: utf-8 -*-

import numpy
import pyRserve

class CallR:
	__rConn = None
	
	def __init__(self):
		pass
		
	def openR(self, rHost='127.0.0.1', rPort=9000):
		if self.__rConn is not None:
			self.closeR()
			
		self.__rConn = pyRserve.connect(rHost, rPort)
		return (self.__rConn)

	def closeR(self):
		if self.__rConn is not None:
			self.__rConn.close()
			
		self.__rConn = None

混合運用

讀取外部 CSV 檔案,置入 Python 陣列,再轉換為 numpy 陣列格式,調用遠端 R 服務,計算各項統計函數。

# -*- coding: utf-8 -*-

import cgi
import time
import csv
import numpy
import pyRserve
import CallR

rConn = None

def htmlValues(tagName, funName):
  global rConn
	
  print "<tr align='center' bgcolor='silver'><td>%s</td>\n" % (tagName),
  print "<td align='right'>%.2f</td>" % (rConn.r('%s(indexClose)' % (funName)))
  print "<td align='right'>%.0f</td>" % (rConn.r('%s(indexVolume)' % (funName)))
  print "<td align='right'>%.2f</td>" % (rConn.r('%s(indexOpen)' % (funName)))
  print "<td align='right'>%.2f</td>" % (rConn.r('%s(indexHigh)' % (funName)))
  print "<td align='right'>%.2f</td>" % (rConn.r('%s(indexLow)' % (funName)))
  print ("</tr>\n")

def htmlHeader():
  print ("Content-type: text/html\n\n")
  print ("<html>\n")

def htmlBody(rHost='127.0.0.1', rPort=9000):
  global rConn
  
  print ("<body>\n")
  print ("<p><a href='#' onclick='history.go(-1); return false;'>%s</a></p>" % "Go Back")

  myData = ""
  header = 0

  vindexVolume = []
  vindexOpen = []
  vindexClose = []
  vindexHigh = []
  vindexLow = []
    
  with open('../../data/HistoricalQuotes.csv', 'rU') as csvfile:
    dataReader = csv.reader(csvfile, delimiter=',')

    print ("<table border='1'>\n")
    
    for rowData in dataReader:
      if header == 0:
        header = 1
        print "<tr align='center' bgcolor='silver'>\n", 
        for i in range(0, 6):
          print "<td>%s</td>" % rowData[i].upper(),
      else:
        __indexClose = float(rowData[1])
        __indexVolume = float(rowData[2])
        __indexOpen = float(rowData[3])
        __indexHigh = float(rowData[4])
        __indexLow = float(rowData[5])
		
        vindexClose.append(__indexClose)
        vindexVolume.append(__indexVolume)
        vindexOpen.append(__indexOpen)
        vindexHigh.append(__indexHigh)
        vindexLow.append(__indexLow)

        print "<tr>\n",
        print "<td align='center'>%s</td>" % rowData[0],
        print "<td align='right'>%.2f</td>" % __indexClose
        print "<td align='right'>%.0f</td>" % __indexVolume
        print "<td align='right'>%.2f</td>" % __indexOpen
        print "<td align='right'>%.2f</td>" % __indexHigh
        print "<td align='right'>%.2f</td>" % __indexLow
        print "</tr>\n"   
    
    if rConn is not None:
      indexVolume = numpy.array(vindexVolume)
      indexOpen = numpy.array(vindexOpen)
      indexClose = numpy.array(vindexClose)
      indexHigh = numpy.array(vindexHigh)
      indexLow = numpy.array(vindexLow)
  
      rConn.r.indexClose = indexClose
      rConn.r.indexVolume = indexVolume
      rConn.r.indexOpen = indexOpen
      rConn.r.indexHigh = indexHigh
      rConn.r.indexLow = indexLow

      htmlValues('Average', 'mean')
      htmlValues('Max', 'max')
      htmlValues('Min', 'min')
	  
    print ("<tr><td colspan='6' align='center'>\n")
    print ("<form method='POST' id='plot' action='ShowChart.cgi'>")
    print ("<input type='hidden' id='myData' name='myData' value=\"%s\">" % myData)
    print ("<input type='submit' value='Show Chart'></form>")
    print ("</td></tr>\n")

    print ("</table>")
    csvfile.close()

def htmlTail():
  print ("<p><a href='#' onclick='history.go(-1); return false;'>%s</a></p>" % "Go Back")
  print ("</body></html>\n")

rServer = CallR.CallR()
rConn = rServer.openR('127.0.0.1', 9000)

htmlHeader()
htmlBody()
htmlTail()

rServer.closeR()
ċ
CallR.py
(0k)
李智,
2015年1月19日 下午6:52
ċ
ShowData2.cgi
(3k)
李智,
2015年1月19日 下午6:52
ċ
web.xml
(136k)
李智,
2015年1月19日 下午6:52