Monday, December 17, 2012

Introducing django and mysql

I wanted to do some rapid prototyping with web applications, and decided to give python and django a go. There are various tutorials out there, but none of them seem to focus on using existing database structures and views.

So this is primarily to document my own findings. If someone else finds it useful: be my guest. ;-)



1. URL configs

These serve as the entry point to django from the web-browser's point of view. You can specify regex's and assign django views. The simplest one is probably this one:
urlpatterns = patterns('',
    url(r'^$', views.index, name='index')
)
For those that are regular-expresionally challenged, this regex matches an empty url. It looks for start of line immediately followed by end of line.


2. views

These views can be simple functions that return a HttpResponse, or more sophisticated classes. The simplest one is probably this one:
def index(request):
    return HttpResponse("Hello, world.")
This view always returns the text "Hello, world.". Yes, it really is that simple. There isn't even HTML code required. Most browsers will just render this text anyway.

3. manage.py syncdb

If you start out with an empty DB, you can use django to create it for you. You just need to define the data model in django. If you use multiple models with relationships, like in the excellent django tutorial here, you might wonder about foreign keys if you use MySQL. At least if InnoDB isn't your default storage engine. Fear not, one can easily tell django to use InnoDB anyway, by adding this to your settings.py file in the DATABASES section:
'OPTIONS': {
       "init_command": "SET storage_engine=INNODB",

 

4. manage.py inspectdb

Everyone knows that django can create a DB schema according to a python model. This is very nice, but quite often you are presented with a pre-existing DB schema. In tha case, just run "python manage.py inspectdb". This will churn out a python model according to the DB schema. I've tried it with MySQL on MyISAM and InnoDB alike. It works better with InnoDB because it supports foreign keys. Of course it won't make a difference if your schema doesn't actually have any. ;-)




No comments: