Spring Python 1.1
Back in 2004, a new revolution was brewing in the Java industry: the Spring Framework.
It challenged the concept of monolithic, one-size-fits-all application servers by offering
pragmatic solutions without heavy handed requirements. Contrary to previous
frameworks, Spring did not require all-or-nothing adoption. Instead, it offered a practical
approach by providing convenient abstractions over commonly used patterns. It also
embraced the concept of dependency injection, allowing non-intrusive adoption of
powerful options.
The Spring Framework doesn’t hinge on the technology that it is coded in. The concepts
and methods, known as the Spring way, work anywhere. In 2006, I created the Spring
Python project. This was to combine the non-intrusive, powerful concepts of Spring with
the nimble, dynamic flexibility of Python.
This book will guide you through the building blocks of Spring Python with the aim of
giving you the key to build better Python applications.
The first seven chapters show you how to download and get started with Spring Python.
Each of these chapters introduces a different module you can use to build applications
with. The eighth chapter shows how to use the modules in concert to build a more
powerful yet easier to maintain application. The ninth chapter introduces a command-line
utility used to rapidly create applications. The final chapter shows how to integrate
Python and Java together, quickly and easily.
I have written this book with the intention that developers can discover the scope and
beauty of the Spring way and how it can enrich development, without complicating it. I
often look at software development as more craftsmanship than science, and believe
Spring Python can make for a valuable tool in any developer’s tool box.
What This Book Covers
Chapter 1: Getting Started with Spring Python gives you a quick glance at various
features of Spring Python, followed by information on how to download and install it.
Chapter 2: The Heart of Spring Python—Inversion of Control introduces you to Spring
Python’s core container which is reused through the rest of the book to empower testing
and non-intrusive features.
Chapter 3: Adding Services to APIs shows how to smoothly add cross cutting services to
your code using Spring Python’s aspect oriented programming.
Chapter 4: Easily Writing SQL Queries with Spring Python shows you how to rapidly
write pure SQL queries without dealing with mind-numbing boilerplate code. It also
shows how Spring Python works nicely with ORM-based persistence.
Chapter 5: Adding Integrity to your Data Access with Transactions shows how to
seamlessly wrap business code with SQL transactions.
Chapter 6: Securing your Application with Spring Python shows how to wrap web
applications with flexible authentication and authorization services, while easily
supporting policy changes. It also shows how to code custom extensions to integrate with
security systems not currently supported.
Chapter 7: Scaling your Application Across Nodes with Spring Python’s Remoting shows
how Spring Python nicely integrates with Pyro, the RPC library for Python. This
powerful combination will allow you to non-intrusively develop simple apps on your
desktop and retool them for multi-node production systems
Chapter 8: Case Study I—Integrating Spring Python with your Web Application invites
you to use all of Spring Python’s components to build a strong, secured banking
application. This shows how the various parts of Spring Python work together in concert
to empower you the developer.
Chapter 9: Creating Skeleton Apps with Coily introduces Spring Python’s plugin-based
Coily tool to rapidly create web applications.
Chapter 10: Case Study II – Integration Spring Python with your Java Application ends
the book by showing how easy it is to link Java and Python components together using
Jython. This allows polyglot programmers to mix together their favorite services.
Spring Framework Articles
- Spring Framework Articles
- Introduction to Spring MVC Web Framework – Web Tier
- Integrating Spring Framework with Hibernate ORM Framework
- Introduction to Spring Web Framework
- Introduction to Spring’s Aspect Oriented Programming(AOP)
- Introduction to Spring Web Services
The Heart of Spring Python—Inversion of Control
Many software teams seek ways to improve productivity without sacrificing quality.
This has led to an increase in automated testing and, in turn, sparked an interest
in making applications more testable. Many automated test frameworks promote
isolating objects by swapping collaborating objects with test doubles to provide
canned responses. This generates a need for developers to plugin test doubles with
as little change as possible.
On some occasions, managers have trimmed budgets by cutting back on
development and integration hardware. This leaves developers with the quandary
of having to develop on a smaller footprint than their production environment.
Software developers need the ability to switch between different test configurations
and deployment scenarios.
Software products sold to customers often need the ability to make fl exible
adjustments on site, whether its through a company representative or from
the customer.
In this chapter, we will explore how Spring Python’s Inversion of Control (IoC)
container meets all these needs by making it possible to move the creation of critical
objects into a container definition, allowing fl exible adjustment without impacting
the core business code.
This chapter will cover:
- How IoC containers make it easy to isolate objects under test in order to
work with automated testing. - A detailed explanation of IoC with high level diagrams. We will learn how
Dependency Injection is a type of IoC and uses the Hollywood principle of
Don’t call us, we’ll call you! - Spring Python’s IoC container, which handles dependency resolution,
setting properties, and lazy initialiation. It also provides extension points
for developers to utilize as needed. - Spring Python’s answer to the community debate of IoC in
dynamic languages. - How mixing Python and Java components together is easy, can be done
many ways, and provides a good way for developers to choose what best
fits their needs.
Swapping production code with test doubles
As developers, we need the ability to exchange production objects with mocks
and stubs.
Mocks and stubs are two ways of generating canned responses used
to test our code. Mocks are used to generate canned method calls.
Stubs are used to generate canned data. Both of these are useful
tools to simulate external components our code must work with.
For more details, see http://martinfowler.com/articles/
mocksArentStubs.html
In this example, we are going to explore how an IoC container makes it easy to
exchange production objects with mock instances. We start by developing a simple
service along with some automated testing for a wikiengine.
- First of all, let’s define a simple service for our wikiengine. The following
WikiService has a function that looks into a MySQL database and returns
the number of hits for a page as well as the ratio of reads per edit. - Next, we will write some startup code used to run our wikiweb server.
if __name__ == “__main__”:
service = WikiService()
WikiWebApp(service).run()
The startup code creates an instance of WikiService, which in turn creates
an instance of MySqlDataAccess. We create an instance of our main web
application component, WikiWebApp, and start it up, giving it a handle on
our service.
We have not defined WikiWebApp or MySqlDataAccess.
Instead, we will be focusing on the functionality WikiService
provides, and on how to isolate and test it.
Let’s look more closely at testing the code we’ve written. A good test case
would involve exercising statistics. Considering that it uses hits and
edits from MySqlDataAccess, it is directly dependent on connecting to
a live MySQL database. One option for testing would be pre-loading the
database with fixed content. However, the cost of set up and tear down can
quickly scale out of control. If you have multiple developers on your team,
you also don’t want the contention where one developer is setting up while
another is tearing down the same tables. - Since we do not want to continuously setup and tear down live database
tables, we are going to code a stubbed out version of the data access
object instead.
class StubDataAccess(object):
def hits(self):
return 10.0
def edits(self, page_name):
return 2.0
Notice how our stub version returns canned values that are
easy to test against.
- Now let’s write a test case that exercises our WikiService. In order to replace
the data_access attribute with a test double, the test case must directly
override the attribute.
class WikiService(object):
def __init_(self):
self.data_access = MySqlDataAccess()
def statistics(self, page_name):
“”"Return tuple containg (num hits, hits per edit)”"”
hits = self.data_access.hits(page_name)
return (hits, hits / len(self.data_access.edits(page_name)))
In this situation, WikiService directly defines data_access to use
MySqlDataAccess. The statistics method calls into MySqlDataAccess to
fetch some information, and returns a tuple containing the number of hits
against the page as well as the ratio of reads per edit.
It is important to point out that our current version of
WikiService has a strong dependency on MySQL as implied
by directly creating an instance of MySqlDataAccess.
class WikiServiceTestCase(unittest.TestCase):
def testHittingWikiService(self):
service = WikiService()
service.data_access = StubDataAccess()
results = service.statistics(“stub page”)
self.assertEquals(10.0, results[0])
self.assertEquals(5.0, results[1])
This solution nicely removes the need to deal with the MySQL database by plugging
in a stubbed out version of our data access layer. These dependencies are depicted in
the following diagram.

WikiServiceTestCase depends on WikiService and StubDataAccess, as well
as an inherited dependency to MySqlDataAccess. Any change to any of these
dependencies could impact our test code.
If we build a huge test suite involving hundreds of test methods, all using this
pattern of instantiating WikiService and then overriding data_access with a test
double, we have set ourselves up with a big risk. For example, WikiService or
StubDataAccess could have some new initializing arguments added. If we later
need to change something about this pattern of creating our testable WikiService,
we may have to update every test method! We would need to make every change
right. This is where Spring Python’s Inversion of Control can help.
More about Inversion of Control
Before diving into our solution, let’s look a little deeper into the meaning of Inversion
of Control.
Inversion of Control is a paradigm where we alter the way we create objects. In
simple object creation scenarios, if we have modules X and Y, and X needs an
instance of Y, we would let X directly create it. This introduces a direct dependency
between X and Y, as shown in the following diagram.

It ‘s dependent because any changes to Y may impact X and incur required updates.
This dependency isn’t just between X and Y. X is now dependent on Y and all of Y’s
dependencies (as shown below). Any updates to Y or any of its dependencies run the
risk of impacting X.

With Inversion of Control, we break this potential risk of impacts from Y and its
dependencies to X by delegating creation of instances of Y to a separate container,
as shown below.

This shifts the dependency between X and Y over to the container, reducing
the coupling.
It’s important to note that the dependency hasn’t been entirely eliminated.
Because X is still given an instance of Y, there is still some dependency
on its API, but the fact that Y and none of its dependencies have to be
imported into X makes X a smaller, more manageable block of code.
We saw in our wikiengine code how WikiService was dependent on
MySqlDataAccess. MySqlDataAccess is dependent on MySQLdb, a python library
for communicating with MySQL. Using the container and coding against a well
defined interface opens up the opportunity to change what version of data access
is being injected into WikiService.
As we continue our example in the next section, we’ll see how IoC can help us make
management of test code easier, reducing long term maintenance costs.






September 8, 2010
Spring Framework