Managing a simple database with Python, SQLite and wxPython, 3

Phase 2 3 Comments »

In the last post we saw how to connect to a SQLite database file and generate a cursor that would allow us to actually interact with such database. Now we need some functionality that will interact with the data, add, read, delete and search. As was mentioned before the idea is to have a generic database interaction class and have unique instantiated class objects for each database of the project. In the db_obj.py file we have an initial structure set, so let’s check the DB_Generic class.

class DB_Generic():
    '''generic class to add DB functionality'''
    def __init__(self, table_name):
        #par= name of the table to be used
        self.table_name = table_name

    def delete_entry(self):
        pass

    def get_data_generic(self):
        '''gets the data from the database
        generic so far, needs to be updated to include range'''        

        range = 1
        (cursor, database) = link_db()

        if range == 1:
            cursor.execute("""SELECT * from %s""" % self.table_name)

        table_data = cursor.fetchall()
        raw_data = []
        for i in table_data:
            raw_data.append(list(i))

        self.table_data = raw_data

        database.close()

    def insert_data(self, values_list, insert_string):
        '''inserts data in the database'''

        (cursor, database) = link_db()
        cursor.execute(insert_string % self.table_name, values_list)

        database.commit()
        database.close()

There are different functions in this class, we will take a look at each one individually. We can see that the class is far from being complete, something that we’ll do in the next posts. We start with the class initialization:

def __init__(self, table_name):
        #par= name of the table to be used
        self.table_name = table_name

Very simple and direct, it receives the table name that is being used by the interface (in this case). The table name is then stored in a object that can be accessed by other functions in the class. The function to delete entries is not finished as we only have a pass in it. We’ll will do it soon. Next we have a function that gets the data from the table.

    def get_data_generic(self):
        '''gets the data from the database
        generic so far, needs to be updated to include range'''        

        range = 1
        (cursor, database) = link_db()

        if range == 1:
            cursor.execute("""SELECT * from %s""" % self.table_name)

        table_data = cursor.fetchall()
        raw_data = []
        for i in table_data:
            raw_data.append(list(i))

        self.table_data = raw_data

        database.close()

So far it grabs everything, there is no range selection based on any of the table fields, so it’s a generic SQL SELECT. Let’s dissect it. The range object is a dummy variable that at the moment is there only to remind us that we need to include a range select. The next line is the most important in this function: it will call the link_db function and start the connection. Remember that link_db returns a tuple with the cursor and database connection. Basically we will work with cursor methods to get the data, and the first action is to execute a SQL SELECT stetement where we select everything in the table

cursor.execute("""SELECT * from %s""" % self.table_name)

Notice that the statement is a regular string and we use string formating % in ordert o add the table that we are searching, which was defined when we initialized the class object in the first place. Also, notice the triple quotes around the select statement: this will avoid any problems in parsing it when sending to the database, making it a string literal.

So this line executes the statement we pass to the method, but it does not actually get the data per se. We need to use another method and fetch everything returned by the select. This is done by

table_data = cursor.fetchall()

A couple of things here. The data fetched will be always (or in most cases) in unicode, when it’s a string field. And the data returned will be in a list of tuples, with the actual number of fields from the table. We know that it’s easier to work with lists than tuples, so we code something to convert types

table_data = cursor.fetchall()
raw_data = []
for i in table_data:
    raw_data.append(list(i))

self.table_data = raw_data

There are extra lines here that are not needed, and we will get rid of them in a code refactoring soon. This short function is able to connect to database, execute a SQL statement on a specified table and grab the data selected, returning a list of lists with every field and value available. We need to add a better selection statement later, and we will do as soon as we have a good structure set.

The last function in this generic class is the one that inserts data into the table.

def insert_data(self, values_list, insert_string):
    '''inserts data in the database'''

    cursor, database) = link_db()

    cursor.execute(insert_string % self.table_name, values_list)

    database.commit()
    database.close()

Identical procedure: connect, get a cursor, execute a statement. But in this case the extra step is not to get the data, but to commit the data to the table, which is done by the commit method. We will explain later how the execute method works here and what are the insert_string and values_list. Notice at the end that we need to close the connection to the database, so we know that the data has been inserted properly.

Next, we will instantiate a class from this generic one and see how easy is to manipulate the data. Stay tuned.

Previously in the series:
Part 1
Part 2

Reblog this post [with Zemanta]

Managing a simple database with Python, SQLite and wxPython, 2

Phase 2 Comments Off

Let’s continue coding our small Python + SQLite application. The initial idea was to have a file for the interface and another file for the DB access. We will start with the later. If you have access to the repository you will see two Python files, bac_form.py and db_obj.py. At the moment they are not well commented and have some junk lines at the bottom, legacy from older versions. Take a look on db_obj.py.

It has two class declarations, one called DB_Generic and another one called Bac. Remember in the last post where I mentioned that the idea was to have different simple tables in the same SQLite database and each table would have a simple input/output interface (If I didn’t mention that, I just did!). So, we can create a generic DB access class and we can subtype from it for every table that we will be using. In the db_obj.py file we have at the moment the generic database management class, a class derived from the generic to access the Bac database and an initialization function, that opens the access to the SQLite file. Let’s take a look at it:

def link_db():
    '''initializes the database file'''
    try:
        db = sqlite3.connect("samples.db")
    except sqlite3.Error, errmsg:
        print 'DB not available ' + str(errmsg)
        sys.exit()

    db_cursor = db.cursor()
    return db_cursor, db

In order to access a SQLite database file we need initially the name of the file. After importing sqlite3 (we’re using the latest version of SQLite here) Python has everything it needs to access, change and manipulate data in a SQLite database. Just to be sure the database file is there and we don’t get an error, we have the initialization code inside an exception. We have seen exceptions before and in this case we use it to be sure the database file has been accessed with no problems. The exception structure looks like

try:
	#here we try to do something
	#the code placed here would be executed
	#if no error reported it will go until the end and exit
	#if not, some error (exception) raised
except:
	#the code under except will be executed

So, the first step is to connect to the database file

db = sqlite3.connect("samples.db")

In our case it’s a fixed file, but the connect method receives any kind of string. It could have been some parameter obtained from the command line or a string from a configuration file. If the connect is successful, no error will be raised and we are safe to continue. We connected to database, now what? We need a cursor, an object that will actually access the data and allow us to execute SQL commands on it.

db_cursor = db.cursor()

cursor method works on the database connection object that we created previously. We’re set. This function returns the cursor and database connection objects that we created, in a tuple and this function can be called from the classes we are going to work. The classes will then have connection to the database and a cursor that would manage, select, delete and add data to it.

Next time we’ll see how our generic table class works.

Previously in the series:
Part 1

Reblog this post [with Zemanta]

Managing a simple database with Python, SQLite and wxPython, 1

Phase 2 17 Comments »
The official wxPython logo
Image via Wikipedia

A little break from reviewing the book, let’s check some database topics in Python. I was asked to create a simple database to organize wet-lab stuff. No relationships needs, no relational tables required. Just a simple table with determined columns, and a nice GUI to go with it so people can edit, search and use.

My first idea was to use SQLite database, and I stuck with it. After the initial phase of “interviews” to check database requirements, I ended up with a list of tables and decided to start working on the table that organizes the BACs used in the lab. BAC is a DNA vector into which large DNA fragments can be inserted and cloned in a bacterial host, and are used mainly in cytogenetics around here. In the end the table had this structure

CREATE TABLE bac
(idbac INTEGER PRIMARY KEY,
clone Text,
sdate Date,
source Text,
gene TEXT,
chromosome Text,
startpos Integer,
endpos Integer,
antibiotic Text,
location1 Text,
temperature Integer,
tubes Integer,
box Integer,
cell Integer,
dnaex Boolean,
validation Boolean,
pcr Boolean,
projects Text,
comments Text,
genelink Text,
refs Text);

I won’t explain in detail each of the fields, but we can see that there is a mix of different types. SQLite doesn’t allow many different field types, so we stick to the basics.

And why SQLite? The module to access it comes with Python 2.5, the whole database is stored in one file that can be moved around and it allows a full SQL query language, which is perfect for these simple cases. So we will going to use Python, SQLite and wxPython to create a simple application to manage our simple database.

I already created a GitHub repository for the upcoming code.

Reblog this post [with Zemanta]

Expert Python Programming by Tarek Ziadé – a review of Chapter 3

off topic 2 Comments »

The chapter 3 review that I promised for “tomorrow” (last Saturday) was lazily postponed until today. So, let’s get to it. Tarek in this chapter continues with syntax best practices, but at this time at class level. As expected the chapter requires that you have a minimal knowledge of Python classes, so I can say it’s geared to somewhat experienced programmers, and not to newcomers. There is a short explanation on sub-classing that warms up things for the next sections.

Next is the built-in method (type?) super, which was new to me. Basically super gives you access a method or attribute of a class by calling its parent directly. This is a segue into understanding the Method Resolution Order in Python, which is understanding which class has precedence over the others. For me, I haven’t dealt with such structures before it was a good and straight explanation, especially when he explains about possible pitfalls of using super. A short list of best practices helps:

  • Multiple inheritance should be avoided:
  • super usage has to be consistent: Mixing super and classic calls is a confusing practice.
  • Don’t mix old-style and new-style classes
  • Class hierarchy has to be looked over when a parent class is called

After dealing with MRO, comes what I think is one of the best sections of the book so far, where Tarek explains about object descriptors and gives a little bit of the Python’s approach to introspection. This short section is basically all code, but it’s good to have a good best practices reference, including here properties and slots.

The last part of the chapter covers meta programming, and as Chris pointed in the comments, that’s a difficult area of Python (maybe for the ones like me that don’t have a CS formation). I would have to try the examples by hand and maybe define areas in my code where I can use it, so to take fully advantage and fully understand it.

Overall, the chapter gives a good series of topics about Python classes and I enjoyed learning a little bit more things that I couldn’t understand previously. Next we will see a review of chapter 4, that deals with PEP 8 and naming best practices.

Expert Python Programming by Tarek Ziadé – a review of Chapter 2

off topic 2 Comments »

So we’re up to the second chapter of Tarek’s book. A short disclaimer before diving into it. I started this blog, basically one year after I had started programming with Python. The initial idea was to “convert” the Beginning Perl for Bioinformatics book to Python and see what were the advantages and disadvantages of both languages. I was far from being a advanced Python programmer, and the inception of the blog helped me getting close to that, even though I consider myself far from being an expert programmer in Python. I learned a lot working on converting the Perl and learned a lot from the comments and interaction with other programmers and visitors of the blog. As anything in life one’s path is long and tortuous and there’s nothing better than daily learning and exercise.

So, as I mentioned in the previous post, this book was tailored for someone like me. I needed a boost on advanced Python techniques and the second chapter just gave me that. Tarek writes in this chapter about good syntax practices below the class level, functions and methods that are common in daily usage. He starts with list comprehensions, that we have seen in this site. It’s a short and concise section and gives you exactly what you need about this functionality.

Next, iterators and generators. I had a little bit of background on iterators, and have used them here and there, but not a lot on generators. I learned a bit from this section, what you expect from a book like this, things like the close and throw. Although this was good first step on generators, I wished the section could be longer, but that maybe not the focus of the book.

Coroutines was a completely new subject for me. Maybe I haven’t been diving into Python as much as I needed to, but time is short these days and programming Python is not the first objective of my work. The example is complete and easy to understand, but again I wish it was a tad bit longer. Tarek then explains a bit of generator expressions (list comprehension for generators) and enters the itertools module. So far so good, it’s a nice summary (at least for me) of simple techniques that can be incorporated into daily coding. And then … Decorators.

I blame on my poor CS skills or maybe my whole background on programming, but I still cannot get decorators. In my short-sighted view of the programming world I cannot see a place, at least on the things I’m doing, where I can use a decorator. And here comes the first criticism of the book: I still cannot get after reading the section. One thing that would help a bit would be to have colours on the examples and maybe go over them explaining some code lines. But at the same time, I admit that this might be a personal problem, where the concept of decorators don’t fit into my brain, and maybe the focus of the book is to show this advanced technique to someone that has a better grasp of the concept.

Overall, it’s a very good chapter and a good pointer to some expert/advanced techniques in Python. Tomorrow, chapter 3, and we’re a going to see classes.

Reblog this post [with Zemanta]

Expert Python Programming by Tarek Ziadé – a review of Chapter 1

off topic Comments Off

I’ve bought (no, Packt Publishing didn’t send me a copy for review) Tarek’s book quite sometime ago, but job changes, and extra-Python issues kept me away from reading it with the attention if fully deserve. When I saw the announcement, I thought that this was the book I wanted in Python. First, a little bit of perspective.

I’m a a biologist, self-taught programmer/coder/you-name-it. I only had a brief course on programming logic with Pascal in 1993 (I think). I first learned Basic on Apple ][, then on PC, then moved to Visual Basic, Pascal, C and C++, most of them with the help of books. About three and a half years ago, I got tired of compiling things and decided to learn a different language that would be more agile to code with. Not liking Perl, made me check Python. And I got hooked. Of course as a lay programmer, I won’t discuss why it’s better or worse than any other language using technical terms, but I can say that Python fits my needs in fast and efficient programming and I’m quite happy with the choice I’ve made. So, this review will not be technical, but will try to expose the book’s strengths and the weak parts.

Chapter one gives a good introduction on how to install Python and some nice pointers on how to program Python, such as IDEs and initial settings you can add to it. Also there is a short overview of the modern Python implementations. Is it a necessary chapter? Yes and no. No, because the schooled Python user won’t need it, his or her programming environment will already be installed, configured, set and ready to go. Yes, because this chapter works as a disclaimer for the not-so-experienced Python programmer, and shows everyone of what is expected of this book and what standards will be used. In my opinion, it’s a necessary starting point, so the author knows that everyone is at the same level. This chapter is also a good short summary of good practices of installing and setting up Python.

Tomorrow, chapter 2.

BPforB is now PEP 8 compliant!

Phase 2 Comments Off

As mentioned in the previous post, Robin Stocker kindly provided a git patch with the required changes to all scripts stored on the repository to be compliant with the PEP 8.

The changes were mainly regarding variable/object names, but they were important as make the code available here more Pythonic following the rules of the Benevolent Dictator for Life.

I would like to thank Robin for spending his time doing this. Much appreciated.

Now, just a quick git tutorial on how to apply patches:

git apply __patch_file__
git commit -a -m “patch applied”
git push

That’s it. Apply, commit, push and you’re done. The repository is already updated.

Finally it’s 2009 …

Phase 2 Comments Off
Python logo, 1990s-2005
Image via Wikipedia

And … we’re back. The long and cold winter is still out there and January 2009 is almost in the books. After a long period without updating I’ll try to “rush” some posts this week, trying to get back on track. So, a little bit of what’s up and coming:

- a patch provided by Robin Stocker to make all scripts published here (at least the ones on GitHub) PEP 8 compliant.

- using SQLite databases in Python

- developing an interface to access the database

- anything that you might suggest, just leave a comment.

Let’s start 2009 then.

Reblog this post [with Zemanta]

Twitter

Phase 2 Comments Off

I’m on Twitter, for quite some time. Some Python stuff, some biology, some bioinformatics, and a little bit of everything else.

nuin.

Python Magazine?

off topic Comments Off

I have been buying Python Magazine in the last months and I really like it, especially now that I already miss Linux Magazine and have no close source for Linux Journal (I should subscribe, I know). Last week I got an email from Python Magazine that I could use a coupon to buy some issues. Coupon that I used right away. Paid with PayPal and I’m still waiting for my issue to show up. Sent a couple of emails using the contact form and until now, nothing. I’ll wait until next year and see what happened. It’s really sad because this issue covers cloud computing with Python.

Edit: problem solved. Thanks everyone!

Design by j david macor.com.Original WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in