Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. ---
  2. title: Using Python
  3. order: 14
  4. layout: page
  5. ---
  6. [[developing-vaadin-apps-with-python]]
  7. = Developing Vaadin apps with Python
  8. [[to-accomplish-exactly-what]]
  9. To accomplish exactly what?
  10. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  11. This article describes how to start developing Vaadin apps with Python
  12. programming language. Goal is that programmer could use Python instead
  13. of Java with smallest amount of boilerplate code necessary to get the
  14. environment working.
  15. Luckily Python can make use of Java classes and vice versa. For detailed
  16. tutorial how to accomplish this in general please see
  17. http://www.jython.org/jythonbook/en/1.0/JythonAndJavaIntegration.html
  18. and http://wiki.python.org/jython/UserGuide.
  19. [[requirements]]
  20. Requirements
  21. ^^^^^^^^^^^^
  22. For setup used in this article you will need to install PyDev plugin to
  23. your Eclipse and Jython. See http://pydev.org/ and
  24. http://www.jython.org/ for more details.
  25. [[lets-get-started]]
  26. Let's get started
  27. ^^^^^^^^^^^^^^^^^
  28. To get started create a new Vaadin project or open existing as you would
  29. normally do. As you have PyDev installed as Eclipse plugin you can start
  30. developing after few steps.
  31. * Add Python nature to your project by right clicking the project and
  32. selecting PyDev -> Set as PyDev Project. After this the project
  33. properties has PyDev specific sections.
  34. * Go to PyDev - Interpreter/Grammar and select Jython as your Python
  35. interpreter.
  36. * Add a source folder where your Python source code will reside. Go to
  37. section PyDev - PYTHONPATH and add source folder. Also add
  38. vaadin-x.x.x.jar to PYTHONPATH in external libraries tab.
  39. * Add jython.jar to your project's classpath and into deployment
  40. artifact.
  41. * Map your python source folder into WEB-INF/classes in deployment
  42. artifact. Go to Deployment Assembly -> Add -> Folder.
  43. image:img/deployartifact.png[Deploy artifact]
  44. [[modify-web.xml-and-applicationservlet]]
  45. Modify web.xml and ApplicationServlet
  46. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  47. First of all to build a basic Vaadin app you need to define your app in
  48. web.xml. You have something like this in your web.xml:
  49. [source,xml]
  50. ....
  51. <servlet>
  52. <servlet-name>Vaadin Application</servlet-name>
  53. <servlet-class>com.vaadin.terminal.gwt.server.ApplicationServlet</servlet-class>
  54. <init-param>
  55. <description>Vaadin application class to start</description>
  56. <param-name>application</param-name>
  57. <param-value>com.vaadin.example.ExampleApplication</param-value>
  58. </init-param>
  59. </servlet>
  60. ....
  61. This will have to be modified a bit. Servlet init parameter application
  62. is a Java class name which will be instantiated for each user session.
  63. Default implementation of
  64. `com.vaadin.terminal.gwt.server.ApplicationServlet` can only instantiate
  65. Java classes so therefore you must override that class so that it is
  66. able to instantiate Python objects. Of course if you want the main
  67. Application object to be a Java class there is no need to modify the
  68. web.xml.
  69. Here's the modified section of web.xml. Implementation of PythonServlet
  70. is explained later. Init parameter application is now actually Python
  71. class.
  72. [source,xml]
  73. ....
  74. <servlet>
  75. <servlet-name>Python Application</servlet-name>
  76. <servlet-class>com.vaadin.example.pythonapp.PythonServlet</servlet-class>
  77. <init-param>
  78. <description>Vaadin application class to start</description>
  79. <param-name>application</param-name>
  80. <param-value>python.vaadin.pythonapp.PyApplication</param-value>
  81. </init-param>
  82. </servlet>
  83. ....
  84. And here's the PythonServlet. This is altered version of original Vaadin
  85. ApplicationServlet.
  86. [source,java]
  87. ....
  88. package com.vaadin.example.pythonapp;
  89. import javax.servlet.ServletException;
  90. import javax.servlet.http.HttpServletRequest;
  91. import org.python.core.PyObject;
  92. import org.python.util.PythonInterpreter;
  93. import com.vaadin.Application;
  94. import com.vaadin.terminal.gwt.server.AbstractApplicationServlet;
  95. public class PythonServlet extends AbstractApplicationServlet {
  96. // Private fields
  97. private Class<? extends Application> applicationClass;
  98. /**
  99. * Called by the servlet container to indicate to a servlet that the servlet
  100. * is being placed into service.
  101. *
  102. * @param servletConfig
  103. * the object containing the servlet's configuration and
  104. * initialization parameters
  105. * @throws javax.servlet.ServletException
  106. * if an exception has occurred that interferes with the
  107. * servlet's normal operation.
  108. */
  109. @Override
  110. public void init(javax.servlet.ServletConfig servletConfig)
  111. throws javax.servlet.ServletException {
  112. super.init(servletConfig);
  113. final String applicationModuleName = servletConfig
  114. .getInitParameter("application");
  115. if (applicationModuleName == null) {
  116. throw new ServletException(
  117. "Application not specified in servlet parameters");
  118. }
  119. String[] appModuleSplitted = applicationModuleName.split("\\.");
  120. if(appModuleSplitted.length < 1) {
  121. throw new ServletException("Cannot parse class name");
  122. }
  123. final String applicationClassName = appModuleSplitted[appModuleSplitted.length-1];
  124. try {
  125. PythonInterpreter interpreter = new PythonInterpreter();
  126. interpreter.exec("from "+applicationModuleName+" import "+applicationClassName);
  127. PyObject pyObj = interpreter.get(applicationClassName).__call__();
  128. Application pyApp = (Application)pyObj.__tojava__(Application.class);
  129. applicationClass = pyApp.getClass();
  130. } catch (Exception e) {
  131. e.printStackTrace();
  132. throw new ServletException("Failed to load application class: "
  133. + applicationModuleName, e);
  134. }
  135. }
  136. @Override
  137. protected Application getNewApplication(HttpServletRequest request)
  138. throws ServletException {
  139. // Creates a new application instance
  140. try {
  141. final Application application = getApplicationClass().newInstance();
  142. return application;
  143. } catch (final IllegalAccessException e) {
  144. throw new ServletException("getNewApplication failed", e);
  145. } catch (final InstantiationException e) {
  146. throw new ServletException("getNewApplication failed", e);
  147. } catch (ClassNotFoundException e) {
  148. throw new ServletException("getNewApplication failed", e);
  149. }
  150. }
  151. @Override
  152. protected Class<? extends Application> getApplicationClass()
  153. throws ClassNotFoundException {
  154. return applicationClass;
  155. }
  156. }
  157. ....
  158. The most important part is the following. It uses Jython's
  159. PythonInterpreter to instantiate and convert Python classes into Java
  160. classes. Then Class object is stored for later use of creating new
  161. instances of it on demand.
  162. [source,java]
  163. ....
  164. PythonInterpreter interpreter = new PythonInterpreter();
  165. interpreter.exec("from "+applicationModuleName+" import "+applicationClassName);
  166. PyObject pyObj = interpreter.get(applicationClassName).__call__();
  167. Application pyApp = (Application)pyObj.__tojava__(Application.class);
  168. ....
  169. Now the Python application for Vaadin is good to go. No more effort is
  170. needed to get it running. So next we see how the application itself can
  171. be written in Python.
  172. [[python-style-application-object]]
  173. Python style Application object
  174. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  175. Creating an Application is pretty straightforward. You would write class
  176. that is identical to the Java counterpart except it's syntax is Python.
  177. Basic hello world application would look like this
  178. [source,python]
  179. ....
  180. from com.vaadin import Application
  181. from com.vaadin.ui import Label
  182. from com.vaadin.ui import Window
  183. class PyApplication(Application):
  184. def __init__(self):
  185. pass
  186. def init(self):
  187. mainWindow = Window("Vaadin with Python")
  188. label = Label("Vaadin with Python")
  189. mainWindow.addComponent(label)
  190. self.setMainWindow(mainWindow)
  191. ....
  192. [[event-listeners]]
  193. Event listeners
  194. ^^^^^^^^^^^^^^^
  195. Python does not have anonymous classes like Java and Vaadin's event
  196. listeners rely heavily on implementing listener interfaces which are
  197. very often done as anonymous classes. So therefore the closest
  198. equivalent of
  199. [source,java]
  200. ....
  201. Button button = new Button("java button");
  202. button.addListener(new Button.ClickListener() {
  203. public void buttonClick(ClickEvent event) {
  204. //Do something for the click
  205. }
  206. });
  207. ....
  208. is
  209. [source,python]
  210. ....
  211. button = Button("python button")
  212. class listener(Button.ClickListener):
  213. def buttonClick(self, event):
  214. #do something for the click
  215. button.addListener(listener())
  216. ....
  217. Jython supports for some extend AWT/Swing-style event listeners but
  218. however that mechanism is not compatible with Vaadin. Same problem
  219. applies to just about anything else event listening interface in Java
  220. libraries like Runnable or Callable. To reduce the resulted verbosity
  221. some decorator code can be introduced like here
  222. https://gist.github.com/sunng87/947926.
  223. [[creating-custom-components]]
  224. Creating custom components
  225. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  226. Creating custom Vaadin components is pretty much as straightforward as
  227. the creation of Vaadin main application. Override the CustomComponent
  228. class in similar manner as would be done with Java.
  229. [source,python]
  230. ....
  231. from com.vaadin.ui import CustomComponent
  232. from com.vaadin.ui import VerticalLayout
  233. from com.vaadin.ui import Label
  234. from com.vaadin.ui import Button
  235. from com.vaadin.terminal import ThemeResource
  236. class PyComponent(CustomComponent, Button.ClickListener):
  237. def __init__(self):
  238. mainLayout = VerticalLayout()
  239. button = Button("click me to toggle the icon")
  240. self.label = Label()
  241. button.addListener(self)
  242. mainLayout.addComponent(self.label)
  243. mainLayout.addComponent(button)
  244. self.super__setCompositionRoot(mainLayout)
  245. def buttonClick(self, event):
  246. if self.label.getIcon() == None:
  247. self.label.setIcon(ThemeResource("../runo/icons/16/lock.png"));
  248. else:
  249. self.label.setIcon(None)
  250. ....
  251. [[containers-and-pythonbeans]]
  252. Containers and PythonBeans
  253. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  254. Although not Python style of doing things there are some occasions that
  255. require use of beans.
  256. Let's say that you would like to have a table which has it's content
  257. retrieved from a set of beans. Content would be one row with two columns
  258. where cells would contain strings "first" and "second" respectively. You
  259. would write this code to create and fill the table.
  260. [source,python]
  261. ....
  262. table = Table()
  263. container = BeanItemContainer(Bean().getClass())
  264. bean = Bean()
  265. bean.setFirst("first")
  266. bean.setSecond("second")
  267. container.addItem(bean)
  268. table.setContainerDataSource(container)
  269. ....
  270. and the Bean object would look like this
  271. [source,python]
  272. ....
  273. class Bean(JavaBean):
  274. def __init__(self):
  275. self.__first = None
  276. self.__second = None
  277. def getFirst(self):
  278. return self.__first
  279. def getSecond(self):
  280. return self.__second
  281. def setFirst(self, val):
  282. self.__first = val
  283. def setSecond(self, val):
  284. self.__second = val
  285. ....
  286. and JavaBean
  287. [source,java]
  288. ....
  289. public interface JavaBean {
  290. String getFirst();
  291. void setFirst(String first);
  292. String getSecond();
  293. void setSecond(String second);
  294. }
  295. ....
  296. Note that in this example there is Java interface mixed into Python
  297. code. That is because Jython in it's current (2.5.2) version does not
  298. fully implement reflection API for python objects. Result without would
  299. be a table that has no columns.
  300. Implementing a Java interface adds necessary piece of information of
  301. accessor methods so that bean item container can handle it.
  302. [[filtering-container]]
  303. Filtering container
  304. ^^^^^^^^^^^^^^^^^^^
  305. Let's add filtering to previous example. Implement custom filter that
  306. allows only bean that 'first' property is set to 'first'
  307. [source,python]
  308. ....
  309. container.addContainerFilter(PyFilter())
  310. class PyFilter(Container.Filter):
  311. def appliesToProperty(self, propertyId):
  312. return True
  313. def passesFilter(self, itemId, item):
  314. prop = item.getItemProperty("first")
  315. if prop.getValue() == "first":
  316. return True
  317. else:
  318. return False
  319. ....
  320. Again pretty straightforward.
  321. [[debugging]]
  322. Debugging
  323. ^^^^^^^^^
  324. Debugging works as you would debug any Jython app remotely in a servlet
  325. engine. See PyDev's manual for remote debugging at
  326. http://pydev.org/manual_adv_remote_debugger.html.
  327. Setting breakpoints directly via Eclipse IDE however does not work.
  328. Application is started as a Java application and the debugger therefore
  329. does not understand Python code.
  330. [[final-thoughts]]
  331. Final thoughts
  332. ^^^^^^^^^^^^^^
  333. By using Jython it allows easy access from Python code to Java code
  334. which makes it really straightforward to develop Vaadin apps with
  335. Python.
  336. Some corners are bit rough as they require mixing Java code or are not
  337. possible to implement with Python as easily or efficiently than with
  338. Java.
  339. [[how-this-differs-from-muntjac]]
  340. How this differs from Muntjac?
  341. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  342. https://pypi.python.org/pypi/Muntjac[Muntjac project]
  343. is a python translation of Vaadin and it's goal is pretty much same as
  344. this article's: To enable development of Vaadin apps with Python.
  345. Muntjac's approach was to take Vaadin's Java source code and translate
  346. it to Python while keeping the API intact or at least similar as
  347. possible. While in this article the Vaadin itself is left as is.
  348. Simple Python applications like shown above can be executed with Vaadin
  349. or Muntjac. Application code should be compatible with both with small
  350. package/namespace differences.
  351. Muntjac requires no Jython but it also lacks the possibility to use Java
  352. classes directly.
  353. The problems we encountered above with requiring the use of mixed Java
  354. code are currently present in Muntjac (v1.0.4) as well. For example the
  355. BeanItemContainer is missing from the Muntjac at the moment.