Django Tastypie with android client

I've been using django-tastypie recently to create restful apis and i wanted to use it especially with an android client. I've put together a sample application, django rest backend and an android client to demonstrate this. So here is a quick walk through of the code. Here is the models.py which describes a recipe.

from django.db import models

class Recipe(models.Model):
name = models.CharField(max_length=50)
content = models.TextField()

def __unicode__(self):
return self.name
We set up a Resource for our API using tastypie.

from tastypie.resources import ModelResource
from recipes.models import Recipe

class RecipeResource(ModelResource):
class Meta:
queryset = Recipe.objects.all()
resource_name = 'recipes'
allowed_methods = ['get']
include_resource_uri = False

def alter_list_data_to_serialize(self, request, data_dict):
if isinstance(data_dict, dict):
if 'meta' in data_dict:
#Get rid of the meta object
del(data_dict['meta'])

return data_dict
Now we set up the urlpattern to access the data

from django.conf.urls.defaults import patterns, include, url
from recipes.api.api import RecipeResource
from django.contrib import admin
admin.autodiscover()

recipe_resource = RecipeResource()

urlpatterns = patterns('',
url(r'^api/', include(recipe_resource.urls)),
url(r'^admin/', include(admin.site.urls)),
)

Test the api using curl.

$ curl -H 'Accept: application/json' http://localhost:8000/api/recipes/
Now that the api works as expected the next part is to create an android app client to consume the api. This will be a simple app for viewing recipes.Later we will add the ability to add recipes to our recipe database from the android client. This will be covered in part 2 of this tutorial.

It's okay to leave if things are not as expected

Lately i have been reading a series of articles about individuals who are leaving or have left their former places of  employment and giving their reasons for leaving.It is very interesting to note that most express dislike about the way things were being steered by their former companies.What is being brought out is that these big companies had turned evil and deviated from their original well meaning motives, if they ever existed.

For one, i tend to think that this is natural.In the world there exists no organisation with an altruistic motive.To think of it, the golden rule is always "whats in it for me".What is actually happening is that eager graduates are drawn in to companies thinking that they are contributing to a greater good, only to realize this years later.Of course there's the usual bouts of philanthropy that usually exist, but deep down to the core, profit is the main motivation.

Startup founders are encouraged to formulate brilliant ideas by looking for problems to solve, or scratching common itches.Ones success is achieved, it all becomes about maximizing profits.Soon the users needs are swept aside.The outlook currently is that the future is in startups, but remember too that the big corporations which have turned evil were once startups.Inevitably as a startup grows into a large  company, moral decay starts occuring.This comes with size and does not occur within a close tightly knit community around a startup because everybody knows everybody and there is close interaction.

There exists a theory in the field of Organization management that brings out this aspect, that as an organization grows it becomes more and more unstable.so it's expected.

Data access on android made easy with OrmLite

OrmLite is a wonderful Object Relational Mapper available for the android operating system.

If your using the normal methods to access the sqlite database, then you are bound to find the
process very tedious.I realized i needed an orm when i found myself writing redundant code and it came to my attention that i was actually writing my own orm.

OrmLite is suited for android because it is lightweight and therefore easy to import to an android project.
Furthermore it uses java annotations to mark classes to be persisted which make your code look clean and easier to understand.


import com.j256.ormlite.field.DatabaseField;

public class Customer {

@DatabaseField
int id;

@DatabaseField
String name;

@DatabaseField
String country;

@DatabaseField
String phone;

@DatabaseField
String address;

@DatabaseField
String businessName;


Customer(){
//used by ormlite
}

@Override
public String toString(){
return this.name;
}

}

To create a table we use TableUtils' createTable method

TableUtils.createTable(connectionSource, Customer.class);
Data access is done using Daos(Data access Object),these offer convenientmethods for querying, creating, deleting... objects on the sqlite database

private Dao<Customer, Integer> customersDao = getDao(Customer.class);

customersDao.create(customer);


customersDao.delete(customer);

customersDao.queryForAll();



In conclusion, using ormlite saves more time and is more convenient.

Transaction management in django

ACID refers to an acronym in the database transactions.Which in full means.Atomic, Consistent, Independent, Durable(or atomicity, consistency, independency and durability).

Atomicity here refers to the idea that a transaction commits(goes through) as a whole or does not commit at all(all or nothing).Various scenarios necessitate the need to maintain atomicity in a transaction.

For instance if you are creating objects which require foreign key relationships with other objects.
It may be necessary to create the object it is related to on the fly and save it just to make sure the foreign key attribute is satisfied.

when controlling transaction management in views the best approach is to use decorators

from django.db import transaction

@transaction.commit_on_success
def viewfunc(request):
# ...
# this code executes inside a transaction
# ...

There are three types of decorators, autocommit, commit_on_success and commit_manually.
autocommit does django's default commit behaviour
commit_on_success does a single transaction for all the work done in a function, this can be the view function.
commit_manually lets you control transactions manually by calling commit() and rollback().

Care should be taken when using commit manually() because some transactions may occur in unexpected places which require a commit.This raises an exception in django.

A point to note is that some databases do not support transaction management.It is surprising to note that SQLite db supports transactions while MySQL db does not.

programming is all about experience

Having spent a couple of years coding and exploring this industry i tend to think the major factor that influences ones proficiency in coding is experience.

Having experience guarantees that you have made certain mistakes that everybody must make in order to become a professional.It also guarantees that you have tried out solutions to some common problems encountered every day,have encountered the common design patterns that exist for creating software and have tried out the major flavors of programming.

There is the common rule that to master any craft you have to spend 10,000 hours at it, which also tends to stress the importance of experience.