Reputation: 819
I'm new to python and just finished the django tutorial. I have a django powered site and I'm writing an android application which needs to send and receive data from the same database managed by django. The website and the application provide the same functionality, but I don't want pages rendered for the application, I just want to send/receive commands and serialised objects. Essentially what I need to do is
receive http request (from mobile) in django ---> Run myProgram.py ---> Update database ---> send confirmation to client.
Could I have a few pointers about what/where to edit? Thanks.
Upvotes: 0
Views: 607
Reputation: 27861
It seems that you are trying to make an API with Django. You can read here more about REST APIs. The basic idea is that your web site will have a set of command links/urls - where each link will either do some action (update db, etc), just return some information (most commonly in JSON - e.g. return an object from db), or will do both.
What you will have to do is make a list of all possible commands the api will have to handle. That will include all the commands of retrieving, inserting, updating, and deleting data.
For this example, lets assume the only job of the application is to manage items in a store. This is a very simplified demo however it should get the point across.
Here is a Django model (within Store
django app):
class Item(models.Model):
name = models.CharField(max_length=255)
price = models.IntegerField() # assume the price is always int
quantity = models.IntegerField()
So then lets assume the possible commands for api are:
URL structure for all the commands
urlpatterns = patterns('',
# will be used for getting, updating, and removing an item
url(r'^item/(?P<item_id>\d+)/$', "item"),
# will be used to get info about all items
url(r'^item/all/$', "item_all"),
# will be used to create new item
url(r'^item/new/$', "item_new"),
)
Getting info about all items
For getting information information from django, django serialization functions are very helpful. Here is a django docs for that.
#views.py
from django.core import serializers
import json
def item_all(request):
items = Item.objects.all()
data = serializers.serialize("json", items)
return HttpResponse(data, mimetype="application/json")
What this will do is return a JSON array with all the items like so:
[
{
pk: 1,
model: "store.item",
fields: {
name: "some_name",
price: 20,
quantity: 1000
}
},
// more items here
]
Adding new item
For this your android app will have to send a JSON object to the django.
JSON object:
{ data:
{
name: "some_name",
price: 40,
quantity: 2000
}
}
So now your django app has to parse the info from the request in order to create a new item:
#views.py
def item_new(request):
# the request type has to be POST
if request.method != "POST":
return HttpResponseBadRequest("Request has to be of type POST")
postdata = request.POST[u"data"]
postdata = json.loads(postdata)
item = Item()
item.name = postdata["name"]
item.price = postdata["price"]
item.quantity = postdata["quantity"]
item.save()
data = serializers.serialize("json", [item])
return HttpResponse(data, mimetype="application/json")
Some notes:
Note the use of the POST request type. This is very crucial in REST API's. Basically depending on the request type, different actions will be done. This is going to be much more vivid in the next view.
Getting, updating, and removing
#views.py
def item(request, item_id):
item = get_object_or_404(Item, pk=item_id)
if request.method == "GET":
data = serializers.serialize("json", [item])
return HttpResponse(data, mimetype="application/json")
elif request.method == "POST":
postdata = request.POST[u"data"]
postdata = json.loads(postdata)
item.name = postdata["name"]
item.price = postdata["price"]
item.quantity = postdata["quantity"]
item.save()
data = json.dumps(True)
return HttpResponse(data, mimetype="application/json")
elif request.method == "DELETE":
item.delete()
data = json.dumps(True)
return HttpResponse(data, mimetype="application/json")
else:
return HttpResponseBadRequest("Invalid request")
So what this method will be is do different actions according to the different request type.
Comments
Note that this is a very, very simple demo. It does not account for any error checking, user authentication, etc. But hopefully it will give you some ideas.
Upvotes: 7