Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

What do you mean it needs to be Java based? How jython saved the day.


Published on

Slides of talk given at PyCon APAC 2011 in Singapore.

Published in: Technology, Education
  • Login to see the comments

What do you mean it needs to be Java based? How jython saved the day.

  1. 1. What do you mean it needs to be Java based? How Jython saved the day! Mark Rees Group CTO Century Software Holdings Berhad @hexdump42
  2. 2. Century Software (M) Sdn Bhd Develop & implement Financial Management Software Solutions Some of our applications use Python. Who?
  3. 3. From a tender document ” The application must be written in an industry standard enterprise programming framework. Please state which framework. ” The problem
  4. 4. Python! Our preferred answer
  5. 5. Java or .NET The expected answer
  6. 6. ” The web application must run using an Enterprise Web Application Server. ” Another problem
  7. 7. Django, Pyramid, ... Our preferred answer
  8. 8. Websphere, JBoss, OAS... The expected answer
  9. 9. The solution
  10. 10. Jython Equivalent to Python Reference Version 2.5 Includes standard library
  11. 11. Installation java -jar jython_installer-2.5.2.jar
  12. 12. Pros Runs most existing Python code without mods No GIL Access to Java Libraries Cons Performance No C extensions Pros & Cons
  13. 13. Call Java Code from import PhoneNumberUtil class PhoneNumberi18n: def __init__(self, country, phonenumber): self.phone_number_util = PhoneNumberUtil.getInstance() self.raw_phone_number = phonenumber = country self.phone_number = self.phone_number_util.parse(phonenumber, country) def is_valid_number(self): return self.phone_number_util.isValidNumber(self.phone_number) def format_as_international(self): return self.phone_number_util.format(self.phone_number, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL) Let's format some phone numbers
  14. 14. Jython has a GUI from java.awt import BorderLayout from javax.swing import JButton, JFrame, JPanel, JLabel class SimpleGUI(object): def __init__(self): self.frame = JFrame( 'Hello World' , defaultCloseOperation = JFrame.EXIT_ON_CLOSE, size = ( 400, 400 )) self.label = JLabel ( 'Hello World' ) self.panel = JPanel() self.button = JButton( 'Click Me' , actionPerformed=self.hello) self.panel.add(self.button) self.content_panel = self.frame.getContentPane() self.content_panel.setLayout(BorderLayout()) self.content_panel.add(self.label, BorderLayout.CENTER) self.content_panel.add(self.panel, BorderLayout.PAGE_END) self.frame.visible = True def hello(self, event): self.label.setText( 'Hello user who clicked' ) if __name__ = = '__main__' : SimpleGUI()
  15. 15. Calling Jython from Java from com.censof.examples.interfaces import PersonType Class Person(Persontype) def __init__(self,name,gender): = name self.gender = gender def getPersonName(self): return Support for Java to use Jython classes It's not simple. Need jython class and interface. // Java interface for Person object package com.censof.examples.interfaces; public interface PersonType { public String getPersonName(); }
  16. 16. Calling Jython from Java package com.censof.examples.util; import com.censof.interfaces.PersonType; import org.python.core.PyObject; import org.python.core.PyString; import org.python.util.PythonInterpreter; public class PersonFactory { private PyObject personClass; PythonInterpreter interpreter = new PythonInterpreter(); interpreter.exec("from Person import Person"); personClass = interpreter.get("Person"); public PersonType create (String name, String location, String id) { PyObject personObject = personClass.__call__(new PyString(name), new PyString(gender), return (PersonType)buildingObject.__tojava__(PersonType.class); } } Then we need an object factory to coerce Jython module into a Java class
  17. 17. Calling Jython from Java package com.censof.examples; import com.censof.examples.util.PersonFactory; import com.censof.examples.interfaces.PersonType; public class Main { private static void print(PersonType person) { System.out.println("Person: " + person.getPersonName(); } public static void main(String[] args) { PersonFactory factory = new PersonFactory(); print(factory.create("Mark", "male")); print(factory.create("Joanne", "female")); } } Now we can call the jython class from java. Told you it's not simple.
  18. 18. Jython Scripting from Java import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class JSRMain { public static void main(String[] args) throws ScriptException { ScriptEngine engine = new ScriptEngineManager().getEngineByName("python"); engine.eval("import sys"); engine.eval("print sys.path"); engine.put("who", "Mark"); engine.eval("print who"); engine.eval("sum = 2 + 2"); Object x = engine.get("sum"); System.out.println("sum: " + x); } } JSR-223 enabled dynamic languages to be callable via Java.
  19. 19. Jython Scripting from Java import org.python.core.PyException; import org.python.core.PyInteger; import org.python.core.PyString; import org.python.core.PyObject; import org.python.util.PythonInterpreter; public class Main { public static void main(String[] args) throws PyException { PythonInterpreter interp = new PythonInterpreter(); interp.exec("import sys"); interp.exec("print sys.path"); interp.set("who", new PyString("Mark")); interp.exec("print who"); interp.exec("sum = 2+2"); PyObject x = interp.get("sum"); System.out.println("sum: " + x); } } You can also use the PythonInterpreter directly.
  20. 20. zxJDBC – Python DBAPI bridge to JDBC export CLASSPATH=/usr/share/java/postgresql.jar from __future__ import with_statement from com.ziclix.python.sql import zxJDBC jdbc_url = "jdbc:postgresql:wiki" username = "postgres" password = "secret" driver = "org.postgresql.Driver" with zxJDBC.connect(jdbc_url, username, password, driver) as conn: with conn: with conn.cursor() as c: c.execute( "select * from pages" ) c.fetchone() Database Access
  21. 21. zxJDBC understands JNDI (Java Naming & Directory Interface) allowing access to managed JDBC connections. from com.ziclix.python.sql import zxJDBC factory = "com.sun.jndi.fscontext.RefFSContextFactory" conn = zxJDBC.lookup( 'jdbc/postgresDS' , INITIAL_CONTEXT_FACTORY=factory) Database Access
  22. 22. Python ORM’s from sqlalchemy import create_engine, Column, Integer, String, Text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine( 'postgresql+zxjdbc://postgres:secret@localhost/wiki' ) session = sessionmaker(bind=engine) Base = declarative_base() class Page (Base): __tablename__ = 'pages ' id = Column(Integer, primary_key = True ) name = Column(String) data = Column(Text) def __init__ (self, name, data= None ): = name = data def __unicode__ (self): return &quot;<Page(%s)&quot; % (,)
  23. 23. Java ORM’s You can utilise Hibernate for persistance. See:
  24. 24. from javax.servlet.http import HttpServlet class MyJythonServlet (HttpServlet): def doGet(self,request,response): self.doPost (request,response) def doPost(self,request,response): toClient = response.getWriter() response.setContentType (&quot;text/html&quot;) toClient.println (&quot;<html><head><title>My Jython Servlet Demo</title>&quot; + &quot;<body><h1>Servlet Jython Servlet at&quot; + request.getContextPath() + &quot;</h1></body></html>&quot;) def getServletInfo(self): return &quot;A Simple Jython Servlet Demo&quot; Create web.xml, copy jython script, jython.jar in the CLASSPATH. http://localhost:8080/MyJythonServlet/ Do it the java way: Jython & the Web - Servlets
  25. 25. Do it the python way: modjy – WSGI compliant gateway for Jython def handler (environ, start_response): start_response ('200 OK' , [( 'Content-Type', 'text/plain' )]) yield 'Hello Worldn ' It's a java jvm, so there's still some xml: web.xml <web-app> <display-name>modjy demo application</display-name> <description>modjy WSGI demo application</description> <servlet> <servlet-name>modjy</servlet-name> <servlet-class>com.xhaus.modjy.ModjyJServlet</servlet-class> … . <init-param> <param-name>app_filename</param-name> <param-value></param-value> </init-param> …... Jython & the Web - modjy
  26. 26. Jython & the Web - django
  27. 27. pip install django Downloading/unpacking django Downloading Django-1.3.tar.gz (6.5Mb): 6.5Mb downloaded Running egg_info for package django Installing collected packages: django Running install for django Successfully installed django pip install django_jython==1.3.0b1 Downloading/unpacking django-jython==1.3.0b1 Downloading django-jython-1.3.0b1.tar.gz (42Kb): 42Kb downloaded Running egg_info for package django-jython Installing collected packages: django-jython Running install for django-jython Successfully installed django-jython In jython environment, install django: Then install django_jython Jython & the Web - django
  28. 28. startproject wiki cd wiki vi DATABASES = { 'default': { 'ENGINE': 'doj.backends.zxjdbc.postgresql', # 'doj.backends.zxjdbc. postgresql', 'doj.backends.zxjdbc.mysql', 'doj.backends.zxjdbc.sqlite3' or ‘'. … . } export CLASSPATH=/usr/share/java/postgresql.jar:$CLASSPATH jython syncdb jython runserver Validating models... 0 errors found Django version 1.3, using settings 'wiki.settings' Development server is running at Quit the server with CONTROL-C. Then configure using zxjdbc for databases: Jython & the Web - django
  29. 29. vi # Add doj to INSTALLED_APPS INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', … . doj,) Thanks to modjy & django_jython we can deploy as a servlet: jython war –include-java-libs=/usr/share/java/postgresql.jar Copying WAR skeleton... Copying jython.jar... … . Copying postgresql.jar... Building WAR on /home/mark/swdev/jython-pycon-apac-2011/django_wiki/wiki.war... Finished. Now you can copy wiki.war to whatever location your application server wants it. Create WAR for deployment: Jython & the Web - django
  30. 30. Jython & the Web - pyramid
  31. 31. Most things work of of the box under Jython Database access thanks to SQLAlchemy snakefight handles deployment under Java servlet containers. Works with any paster based web app. Jython & the Web - pyramid
  32. 32. YES Did Jython really save the day?
  33. 33. Jython Website The Definitive Guide to Jython Book / Resources
  34. 34. Credits for images used
  35. 35. Q & A