Por mi, recomendaria crear un modulo python, y utilizar un orm para la interaccion con la base de datos
Ejemplo creando el modulo 'xip.mod':
x-ip@darkstar:~$ mkdir tutorial
x-ip@darkstar:~$ cd tutorial/
x-ip@darkstar:~/tutorial$ mkdir xip.mod
x-ip@darkstar:~/tutorial$ touch xip.mod/setup.py
x-ip@darkstar:~/tutorial$ mkdir -p xip.mod/xip/mod
x-ip@darkstar:~/tutorial$ touch xip.mod/xip/__init__.py
x-ip@darkstar:~/tutorial$ touch xip.mod/xip/mod/__init__.py
Luego seteo el setup.py:
from setuptools import setup, find_packages
import sys, os
version = '0.1'
setup(name='xip.mod',
version=version,
description="modulo basico de ejemplo",
long_description="""\
xip.mod""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='lain aka x-ip',
author_email='',
url='',
license='',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",
)
podes comprobar de que tu modulo se puede importar, usando ipython de
la siguiente forma:
In [1]: import sys
In [2]: pwd
Out[2]: '/home/x-ip/tutorial'
In [3]: ls
xip.mod/
In [4]: cd xip.mod/
/home/x-ip/tutorial/xip.mod
In [5]: __import__('xip.mod')
Out[5]: <module 'xip' from 'xip/__init__.pyc'>
In [6]: 'xip.mod' in sys.modules
Out[6]: True
Luego falta escribir una clase para agrupar las funciones relacionadas con la DB, como
recomende usar un orm (object relation mapper), mi preferido es sqlalchemy. Creo un
archivo 'database.py' dentro de mi modulo:
x-ip@darkstar:~/tutorial$ touch xip.mod/xip/mod/database.py
Cual su codigo podria ser por ejemplo:
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy import orm
from sqlalchemy.orm import sessionmaker
class Database(object):
'''DatabaseConnection se encarga de gestionar la conexion
contra la base de datos, utilizando sqlalchemy como orm.
'''
def get_engine(self, **kws):
'''PARAMS **kws: Diccionario que setea los datos de conexión a la DB.
El metodo retorna un objeto de tipo Engine
'''
engine = ('%s://%s:%s@%s/%s' % (kws.get('engine'),
kws.get('user'),
kws.get('passwd'),
kws.get('host'),
kws.get('dbname'))
)
return create_engine(engine)
def bind_session(self, engine):
'''
PARAMS engine. Es un objeto de tipo Engine.
Retorna un obj. de tipo Session que luego debe ser instanciado
localmente.
Como dice en:
http://www.sqlalchemy.org/docs/session.html#what-does-the-session-do
You typically invoke Session() when you first need to talk to your
database, and want to save some objects or load some existing ones.
Then, you work with it, save your changes, and then dispose of it....or
at the very least close() it.
'''
return sessionmaker(bind=engine)
Luego, podes probar que tu database.py se puede importar nuevamente utilizando
ipython asi:
In [1]: __import__('xip.mod')
Out[1]: <module 'xip' from 'xip/__init__.pyc'>
In [2]: from xip.mod import database
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
/home/x-ip/tutorial/xip.mod/<ipython console> in <module>()
/home/x-ip/tutorial/xip.mod/xip/mod/database.py in <module>()
2 from sqlalchemy import MetaData
3 from sqlalchemy import orm
4 from sqlalchemy.orm import sessionmaker
5
6
ImportError: No module named sqlalchemy
Me tira error por no tener instalado sqlalchemy, pues lo instalamos
x-ip@darkstar:~/tutorial/xip.mod$ easy_install sqlalchemy
/usr/lib/python2.6/site-packages/Pyrex/Compiler/Errors.py:17: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message
Searching for sqlalchemy
Reading http://pypi.python.org/simple/sqlalchemy/
Reading http://www.sqlalchemy.org
Best match: SQLAlchemy 0.6.2
.....
Vuelvo a intentar ...
In [1]: pwd
Out[1]: '/home/x-ip/tutorial/xip.mod'
In [2]: __import__('xip.mod')
Out[2]: <module 'xip' from 'xip/__init__.pyc'>
In [3]: from xip.mod import database
Y ahora si funciona
. Luego para reutilizar tu modulo python, es cuestion de
empaquetarlo en un 'egg'.
(plone4)x-ip@darkstar:~/tutorial/xip.mod$ python setup.py bdist_egg
/usr/lib/python2.6/site-packages/Pyrex/Compiler/Errors.py:17: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message
running bdist_egg
running egg_info
creating xip.mod.egg-info
....
Tu codigo empaquetado se va a encontrar en el directorio 'dist', te muestro mi shell asi
se entiende:
(plone4)x-ip@darkstar:~/tutorial/xip.mod$ ls dist/
xip.mod-0.1-py2.6.egg
Este paquete xip.mod ahora lo podes pasar a todos tus amigos o vos instalarlo de manera
sencilla en donde lo precises, haciendo:
x-ip@darkstar:~/tutorial/xip.mod/dist$ easy_install xip.mod-0.1-py2.6.egg
/usr/lib/python2.6/site-packages/Pyrex/Compiler/Errors.py:17: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message
Processing xip.mod-0.1-py2.6.egg
creating /home/x-ip/envs/plone4/lib/python2.6/site-packages/xip.mod-0.1-py2.6.egg
Extracting xip.mod-0.1-py2.6.egg to /home/x-ip/envs/plone4/lib/python2.6/site-packages
Adding xip.mod 0.1 to easy-install.pth file
Installed /home/x-ip/envs/plone4/lib/python2.6/site-packages/xip.mod-0.1-py2.6.egg
Processing dependencies for xip.mod==0.1
Finished processing dependencies for xip.mod==0.1
Al haberlo instalado, ya no es necesario que hagas __import__('...'), si abris tu interprete
de python o ipython veras:
(plone4)x-ip@darkstar:~/tutorial/xip.mod/dist$ ipytho
-bash: ipytho: command not found
(plone4)x-ip@darkstar:~/tutorial/xip.mod/dist$ ipython
Python 2.6.2 (r262:71600, Jun 9 2009, 17:15:39)
Type "copyright", "credits" or "license" for more information.
IPython 0.10 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [1]: from xip.mod import database
In [2]:
Saludos