Difference between revisions of "PyUNOServer"

From Apache OpenOffice Wiki
Jump to: navigation, search
m
 
(9 intermediate revisions by 4 users not shown)
Line 1: Line 1:
{{Extensions}}
+
[[image:Py-uno_128.png|right|PyUNO Logo]]
The PyUNOServer is a script that works as an XML server for OpenOffice.org Calc where it can exchange data through XML calls. This means that can get data from other apps that are XML compliant.
+
The PyUNOServer is a script that works as an XML server for OpenOffice.org Calc where it can exchange data through XML calls. This means that can get data from other apps that are XML compliant. You can download the script from [http://es.openoffice.org/files/documents/73/2929/pyUnoServer.tar.gz this mirror] since the original site seems to be down.
  
 
The zip file contains 3 files:  
 
The zip file contains 3 files:  
* PyUNOServerV2.py - The Python Script
+
* '''PyUNOServerV2.py''' - The Python Script
* PyUNOServerV2.pyc - compiled version
+
* '''PyUNOServerV2.pyc''' - compiled version
* PyUNOServer.sh2 - the script to conect to the service
+
* '''PyUNOServer.sh2''' - the script to conect to the service
  
<code>[python]
+
The script have just 1 script called '''PyUNOServerV2.py''' however there is a faster, bytecode-compiled script. It also includes a bash script which loads the path to the openoffice.org application.
 +
 
 +
'''NOTE: This script will work on just certain distros since the location of OpenOffice.org might vary. We recomend to load the path manually.'''
 +
 
 +
This script uses the following libraries:
 +
 
 +
* '''OS''' - This module provides a more portable way of using operating system dependent functionality than importing a operating system dependent built-in module like posix or nt.
 +
* '''UNO''' - Python UNO implementation module, this can used by python 2.3.4 '''only''' which is the python provided within openoffice.org. It provides all the interfaces from OpenOffice.org into python.
 +
* '''SYS''' - This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available.
 +
* '''time''' - This module provides various time-related functions. It is always available, but not all functions are available on all platforms. Most of the functions defined in this module call platform C library functions with the same name. It may sometimes be helpful to consult the platform documentation, because the semantics of these functions varies among platforms.
 +
* '''logging''' - Logging is performed by calling methods on instances of the Logger class (hereafter called loggers). Each instance has a name, and they are conceptually arranged in a name space hierarchy using dots (periods) as separators.
 +
* '''urllib''' - This module provides a high-level interface for fetching data across the World Wide Web. In particular, the urlopen() function is similar to the built-in function open(), but accepts Universal Resource Locators (URLs) instead of filenames. Some restrictions apply -- it can only open URLs for reading, and no seek operations are available.
 +
* '''SimpleXMLRPCServer''' - The SimpleXMLRPCServer module provides a basic server framework for XML-RPC servers written in Python. Servers can either be free standing, using SimpleXMLRPCServer, or embedded in a CGI environment, using CGIXMLRPCRequestHandler.
 +
 
 +
 
 +
<source lang=python>
 
# -*- coding: iso-8859-1 -*-
 
# -*- coding: iso-8859-1 -*-
 
#
 
#
 
# pyUnoServer - version 2.0
 
# pyUnoServer - version 2.0
#
 
# (C) 2005 ECWeb Ingenieria y Desarrollo - http://www.ecweb.cl/
 
# Written by:
 
# - Jose Antonio Akel <jakel@NOSPAMecweb.cl>
 
# - Hector Vergara <hector@NOSPAMecweb.cl>
 
# - Luis Gonzalez Miranda <lgm@NOSPAMecweb.cl>
 
#
 
# This program is freely distributable per the following license:
 
#
 
# Permission to use, copy, modify, and distribute this software and its
 
# documentation for any purpose and without fee is hereby granted,
 
# provided that the above copyright notice appears in all copies and that
 
# both that copyright notice and this permission notice appear in
 
# supporting documentation.
 
#
 
# I DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
 
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL I
 
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
 
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
 
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
 
# ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
 
# SOFTWARE.
 
 
"""
 
This program implements a XMLRPC gateway to Openoffice's Spreadsheet Calculator,
 
allowing external programs to exchange data with spreadsheets.
 
"""
 
 
 
 
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
 
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
 
import os
 
import os
Line 60: Line 46:
 
try:
 
try:
 
ret = func(*params)
 
ret = func(*params)
self.logger.info("Llamada: "+str(method)+str(params)+" | Retorno: "+str(ret))
+
self.logger.info("Llamada: %s%s | Retorno: %s" % (method, params, ret))
 
return ret
 
return ret
 
except:
 
except:
self.logger.info("Llamada: "+str(method)+str(params))
+
self.logger.info("Llamada: %s%s" % (method, params))
self.logger.error("Error: "+str(sys.exc_type)+":"+str(sys.exc_value))
+
self.logger.error("Error: %s:%s" % sys.exc_info()[:2])
  
 
def init(self):
 
def init(self):
Line 71: Line 57:
 
"""
 
"""
 
 
#Creo algunas constantes de utilidad
+
# Generate some useful constants
 
self.EMPTY = uno.Enum("com.sun.star.table.CellContentType", "EMPTY")
 
self.EMPTY = uno.Enum("com.sun.star.table.CellContentType", "EMPTY")
 
self.TEXT = uno.Enum("com.sun.star.table.CellContentType", "TEXT")
 
self.TEXT = uno.Enum("com.sun.star.table.CellContentType", "TEXT")
Line 77: Line 63:
 
self.VALUE = uno.Enum("com.sun.star.table.CellContentType", "VALUE")
 
self.VALUE = uno.Enum("com.sun.star.table.CellContentType", "VALUE")
  
# Creo un Logger
+
# Generate a Logger
 
self.logger = logging.getLogger('pyUnoServer')
 
self.logger = logging.getLogger('pyUnoServer')
 
hdlr = logging.FileHandler('./pyUnoServer.log')
 
hdlr = logging.FileHandler('./pyUnoServer.log')
Line 88: Line 74:
 
self.sessionSerial = 0
 
self.sessionSerial = 0
  
# Echo a correr el OpenOffice Calc obteniendo su PID
+
# Start Calc and grep the PID
 
self.PID = os.spawnlp(os.P_NOWAIT,"/usr/bin/oocalc","","-accept=socket,host=localhost,port=2002;urp;")
 
self.PID = os.spawnlp(os.P_NOWAIT,"/usr/bin/oocalc","","-accept=socket,host=localhost,port=2002;urp;")
 
 
self.logger.info("OOCalc Iniciado con el PID "+str(self.PID))
+
self.logger.info("OOCalc Iniciado con el PID %d" % self.PID)
  
 
while 1:
 
while 1:
Line 116: Line 102:
 
"""
 
"""
  
currentSerial = -1
+
for i,x in enumerate(self.sessions):
 
+
if x[0] == session:
for i in range(0,len(self.sessions)):
+
if self.sessions[i][0] == session:
+
 
currentSerial = i
 
currentSerial = i
 
break
 
break
+
else:
if currentSerial == -1:
+
 
self.sessions.append([session,[]])
 
self.sessions.append([session,[]])
 
currentSerial = len(self.sessions)-1
 
currentSerial = len(self.sessions)-1
Line 158: Line 141:
 
currentBook = -1
 
currentBook = -1
 
 
for i in range(0, len(self.sessions[currentSerial][1])):
+
for i, book in enumerate(self.sessions[currentSerial][1]):
 
try:
 
try:
 
book = self.sessions[currentSerial][1][i]
 
 
 
 
bookname = book[0]
 
bookname = book[0]
Line 169: Line 150:
 
if bookname == bookPath:
 
if bookname == bookPath:
 
modtime = os.path.getmtime(bookPath)
 
modtime = os.path.getmtime(bookPath)
if (modtime > bookmodtime):
+
if modtime > bookmodtime:
 
book[1].dispose()
 
book[1].dispose()
 
self.sessions[currentSerial][1].remove(book)
 
self.sessions[currentSerial][1].remove(book)
Line 179: Line 160:
 
 
  
if (currentBook < 0 ):
+
if currentBook < 0:
 
handler = self.desktop.loadComponentFromURL( "file://" + bookPath ,"_blank",0,())
 
handler = self.desktop.loadComponentFromURL( "file://" + bookPath ,"_blank",0,())
  
if(handler == None):
+
if handler == None:
 
raise Exception('El libro no existe o tiene caracteres extraños...')
 
raise Exception('El libro no existe o tiene caracteres extraños...')
  
Line 197: Line 178:
 
books = self.sessions[sessionID][1]
 
books = self.sessions[sessionID][1]
 
 
#esto cierra el documento. Parece Cerdo, pero segun la documentcion, asi es
+
# Close the document. It doesn't look very elegant but thats the way is documented.
 
books[bookID][1].dispose()
 
books[bookID][1].dispose()
 
self.sessions[sessionID][1].remove(books[bookID])
 
self.sessions[sessionID][1].remove(books[bookID])
Line 219: Line 200:
 
 
 
container = []
 
container = []
while(sheets.hasMoreElements()):
+
while sheets.hasMoreElements():
 
currentSheet = sheets.nextElement()
 
currentSheet = sheets.nextElement()
 
container.append(currentSheet.getName().encode("UTF-8"))
 
container.append(currentSheet.getName().encode("UTF-8"))
Line 296: Line 277:
 
return 1
 
return 1
  
#en que cambiara todo? mmm...
+
#what will change? mmm...
 
def massiveSetCell(self, data):
 
def massiveSetCell(self, data):
 
for valores in data:
 
for valores in data:
Line 327: Line 308:
 
os.kill(server.PID,1)
 
os.kill(server.PID,1)
 
server.logger.info("Socket cerrado.")
 
server.logger.info("Socket cerrado.")
</code>
+
</source>
  
 
==startPyUnoServer.sh2==
 
==startPyUnoServer.sh2==
<code>[bash]
+
<source lang=bash>
 
#!/bin/bash
 
#!/bin/bash
 
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/openoffice/program/
 
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/openoffice/program/
Line 337: Line 318:
 
echo "Logging en pyUnoServer.log"
 
echo "Logging en pyUnoServer.log"
 
python pyUnoServerV2.py
 
python pyUnoServerV2.py
echo "CHAO!"
+
echo "Ciao!"
</code>
+
</source>
 +
 
 +
[[Category:Python]][[Category:Uno]]

Latest revision as of 05:49, 15 May 2010

PyUNO Logo

The PyUNOServer is a script that works as an XML server for OpenOffice.org Calc where it can exchange data through XML calls. This means that can get data from other apps that are XML compliant. You can download the script from this mirror since the original site seems to be down.

The zip file contains 3 files:

  • PyUNOServerV2.py - The Python Script
  • PyUNOServerV2.pyc - compiled version
  • PyUNOServer.sh2 - the script to conect to the service

The script have just 1 script called PyUNOServerV2.py however there is a faster, bytecode-compiled script. It also includes a bash script which loads the path to the openoffice.org application.

NOTE: This script will work on just certain distros since the location of OpenOffice.org might vary. We recomend to load the path manually.

This script uses the following libraries:

  • OS - This module provides a more portable way of using operating system dependent functionality than importing a operating system dependent built-in module like posix or nt.
  • UNO - Python UNO implementation module, this can used by python 2.3.4 only which is the python provided within openoffice.org. It provides all the interfaces from OpenOffice.org into python.
  • SYS - This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available.
  • time - This module provides various time-related functions. It is always available, but not all functions are available on all platforms. Most of the functions defined in this module call platform C library functions with the same name. It may sometimes be helpful to consult the platform documentation, because the semantics of these functions varies among platforms.
  • logging - Logging is performed by calling methods on instances of the Logger class (hereafter called loggers). Each instance has a name, and they are conceptually arranged in a name space hierarchy using dots (periods) as separators.
  • urllib - This module provides a high-level interface for fetching data across the World Wide Web. In particular, the urlopen() function is similar to the built-in function open(), but accepts Universal Resource Locators (URLs) instead of filenames. Some restrictions apply -- it can only open URLs for reading, and no seek operations are available.
  • SimpleXMLRPCServer - The SimpleXMLRPCServer module provides a basic server framework for XML-RPC servers written in Python. Servers can either be free standing, using SimpleXMLRPCServer, or embedded in a CGI environment, using CGIXMLRPCRequestHandler.


# -*- coding: iso-8859-1 -*-
#
# pyUnoServer - version 2.0
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
import os
import uno
import sys
import time
import logging
import urllib
 
class PyUNOServer(SimpleXMLRPCServer):
 
	def _dispatch(self, method, params):
 
		try:
			func = getattr(self, '' + method)
		except:
			self.logger.error("El Metodo '"+method+"' no esta soportado!")
			raise Exception('method "%s" is not supported' % method)
		else:
			try:
				ret = func(*params)
				self.logger.info("Llamada: %s%s | Retorno: %s" % (method, params, ret))
				return ret
			except:
				self.logger.info("Llamada: %s%s" % (method, params))
				self.logger.error("Error: %s:%s" % sys.exc_info()[:2])
 
	def init(self):
		"""
		This method	starts an Openoffice session and initializes the XMLRPC server
		"""
 
		# Generate some useful constants
		self.EMPTY = uno.Enum("com.sun.star.table.CellContentType", "EMPTY")
		self.TEXT = uno.Enum("com.sun.star.table.CellContentType", "TEXT")
		self.FORMULA = uno.Enum("com.sun.star.table.CellContentType", "FORMULA")
		self.VALUE = uno.Enum("com.sun.star.table.CellContentType", "VALUE")
 
		# Generate a Logger
		self.logger = logging.getLogger('pyUnoServer')
		hdlr = logging.FileHandler('./pyUnoServer.log')
		formatter = logging.Formatter('%(asctime)s %(levelname)s -- %(message)s')
		hdlr.setFormatter(formatter)
		self.logger.addHandler(hdlr) 
		self.logger.setLevel(logging.INFO)
 
		self.sessions = []
		self.sessionSerial = 0
 
		# Start Calc and grep the PID
		self.PID = os.spawnlp(os.P_NOWAIT,"/usr/bin/oocalc","","-accept=socket,host=localhost,port=2002;urp;")
 
		self.logger.info("OOCalc Iniciado con el PID %d" % self.PID)
 
		while 1:
			try: 
				localContext = uno.getComponentContext()
				resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
				smgr = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager" )
				remoteContext = smgr.getPropertyValue( "DefaultContext" )
				self.desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",remoteContext)
				self.logger.info("Sistema conectado al socket de UNO")
				break
			except:
				time.sleep(0.5)
 
	def openSession(self, session):
		"""
		This method opens a new session.
		Sample usage from PHP:
		 - $sessionString is your a session ID provided by your program):
 
			$openSession = array( new XML_RPC_VALUE($sessionString, "string"));
			$sessionID = queryXMLRPC($client, "openSession", $openSession);
			return $sessionID;
		"""
 
		for i,x in enumerate(self.sessions):
			if x[0] == session:
				currentSerial = i
				break
		else:
			self.sessions.append([session,[]])
			currentSerial = len(self.sessions)-1
 
		return currentSerial
 
 
	def getSessions(self):
		return self.sessions
 
	def openBook(self, session, bookPath):
		"""
		This method opens a new Openoffice spreadsheet book.
		Sample usage from PHP:
		 - $sessionID is the session's ID returned by openSession()
		 - $path is the path to the book in the server's filesystem
 
		$openBookQuery = array( new XML_RPC_VALUE($sessionID, "int"), new XML_RPC_VALUE($path,"string") );
		$bookID = queryXMLRPC($client, "openBook", $openBookQuery);
		return $bookID;
		"""
 
		currentSerial = session
		bookPath = bookPath.strip()
		print bookPath
 
 
		exists = os.path.exists(bookPath)
		if exists == False:
			raise Exception('El libro %s no existe', bookPath)
		else:
			self.logger.info("se ha encontrado el libro!")
 
		currentBook = -1
 
		for i, book in enumerate(self.sessions[currentSerial][1]):
			try:
 
				bookname = book[0]
				bookhandler = book[1]
				bookmodtime = book[2]
 
				if bookname == bookPath:
					modtime = os.path.getmtime(bookPath)
					if modtime > bookmodtime:
						book[1].dispose()
						self.sessions[currentSerial][1].remove(book)
					else:
						currentBook = i
					break
			except:
				self.logger.error("El libro "+currentBook+" no existe!")
 
 
		if currentBook < 0:
			handler = self.desktop.loadComponentFromURL( "file://" + bookPath ,"_blank",0,())
 
			if handler == None:
				raise Exception('El libro no existe o tiene caracteres extraños...')
 
			modtime = os.path.getmtime(bookPath)
 
			estruct = [bookPath,handler,modtime]
			self.sessions[currentSerial][1].append(estruct)
			currentBook = len(self.sessions[currentSerial][1])-1
 
		return currentBook
 
	def closeBook(self, sessionID, bookID):
 
		books = self.sessions[sessionID][1]
 
		# Close the document. It doesn't look very elegant but thats the way is documented.
		books[bookID][1].dispose()
		self.sessions[sessionID][1].remove(books[bookID])
 
		return 1
 
 
	def getBookSheets(self, sessionID, bookID):
		"""
		This method return an array with the book's worksheets.
		Sample usage from PHP:
		 - $sessionID is the session's ID returned by openSession()
		 - $bookID is the book's ID returned by openBook()
 
		$sheetsQuery = array( new XML_RPC_VALUE($sessionID, "int"), new XML_RPC_VALUE($bookID, "int") );
		$sheets = queryXMLRPC($client, "getBookSheets" , $sheetsQuery);
		return $sheets;
		"""
 
		sheets = self.sessions[sessionID][1][bookID][1].getSheets().createEnumeration()
 
		container = []
		while sheets.hasMoreElements():
			currentSheet = sheets.nextElement()
			container.append(currentSheet.getName().encode("UTF-8"))
 
		return container
 
	def getCellValue (self,sheet,x,y):
 
		cell = sheet.getCellByPosition(x,y)
		cellType  = cell.getType()
 
		if cellType == self.TEXT :
			data = cell.getString().encode("UTF-8")
			if data == None:
				return ""
			return data.encode("UTF-8")
 
		if cellType == self.FORMULA or cellType == self.VALUE :
			data = cell.getValue()
			if data == None:
				return 0
			return cell.getValue()
 
		if cellType == self.EMPTY :
			return ""
 
 
	def getCell(self, session, book, sheet, x, y):
		"""
		This method returns the content of a cell.
		Sample usage from PHP:
		 - $sessionID is the session's ID returned by openSession()
		 - $bookID is the book's ID returned by openBook()
		 - $sheet is the sheet's ID as returned by getBookSheets()
 
		$query = array(	
						new XML_RPC_Value($sessionID, "int"), 
						new XML_RPC_VALUE($bookID, "int"), 
						new XML_RPC_VALUE($sheet, "int"), 
						new XML_RPC_Value($x, "int"), 
						new XML_RPC_Value($y, "string")
					);
 
		$result = queryXMLRPC($client, "getCell", $query);
		return $result;
		"""
 
		sheetref = self.sessions[session][1][book][1].getSheets().getByIndex(sheet)
		valor = self.getCellValue(sheetref,x,y)
		return valor
 
	def setCell(self,session,book,sheet,x,y,value):
		"""
		This method sets the content of a cell.
		Sample usage from PHP:
		 - $sessionID is the session's ID returned by openSession()
		 - $bookID is the book's ID returned by openBook()
		 - $sheet is the sheet's ID as returned by getBookSheets()
 
		$query = array(
						new XML_RPC_Value($sessionID, "int"), 
						new XML_RPC_VALUE($bookID, "int"), 
						new XML_RPC_VALUE($sheet, "int"), 
						new XML_RPC_Value($x, "int"), 
						new XML_RPC_Value($y, "int"),
						new XML_RPC_Value($value, "string")
					);
 
		$result = queryXMLRPC($client, "setCell", $query);
		return $result;
		"""
 
		bookObject = self.sessions[session][1][book][1]
		cell = bookObject.getSheets().getByIndex(sheet).getCellByPosition(x,y)
		cell.setValue(value)
		return 1
 
	#what will change? mmm...
	def massiveSetCell(self, data):
			for valores in data:
				session,sheetid,x,y,valor = valores.split("|")
				code = self.setCell(self.trim(session),self.trim(sheetid),self.trim(x),self.trim(y),valor)
				if code < 0:
					return code
			return 1
 
	def getSheetPreview(self,session,book,sheet):
 
		sheet = self.sessions[session][1][book][1].getSheets().getByIndex(sheet)
		range = sheet.getCellRangeByPosition(0,0,8,23).getDataArray()
		return range
 
 
	def trim(self, cadena):
		return cadena.strip()
 
server = PyUNOServer(("localhost", 8000))
 
server.init()
server.logger.info("Servicio Inicializado...")
 
try:
	server.serve_forever()
except KeyboardInterrupt:
	server.logger.info("Cerrando el socket...")
	server.server_close()
	os.kill(server.PID,1)
	server.logger.info("Socket cerrado.")

startPyUnoServer.sh2

#!/bin/bash
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/openoffice/program/
export PYTHONPATH=$PYTHONPATH:/usr/lib/openoffice/program
export DISPLAY=localhost:1
echo "Logging en pyUnoServer.log"
python pyUnoServerV2.py
echo "Ciao!"
Personal tools