• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
What do you mean it needs to be Java based? How jython saved the day.
 

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

on

  • 3,418 views

Slides of talk given at PyCon APAC 2011 in Singapore.

Slides of talk given at PyCon APAC 2011 in Singapore.

Statistics

Views

Total Views
3,418
Views on SlideShare
3,309
Embed Views
109

Actions

Likes
3
Downloads
0
Comments
0

4 Embeds 109

http://lanyrd.com 43
http://life-of-a-tech-dude.blogspot.com 41
http://www.lifeofatechdude.com 24
http://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Allowed us to use our existing python code with no or min code change
  • Allowed us to use our existing python code with no or min code change Haven't found that only Python 2.5 support an issue Works with virtualenv, easy_install, pip etc
  • Need Java JRE 5 or 6 installed Download jython installer jar from http://www.jython.org/downloads.html
  • Performance Startup time an issue but less impact for long running processes Replace Python code with calls to Java libs where speedup necessary
  • Needed to format phone numbers, looked for existing code. Found libphonenumber, Google's common Java library for parsing, formatting, storing and validating international phone numbers, at the time, no Python library (there is now :-]). Java code must be in CLASSPATH
  • Cpython has tcl/tk as it ’ s ” standard ” GUI. Does anyone use it about from IDLE Jython ’ s GUI is what ships with Java AWT/Swing. a It ’ s a nice GUI toolkit and Jython makes it esy to use.
  • jython.jar must be in CLASSPATH Also JSR-223 only works with jython 2.5.1+
  • Support prior to Jython 2.5.1 Allows access to Python Objects
  • zxJDBC was contributed by Brian Zimmer,a Jython committer. This API was written to enable Jython developers to have the capability of working with databases using techniques that more closely resembled the Python DB API. Originally a standaolne package it is now part of the Jython distribution
  • Thanks to zxjdbc, SQLAlchemy runs great under Jython. With exception of jdbc uri, the rest of the code is identical to CPython.
  • Jython script must be the same name as the class Create MyJythonServlet sub directory in Tomcat webapps directory. Copy web.xml to WEB-INF directory in the MyJythonServlet directory.
  • . Created by Alan Kennedy during early days of WSGI PEP 333.Now part of jython distribution.
  • django_jython Development server runs under jython
  • Support zxjdbc support added by django_jython package.
  • New command war added by django_jython means no need to create web.xml or package as war file manually. Gotcha: If there is already a jython.jar & cachedir in server lib, you will get a ” maximum recursion depth exceeded ” error. Two options: 1. Have separate jython.jars per app (default for doj) or 2. Use –shared-war doj war creation option.
  • Limitations – cannot use AST based template languages – no Chameleon, use Jinja2 or Mako Snakefight to package
  • Running inside WebSphere Using JasperReports Scripting workflow systems

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

  • What do you mean it needs to be Java based? How Jython saved the day! Mark Rees Group CTO Century Software Holdings Berhad http://www.censof.com/ @hexdump42
  • Century Software (M) Sdn Bhd http://www.centurysoftware.com.my Develop & implement Financial Management Software Solutions Some of our applications use Python. Who?
  • From a tender document ” The application must be written in an industry standard enterprise programming framework. Please state which framework. ” The problem
  • Python! Our preferred answer
  • Java or .NET The expected answer
  • ” The web application must run using an Enterprise Web Application Server. ” Another problem
  • Django, Pyramid, ... Our preferred answer
  • Websphere, JBoss, OAS... The expected answer
  • The solution
  • Jython Equivalent to Python Reference Version 2.5 Includes standard library
  • Installation java -jar jython_installer-2.5.2.jar
  • Pros Runs most existing Python code without mods No GIL Access to Java Libraries Cons Performance No C extensions Pros & Cons
  • Call Java Code from com.google.i18n.phonenumbers import PhoneNumberUtil class PhoneNumberi18n: def __init__(self, country, phonenumber): self.phone_number_util = PhoneNumberUtil.getInstance() self.raw_phone_number = phonenumber self.country = 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 http://code.google.com/p/libphonenumber/
  • 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()
  • Calling Jython from Java from com.censof.examples.interfaces import PersonType Class Person(Persontype) def __init__(self,name,gender): self.name = name self.gender = gender def getPersonName(self): return self.name 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(); }
  • 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
  • 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.
  • 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.
  • 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.
  • 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
  • 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
  • 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 ): self.name = name self.data = data def __unicode__ (self): return &quot;<Page(%s)&quot; % (self.name,)
  • Java ORM’s You can utilise Hibernate for persistance. See: http://www.jython.org/jythonbook/en/1.0/DatabasesAndJython.html#hibernate
  • 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/MyJythonServlet.py Do it the java way: Jython & the Web - Servlets
  • 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>helloworld.py</param-value> </init-param> …... Jython & the Web - modjy
  • Jython & the Web - django
  • pip install django Downloading/unpacking django Downloading Django-1.3.tar.gz (6.5Mb): 6.5Mb downloaded Running setup.py egg_info for package django Installing collected packages: django Running setup.py 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 setup.py egg_info for package django-jython Installing collected packages: django-jython Running setup.py install for django-jython Successfully installed django-jython In jython environment, install django: Then install django_jython Jython & the Web - django
  • django-admin.py startproject wiki cd wiki vi settings.py DATABASES = { 'default': { 'ENGINE': 'doj.backends.zxjdbc.postgresql', # 'doj.backends.zxjdbc. postgresql', 'doj.backends.zxjdbc.mysql', 'doj.backends.zxjdbc.sqlite3' or ‘ doj.backends.zxjdbc.oracle'. … . } export CLASSPATH=/usr/share/java/postgresql.jar:$CLASSPATH jython manage.py syncdb jython manage.py runserver Validating models... 0 errors found Django version 1.3, using settings 'wiki.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Then configure using zxjdbc for databases: Jython & the Web - django
  • vi settings.py # 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 manage.py 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
  • Jython & the Web - pyramid
  • 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. http://pypi.python.org/pypi/snakefight Jython & the Web - pyramid
  • YES Did Jython really save the day?
  • Jython Website http://www.jython.org/ The Definitive Guide to Jython Book http://www.jythonbook.com / Resources
  • http://djangopony.com/ http://www.felixlaflamme.com/2011/03/16/pyramid-web-application-framework/ Credits for images used
  • Q & A