Showing posts with label SQLAlchemy. Show all posts
Showing posts with label SQLAlchemy. Show all posts

Tuesday, December 30, 2014

pyDAL, a pure Python Database Abstraction Layer

By Vasudev Ram


pyDAL is a pure Python Database Abstraction Layer. So it seems to be something like the lower layer of SQLAlchemy, i.e. SQLAlchemy Core, the library that is used by the upper layer, SQLAlchemy ORM. See the SQLAlchemy (0.8) documentation.

From the pyDAL site:

[ It dynamically generates the SQL in real time using the specified dialect for the database back end, so that you do not have to write SQL code or learn different SQL dialects (the term SQL is used generically), and your code will be portable among different types of databases.

pyDAL comes from the original web2py's DAL, with the aim of being wide-compatible. pyDAL doesn't require web2py and can be used in any Python context. ]

IOW, pyDAL has been separated out into a different project from web2py, a Python web framework, of which it was originally a part.

The use of an ORM (Object Relational Mapper) vs. writing plain SQL code (vs. using an intermediate option like pyDAL or SQLAlchemy Core), can be controversial; there are at least some pros and cons on both (or all 3) sides. I've read some about this, and have got some experience with using some of these options in different projects, but am not an expert on which is the best approach, and also, it can vary depending on your project's needs, so I'm not getting into that topic in this post.

pyDAL seems to support many popular databases, mostly SQL ones, but also a NoSQL one or two, and even IMAP. Here is a list, from the site: SQLite, PostgreSQL, MySQL, Oracle, MSSQL, FireBird, DB2, Informix, Ingres, Cubrid, Sybase, Teradata, SAPDB, MongoDB, IMAP.

For some of those databases, it uses PyMySQL, pyodbc or fbd, which are all Python database libraries that I had blogged about earlier.

I tried out pyDAL a little, with this simple program, adapted from its documentation:

import sys
import time
from pydal import DAL, Field
db = DAL('sqlite://storage.db')
db.define_table('product', Field('name'))
t1 = time.time()
num_rows = int(sys.argv[1])
for product_number in range(num_rows):
    db.product.insert(name='Product-'.format(str(product_number).zfill(4)))
t2 = time.time()
print "time to insert {} rows = {} seconds".format(num_rows, int(t2 - t1))
query = db.product.name
t1 = time.time()
rows = db(query).select()
for idx, row in enumerate(rows):
    #print idx, row.name
    pass
t2 = time.time()
print "time to select {} rows = {} seconds".format(num_rows, int(t2 - t1))

It worked, and gave this output:

$ python test_pydal2.py 100000
No handlers could be found for logger "web2py"
time to insert 100000 rows = 18 seconds
time to select 100000 rows = 7 seconds

Note: I first ran it with this statement uncommented:
#print idx, row.name
to confirm that it did select the records, and then commented it and replaced it with "pass" in order to time the select without the overhead of displaying the records to the screen.

I'll check out pyDAL some more, for other commonly needed database operations, and may write about it here.
There may be a way to disable that message about a logger.

The timing statements in the code and the time output can be ignored for now, since they are not meaningful without doing a comparison against the same operations done without pyDAL (i.e. just using SQL from Python with the DB API). I will do a comparison later on and blog about it if anything interesting is found.

- Vasudev Ram - Dancing Bison Enterprises - Python training and consulting

Signup to hear about new products or services from me.

Contact Page

Tuesday, August 20, 2013

Publish SQLAlchemy data to PDF with xtopdf


By Vasudev Ram

SQLAlchemyToPDF is a demo program that shows how to publish your database data via SQLAlchemy to PDF.



SQLAlchemy is a popular and widely used database toolkit for Python. It includes both a Core, which consists of a sort of DSL (Domain-Specific Language) for SQL, written in Python, and an ORM (Object Relational Mapper) which is built on top of the Core.

SQLAlchemyToPDF, after some improvement, will become a part of my xtopdf toolkit for PDF creation. It will be released under the BSD license, like the rest of xtopdf.

Using the technique shown below (with appropriate modifications), you can publish data, from any of the major databases that SQLAlchemy supports, to PDF. And you can do this using the high-level interface provided by SQLAlchemy's ORM, which means code that is shorter and easier to write.

However, SQLAlchemy also provides you the ability to go to a lower level when needed, to access more of the power of SQL or of a specific database.

Here is the code for SQLAlchemyToPDF.py:
# SQLAlchemyToPDF.py
# Program to read database data via SQLAlchemy 
# and publish it to PDF. This is a demo.
# Author: Vasudev Ram - http://www.dancingbison.com
# Copyright 2013 Vasudev Ram
# Version 0.1

from PDFWriter import PDFWriter
from sqlalchemy import create_engine

engine = create_engine('sqlite:///:memory:', echo=False)

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

from sqlalchemy import Column, Integer, String

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    email = Column(String)

    def __init__(self, name, fullname, email):
        self.name = name
        self.fullname = fullname
        self.email = email

Base.metadata.create_all(engine) 

a_user = User('A', 'A 1', '[email protected]')
b_user = User('B', 'B 2', '[email protected]')
c_user = User('C', 'C 3', '[email protected]')

from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)

session = Session()

for user in (a_user, b_user, c_user):
    session.add(user)

pw = PDFWriter('users.pdf')
pw.setFont("Courier", 12)
pw.setHeader("SQLAlchemyToPDF - User table report")
pw.setFooter("Generated by xtopdf using Reportlab and Python")

users = session.query(User)
for user in users:
    pw.writeLine(user.name + "|" + user.fullname + "|" + user.email)

pw.savePage()
pw.close()


I used an in-memory SQLite database to keep the code simple. Refer to the SQLAlchemy documentation for how to connect to other databases.

And here is a screenshot of the resulting PDF output:


Read other xtopdf posts on jugad2

Read other python posts on jugad2

- Vasudev Ram - Dancing Bison Enterprises

Contact me

Thursday, August 15, 2013

Free Webinar - Intro to OpenStack - by the Linux Foundation


By Vasudev Ram

I saw this news via the Linux Foundation's email newsletter.

The Linux Foundation is hosting a free webinar, Introduction to OpenStack Cloud.

OpenStack is FOSS (Free and Open Source Software) for deploying public and private clouds. NASA and Rackspace were among the original developers of OpenStack. In a short few years, OpenStack has become what may be the largest open source project after Linux (as I've heard it said).

OpenStack

OpenStack on Wikipedia

About the Linux Foundation

The Linux Foundation sponsors the work of Linus Torvalds, the original creator of Linux:

Linux Foundation staff

(I originally made a typo in the name of Linus above, wrote Linux :) Sorry, readers via Planet Python. Though I corrected it soon, it was already included in the feed. On the other hand, it might not be a bad moniker for him, considering what he's achieved :), along with countless others, of course.

Excerpt from the newsletter about the free OpenStack webinar:

[
Cloud Computing has taken the IT world by storm over the last few years. Advances in virtualization technology have made it possible to not only make much more efficient use of available hardware, but to offer it with previously unheard-of levels of flexibility. Furthermore, sysadmins and devops need not reinvent the wheel when deploying a cloud: a vibrant ecosystem has grown from the need for quality free and open-source tools to build such an infrastructure.

Due to the organized structure of OpenStack, rapid development, and flexible components, in just over three years, it has risen in the F/OSS community as the platform of choice for private and public cloud deployments. In this webinar, Adolfo Brandes, an OpenStack technical consultant for hastexo, will give an overview of why that is, including:

An overview of OpenStack and its components
A live demonstration of an OpenStack Cloud
Best practices on how to do a first deployment
]

Here are the webinar details:

Date: Wednesday, August 28th, 2013
Time: 9am Pacific / Noon Eastern / 1800 CEST

OpenStack is written in Python, and uses SQLAlchemy for database access.

SQLAlchemy is a database toolkit for Python, which provides both a "Core" Pythonic interface to the generic as well as specific capabilities of various relational databases, and also a higher-level ORM (Object Relational Mapper) built upon the Core.

Here is a video of Mike Bayer's Introduction to SQLAlchemy presented at the last PyCon 2013 in the US:



The list of members of the Linux Foundation is large, and colorful :) due to all the corporate logos.

Linux posts on jugad2

- Vasudev Ram - Dancing Bison Enterprises

Contact me

Monday, February 25, 2013

codepad.org, executable multi-language pastebin, in Python

about - codepad

codepad - http://codepad.org - is an online pastebin. It lets you enter your code, written in Python or one of some other popular languages, into a text box. You then click a button on the page to run the code. Codepad shows the output from the run.

You don't have to register on the site to edit and run code, only to save code. You also get a unique URL for your code, which you can share via chat, email or on your web site or blog.

I tried out Codepad with a simple Python function  definition and two calls to it. It worked:

http://codepad.org/dkAfNoF8

The Codepad site is written in Python using the Pylons web framework and the SQLAlchemy ORM, and some other techniques such as a supervisor and virtual machines, which are of interest too, IMO.

http://pylonshq.com/

http://www.sqlalchemy.org/

Steven Hazel is the creator of Codepad, and also founder of Sauce Labs, a Selenium testing company.

https://saucelabs.com/

http://en.m.wikipedia.org/wiki/Selenium_(software)

http://docs.seleniumhq.org/

- Vasudev
dancingbison.com

Friday, October 26, 2012

Akiban, new database, supported by SQLAlchemy


By Vasudev Ram

Akiban is a new type of database, with what may be some interesting features.

Seen via the Planet Python Twitter account, specifically, via this tweet:

It's the author of SQLAlchemy, Michael Bayer, talking about starting to provide SQLAlchemy support for Akiban.

The Akiban team seems accomplished. Akiban, the company, is based in Boston.

P.S. I was interested to see that one of the Akiban team members, Jack Orenstein, was a founder/architect at Archivas, which was later acquired by Hitachi Data Systems. I had read about Archivas some years ago; they created a kind of archival system for large amounts of data, with fast retrieval times. They used Python as one of their development tools. Archivas was also based in Boston.

P.P.S. Jack Orenstein of Akiban (and Archivas), referred to above, made a comment on this post. Check it out below. Pretty interesting info ...

Incidentally, I learnt from his comment that Jack is also the creator of Osh, the Object Shell, which was one of the tools I blogged about in my first post on some ways of doing UNIX-style pipes in Python. And seeing those tools is what inspired me to later create pipe_controller. Talk about serendipity ... :-)


- Vasudev Ram - Dancing Bison Enterprises