Intro To Spring Python

download Intro To Spring Python

If you can't read please download the document

Transcript of Intro To Spring Python

Example Title of the Presentation

Introduction to
Spring Python

Greg L. TurnquistSenior Software EngineerSpringSource

Adapted from presentation given at SpringOne 2008

What should you take away from this?

Spring Python gives you the tools to build dynamic, powerful, easy-to-maintain enterprise solutions

Who Am I?

A test-bitten script junky, always seeking better solutions for customer requirements

Worked as a software engineer for 11 years at Harris Corporation after graduating Auburn University with Master's in Computer Engineering. Joined SpringSource in 2010.

Have built mission critical systems, trained on-call support teams, evangelized usage of wikis, and utilized Agile practices to write top quality software

Active contributor to open source community: MythTV, Mediawiki, Spring Framework/Acegi, TestNG Eclipse plug-in

Find me at http://www.linkedin.com/in/GregLTurnquist

Who Am I?

Wrote Spring Python 1.1

Find detailed diagrams, lots of code examples, and information on how to build powerful Python applications using the Spring way.

http://springpythonbook.com

The Spring Framework provides many useful features, and I wanted those same features available in Python.

Agenda

History

Technology

IoC container

Database template

Transactions

Security

AOP

Remoting

Status

Current

Future of the project

When/where did it come from?

In October 2006 came the carputer

Needed utility of Spring with power of Python

In December 2006, made first release to Sourceforge

In July 2008, Russ Miles (SpringSource) invited Spring Python to be a Spring Extension

In June 2009, started writing Python 1.1 book

Becoming an extension

Since then:

Migrated code to Spring's subversion servers, and later to git

Worked with build team to setup Continuous Integration

Copied all tickets into JIRA (open and closed)

Setup Spring Python community forum, blog, and irc channel (#springpython)

Made 750+ commits; released versions 0.6-0.9, 1.0, and 1.1; closed 109 issues

Brought on board two more committers

Currently interacting w/many devs and users about future of Spring Python including roadmap for 1.2 and beyond

Agenda

History

Technology

IoC container

Database template

Transactions

Security

AOP

Remoting

Status

Current

Future of the project

We have the same concepts as Spring

SimpleObject

SimpleObject

Dependency Injection

AOP

Portable Service Abstractions

Multiple IoC formats supported

Started with an XML-based configuration

Later, a python decorator-based configuration

Recently rewrote IoC container, handles:

Original format (now called PyContainerConfig)

Newer, more sophisticated XML format (XMLConfig)

Spring Java's format (SpringJavaConfig)

Decorator-based @Object format (PythonConfig)

YAML-based format (YamlConfig)

New container can mix ANYTHING

Allows multiple sources in multiple formats

Objects can reference ANY other object

...no matter WHERE its defined

...and no matter WHAT format its defined in

Flexible IoC container + dynamic Python = High Value

Pure Python IoC

@Object-based configuration

class MovieBasedConfig(PythonConfig):

def __init__(self):

super(MovieBasedConfig, self).__init__()

@Object(scope.PROTOTYPE)def MovieLister(self):

lister = MovieLister()lister.finder = self.MovieFinder()lister.description = self.SingletonString()return lister

@Object(scope.SINGLETON)def MovieFinder(self):

return ColonMovieFinder(filename="support/movies1.txt")

Compare with Spring's IoC

Similar concepts found in Spring

Java = beans, Python = objects

@Object is like @Bean

Current scopes: SINGLETON and PROTOTYPE

FUTURE: Lazy initialization, auto-wiring

Newer concepts not yet found in Spring

One-and-only-one container type

FUTURE: Fluent API (DSL) configuration

Question

What database problem does Python have?

Answer

The Magic 8 says:
Same problem Java JDBC has!

Python's database issue

For every query:

Only difference between every query is SQL and row conversion

// open connection to database// create cursor// execute SQL query// for eachRow in resultSet

// convert row into an object

// close cursor// close connection

Why create DatabaseTemplate?

Spring's JdbcTemplate helped me write database queries fast in Java

Python apps have the same problem and need the same leverage

DatabaseTemplate should be reason enough for potential users to embrace Spring Python

ORMs and DatabaseTemplate

They provide quick way to persist objects.

But sometimes they are tricky for complex queries. What if...You need left outer joins that lack foreign key meta-data

You actually know what a left outer join is and don't need help

You are porting from ORM to another

You have a DBA team that can optimize your queries

How to code a query

Piece of PetClinic:

Use binding variables (?) to avoid SQL injection attacks

Each row of results is passed to callback

Notice lack of cursor management?

return databaseTemplate.query("""

SELECT id, first_name, last_name, address, city, telephoneFROM ownersWHERE upper(last_name) like ?""",("%" + lastName.upper() + "%",),OwnerRowMapper())

Immediate payoff

Benefits:

No cursors to manage

No ugly try/except blocks

Focus is on business logic

Query will work with any RDBMS*MySQL, Sqlite, PostGreSQL, Oracle

(*Okay, DB vendors can support different forms of binding variables, but we are ready for that!)

How to code a row mapper

The other side:

Very useful when you have to code a lot of Owner-based queries

class OwnerMapper(RowMapper):

def map_row(self, row):

owner = Owner()owner.id = row[0]owner.firstName = row[1]owner.lastName = row[2]owner.address = row[3]owner.city = row[4]owner.telephone = row[5]return owner

Question

Have you ever had to deal with transactions?

Transactions power the enterprise

Database calls are valuable for any app, small or large

Transactions power enterprise solutions

Coding transactions is one of the first demands for enterprise apps

How to code transactions

Spring Python makes it easy to programmatically code transactions

tx_mgr = ConnectionFactoryTransactionManager(factory)tx_template = TransactionTemplate(tx_mgr)dt = DatabaseTemplate(factory)

class txDefinition(TransactionCallback):

def do_in_transaction(s, status):

dt.execute("INSERT INTO animal (name) VALUES (?)",('black mamba',))dt.execute("INSERT INTO animal (name) VALUES (?)",('copperhead',))results = dt.queryForObject("SELECT nameFROM animal WHERE name like 'c%'", required_type=types.StringType)return results

print tx_template.execute(txDefinition())

>>> "copperhead"

Declarative transactions are key

TransactionTemplate is useful for a handful of transactions

However, marking business methods with @transactional catapults you into the enterprise

Decouples business logic from the database

How to declare transactions

class TransactionalBank(object): def __init__(self, factory): self.dt = DatabaseTemplate(factory)

@transactional(["PROPAGATION_REQUIRED"]) def deposit(self, amount, account_num): self.dt.execute("UPDATE account SET balance = balance + ? WHERE account_num = ?", (amount, account_num))

@transactional(["PROPAGATION_REQUIRED"]) def withdraw(self, amount, account_num): self.dt.execute("UPDATE account SET balance = balance - ? WHERE account_num = ?", (amount, account_num)) return amount

@transactional(["PROPAGATION_REQUIRED"]) def transfer(self, amount, from_account_num, to_account_num): self.withdraw(amount, from_account_num) self.deposit(amount, to_account_num)

Code is clean and easy to read

Declarative transactions move configuration to a central location

Your logic is clean, concise, and clear to its purpose

Enterprise apps tend to get HUGE, so maintainable code is paramount to success

Spring Python's declarative transactions are EXACTLY what you need

Spring Python 1.1 shows you the pros and cons of programmatic vs. declarative vs. AOP-based transactions.

Question

At what stage do developers code security into their apps?

Answer

HINT: Its usually not the first thing on your mind

Security done right is hard

Security is a big flaw in modern web apps

Security is typically done last and thus, often rushed

Rushed implementation = WRONG solution

Spring Python's security is the RIGHT solution

Authentication made easy

Authenticating a user is EASY

Uses AOP so your APIs don't change

Familiar with Spring Security? We borrowed their concepts.

Makes Spring Python powerful!

TODAY: In-memory (for testing), database, LDAP

FUTURE: X.509, OpenID, OpenSSO, Basic HTTP, 2-factor, anything!

Authorization also easy

Authorizing users is also easy

Spring Python is just as powerful

TODAY:

Role-based and/or Label-based voters+Affirmative- or Unanimous- or Consensus-based policies= Powerful, flexible, elegant configuration

FUTURE:

read-write-execute ACL voters for domain object security

Anything the community needs!

Question

What technology makes it easy to layer on services without changing APIs?

Answer

Survey says:

Aspect Oriented Programming

Spring makes AOP easy

Spring AOP = easy AOP for Java

Spring Python AOP = easy AOP for Python

Allows enterprise-style services to be easily built around your objects

Security, transactions, auditing, tracing, performance analysis

Many parts of Spring Python ride on AOP

AOP is part of the Spring triangle

SimpleObject

SimpleObject

Dependency Injection

AOP

Portable Service Abstractions

AOP, easy as 1-2-3

class SampleService: def method(self, data): return "You sent me '%s'" % data

service = SampleService()print service.method("something")

>>> "You sent me 'something'"

class WrappingSvc(MethodInterceptor): def invoke(self, invocation): return "" + invocation.proceed() + ""

service = ProxyFactoryObject(target = SampleService(), interceptors = [WrappingSvc()])print service.method("something")

>>> "You sent me 'something'"

Question

What can you do to make apps redundant and support more clients?

Answer

The answer behind door #3 is:

Spread your app across multiple nodes

Remoting links things together

Remoting is the building block for distributed systems

It allows you to split up apps that need more resources

Horizontal scaling allows you to grow your enterprise

Spring Python allows you to easily supply and consume remote services

Pyro today, REST & WS tomorrow

Today:

Pyro (Python remote objects) pure python RPC library

Hessian interoperable protocol

JMS link Python-to-Python or Python-to-Java with WebshereMQ

Tomorrow:

RESTful web services

COMET-enabled web apps

Twitter

Any web service, or other useful remoting protocol

Other JMS providers

Agenda

History

Technology

IoC container

Database template

Transactions

Security

AOP

Remoting

Status

Current

Future of the project

Top quality, production-ready

Just released 1.1.0.FINAL. Starting 1.2.

Has ALL key features needed for development

Top quality

Tied in to CI: nightly builds and trunk commits

Built from Day 1 using TDD => Code coverage at 85%

Powerful integration

CherryPy, Pyro, Hessian, MySQL, PostGreSQL, Sqlite, Oracle

Documentation is up-to-date and useful

Community support is important

Solutions

What solutions do python users need?

What 3rd party libraries can be enhanced or leveraged to provide integrated solutions?

Community

Striving to answer any/all questions posted to the forums

Provide fast support to email distribution list

Grow the community of users

Spring Python has a strong future

Quality is always #1 priority

Integrating with top-used tools is important

Django, Turbogears, Zope/Plone, Paste, Google App Engine, SpringSource Tool Suite, Jython, IronPython

Books, podcasts, slide shows, video tutorials, anything to support the community

Spring + Python = powerful solutions

Spring Python provides powerful, dynamic, and easy-to-maintain enterprise solutions

Useful project links

Web site: http://springpython.webfactional.com

Book: http://springpythonbook.com

Blog: http://blog.springpython.webfactional.com

Community forum: http://forum.springframework.org

Source code: https://src.springframework.org/svn/se-springpython-py/

Bug tracking: http://jira.springframework.org/browse/SESPRINGPYTHONPY

Mailing list: http://lists.springsource.com/listmanager/listinfo/springpython-users

CI: http://build.springframework.org/browse/EXT-PYSNAPSHOT

Fisheye: https://fisheye.springframework.org/browse/se-springpython-py

Thank you
for your attention

Slide

Slideshow is licensed under a Creative Commons Attribution 3.0 United States License.