This function creates a new player object each time it is invoked
and inserts a record into the corresponding database table.
'''
addNew = 'Y'
print "Add a player to the roster by providing the following information\n"
while addNew.upper() == 'Y':
first = raw_input("First Name: ")
last = raw_input("Last Name: ")
position = raw_input("Position: ")
id = len(self.return_player_list())
session = self.factory.openSession()
try:
tx = session.beginTransaction()
player = Player()
player.first = first
player.last = last
player.position = position
session.save(player)
tx.commit()
except Exception,e:
if tx!=None:
tx.rollback()
print e
finally:
session.close()
print "Player successfully added to the roster\n"
addNew = raw_input("Add another? (Y or N)")
self.make_selection()
def print_roster(self):
'''
Prints the contents of the Player database table
'''
print "====================\n"
print "Complete Team Roster\n"
print "======================\n\n"
playerList = self.return_player_list()
for player in playerList:
print "%s %s - %s" % (player.first, player.last, player.position)
print "\n"
print "=== End of Roster ===\n"
self.make_selection()
def search_roster(self):
'''
Takes input from the command line for a player's name to search within the
database. If the player is found in the list then an affirmative message
is printed. If not found, then a negative message is printed.
'''
index = 0
found = False
print "Enter a player name below to search the team\n"
first = raw_input("First Name: ")
www.it-ebooks.info
CHAPTER 12
■
DATABASES AND JYTHON: OBJECT RELATIONAL MAPPING AND USING JDBC
259
last = raw_input("Last Name: ")
position = None
playerList = self.return_player_list()
while index < len(playerList):
player = playerList[index]
if player.first.upper() == first.upper():
if player.last.upper() == last.upper():
found = True
position = player.position
index = index + 1
if found:
print '%s %s is in the roster as %s' % (first, last, position)
else:
print '%s %s is not in the roster.' % (first, last)
self.make_selection()
def remove_player(self):
'''
Removes a designated player from the database
'''
index = 0
found = False
print "Enter a player name below to remove them from the team roster\n"
first = raw_input("First Name: ")
last = raw_input("Last Name: ")
position = None
playerList = self.return_player_list()
found_player = Player()
while index < len(playerList):
player = playerList[index]
if player.first.upper() == first.upper():
if player.last.upper() == last.upper():
found = True
found_player = player
index = index + 1
if found:
print '''%s %s is in the roster as %s,
are you sure you wish to remove?''' % (found_player.first,
found_player.last,
found_player.position)
yesno = raw_input("Y or N")
if yesno.upper() == 'Y':
session = self.factory.openSession()
tx = None
try:
delQuery = "delete from Player player where id = %s" % (found_player.id)
tx = session.beginTransaction()
q = session.createQuery(delQuery)
q.executeUpdate()
tx.commit()
print 'The player has been removed from the roster', found_player.id
except Exception,e:
if tx!=None:
www.it-ebooks.info
CHAPTER 12
■
DATABASES AND JYTHON: OBJECT RELATIONAL MAPPING AND USING JDBC
260
tx.rollback()
print e
finally:
session.close
else:
print 'The player will not be removed'
else:
print '%s %s is not in the roster.' % (first, last)
self.make_selection()
def return_player_list(self):
'''
Connects to database and retrieves the contents of the
player table
'''
session = self.factory.openSession()
try:
tx = session.beginTransaction()
playerList = session.createQuery("from Player").list()
tx.commit()
except Exception,e:
if tx!=None:
tx.rollback()
print e
finally:
session.close
return playerList
# main
#
# This is the application entry point. It simply prints the application title
# to the command line and then invokes the makeSelection() function.
if __name__ == "__main__":
print "Hockey Roster Application\n\n"
hockey = HockeyRoster()
hockey.make_selection()
We begin our implementation in the main block, where the HockeyRoster class is instantiated. As
you can see, the hibernate configuration is initialized and the session factory is built within the class
initializer. Next, the make_selection() method is invoked which begins the actual execution of the
program. The entire Hibernate configuration resides within the Java project, so we are not working with
XML here, just making use of it. The code then begins to branch so that various tasks can be performed.
In the case of adding a player to the roster, a user could enter the number 1 at the command prompt.
You can see that the addPlayer() function simply creates a new Player object, populates it, and saves it
into the database. Likewise, the searchRoster() function calls another function named returnPlayerList()
which queries the player table using Hibernate query language and returns a list of Player objects.
In the end, we have a completely scalable solution. We can code our entities using a mature and
widely used Java ORM solution, and then implement the rest of the application in Jython. This allows us
to make use of the best features of the Python language, but at the same time, persist our data using Java.
www.it-ebooks.info
CHAPTER 12
■
DATABASES AND JYTHON: OBJECT RELATIONAL MAPPING AND USING JDBC
261
Summary
You would be hard-pressed to find too many enterprise-level applications today that do not make use of
a relational database in one form or another. The majority of applications in use today use databases to
store information as they help to provide robust solutions. That being said, the topics covered in this
chapter are very important to any developer. In this chapter, we learned that there are many different
ways to implement database applications in Jython, specifically through the Java database connectivity
API or an object relational mapping solution.
www.it-ebooks.info
www.it-ebooks.info
C H A P T E R 13
■ ■ ■
263
P A R T III
■ ■ ■
Developing Applications with Jython www.it-ebooks.info
CHAPTER 13
■
SIMPLE WEB APPLICATIONS
264
www.it-ebooks.info
C H A P T E R 13
■ ■ ■
265
Simple Web Applications One of the major benefits of using Jython is the ability to make use of Java platform capabilities
programming in the Python programming language instead of Java. In the Java world today, the most
widely used web development technique is the Java servlet. Now in JavaEE, there are techniques and
frameworks used so that we can essentially code HTML or other markup languages as opposed to
writing pure Java servlets. However, sometimes writing a pure Java servlet still has its advantages. We
can use Jython to write servlets and this adds many more advantages above and beyond what Java has to
offer because now we can make use of Python language features as well. Similarly, we can code web start
applications using Jython instead of pure Java to make our lives easier. Coding these applications in pure
Java has proven sometimes to be a difficult and sometimes grueling task. We can use some of the
techniques available in Jython to make our lives easier. We can even code WSGI applications with Jython
making use of the modjy integration in the Jython project.
In this chapter, we will cover three techniques for coding simple web applications using Jython:
servlets, web start, and WSGI. We’ll get into details on using each of these different techniques here, but
we will discuss deployment of such solutions in Chapter 17.
Servlets
Servlets are a Java platform technology for building web-based applications. They are a platform- and
server-independent technology for serving content to the web. If you are unfamiliar with Java servlets, it
would be worthwhile to learn more about them. An excellent resource is wikipedia
(http://en.wikipedia.org/wiki/Java_Servlet); however, there are a number of other great places to find
out more about Java servlets. Writing servlets in Jython is a very productive and easy way to make use of
Jython within a web application. Java servlets are rarely written using straight Java anymore. Most Java
developers make use of Java Server Pages (JSP), Java Server Faces (JSF), or some other framework so that
they can use a markup language to work with web content as opposed to only working with Java code.
However, in some cases it is still quite useful to use a pure Java servlet. For these cases we can make our
lives easier by using Jython instead. There are also great use-cases for JSP; similarly, we can use Jython
for implementing the logic in our JSP code. The latter technique allows us to apply a model-view-
controller (MVC) paradigm to our programming model, where we separate our front-end markup from
any implementation logic. Either technique is rather easy to implement, and you can even add this
functionality to any existing Java web application without any trouble.
Another feature offered to us by Jython servlet usage is dynamic testing. Because Jython compiles at
runtime, we can make code changes on the fly without recompiling and redeploying our web
application. This can make it very easy to test web applications, because usually the most painful part of
web application development is the wait time between deployment to the servlet container and testing.
www.it-ebooks.info
CHAPTER 13
■
SIMPLE WEB APPLICATIONS
266
Configuring Your Web Application for Jython Servlets
Very little needs to be done in any web application to make it compatible for use with Jython servlets.
Jython contains a built-in class named PyServlet that facilitates the creation of Java servlets using Jython
source files. We can make use of PyServlet quite easily in our application by adding the necessary XML
configuration into the application’s web.xml descriptor such that the PyServlet class gets loaded at
runtime and any file that contains the .py suffix will be passed to it. Once this configuration has been
added to a web application, and jython.jar has been added to the CLASSPATH then the web application
is ready to use Jython servlets. See Listing 13-1.
Listing 13-1. Making a Web Application Compatible with Jython PyServlet org.python.util.PyServlet 1
PyServlet *.py
Any servlet that is going to be used by a Java servlet container also needs to be added to the web.xml file as well, since this allows for the correct mapping of the servlet via the URL. For the purposes of this
book, we will code a servlet named NewJythonServlet in the next section, so the following XML
configuration will need to be added to the web.xml file. See Listing 13-2.
Listing 13-2. Coding a Jython Servlet NewJythonServlet NewJythonServlet
NewJythonServlet /NewJythonServlet
Writing a Simple Servlet
In order to write a servlet, we must have the javax.servlet.http.HttpServlet abstract Java class within our
CLASSPATH so that it can be extended by our Jython servlet to help facilitate the code. This abstract
class, along with the other servlet implementation classes, is part of the servlet-api.jar file. According to
the abstract class, there are two methods that we should override in any Java servlet, those being doGet and doPost. The former performs the HTTP GET operation while the latter performs the HTTP POST
operation for a servlet. Other commonly overridden methods include doPut, doDelete, and
getServletInfo. The first performs the HTTP PUT operation, the second performs the HTTP DELETE
operation, and the last provides a description for a servlet. In the following example, and in most use-
cases, only the doGet and doPost are used.
www.it-ebooks.info
CHAPTER 13
■
SIMPLE WEB APPLICATIONS
267
Let’s first show the code for an extremely simple Java servlet. This servlet contains no functionality
other than printing its name along with its location in the web application to the screen. Following that
code we will take a look at the same servlet coded in Jython for comparison (Listing 13-3).
Listing 13-3. NewJavaServlet.java import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Modjy servlet running correctly:
jython $version on $platform:
Hello jython WSGI on your local server!
Here are the contents of the WSGI environment
'''
environ_str = "
"
keys = environ.keys()
keys.sort()
for ix, name in enumerate(keys):
if ix % 2:
background='#ffffff'
else:
background='#eeeeee'
style = " " % background
value = escape_html(cutoff(str(environ[name]))) or ' '
environ_str = "%s\n