Creating a django rest API for my python script
Question: I have a JSON file with data as such :

    
    
    ['dbname' : 'A', 'collection' : 'ACollection', 'fields' : ['name', 'phone_no', 'address']}
    ['dbname' : 'B', 'collection' : 'BCollection', 'fields' : ['name', 'phone_no', 'address', 'class']}
    

These are 2 examples amongst many other dictionaries of the same format.

I have a python code that does the following : Accepts 2 inputs from the user
- phone_no and dbname. For example, the user enters phone_no as xxxxxxxxxx and
dbname as A. The python code then reads the JSON file and matches the user
input with the dictionary element having the name of the database as 'A'. It
then opens the database 'A', opens the respective collection 'ACollection' and
prints the respective fields of posts within the collection that have the
phone_no value as xxxxxxxxxx. The databases are implemented with mongoDB.

I need to build a django rest api for this code. The end goal is to access the
code from a browser. The user provides the 2 inputs in the browser and the
code is executed, returning the data, which is displayed on the browser. I
have gone through the django-rest framework documentation but I'm new to this
whole concept and would like some guidance.

How do I implement these functions and create an API? What code should the
models, serializers, views and urls files have related to my program?

models.py

    
    
    from django.db import models
    
    
    class App(object):
            def __init__(self, phone_no, name, address, categories):
                    self.phone_no = phone_no
                    self.name = name
                    self.address = address
                    self.categories = categories
    

This is what I'm working with so far, to get started. The problem, however, is
that the models class should essentially be dynamic. Ex: If 'A' is the
database, the program returns 3 fields but if 'B' is the database, the program
returns 4 values so I'm not sure what the models class would be like.

views.py

    
    
    from django.views.decorators.csrf import csrf_exempt
    from rest_framework.decorators import api_view
    from rest_framework.response import Response
    from pymongo import Connection
    from models import App
    from serializers import AppSerializer
    import json
    import pymongo
    from os import listdir
    import re
    from django import forms
    
    
    @csrf_exempt
    @api_view(['GET'])
    def pgs(request):
        #connect to our local mongodb
        db = Connection('localhost',27017)
        #get a connection to our database
        dbconn = db.general
        dbCollection = dbconn['data']
    
        if request.method == 'GET':
            #get our collection
            items = []
            for r in dbCollection.find():
                post = App(r["phone_no"],r["name"],r["address"],r["categories"])
                items.append(post)
            serializedList = AppSerializer(items, many=True)
            return Response(serializedList.data)
    


Answer: Let's say you have identical tables in two different databases. We'd start by
creating two db connections in settings.py. Let's say those are called db_a
and db_b. We might model this as so:

    
    
    class PhoneGenome(models.Model):
        phone_no = models.CharField(length=255)
        name = models.CharField(length=255)
        # and so on...
        class Meta:
            # if database pre-exists, may want to use managed=False
            managed = False
    

This gives us a model. Now we choose which database to pull from based on user
input. In a view, you might have something like:

    
    
    db_used = request.GET.get('database')
    db_conns = {'a': 'db_a', 'b': 'db_b'}
    if db_conns.has_key(db_used):    
        records = PhoneGenome.objects.using(db_conns[db_used]).filter( user_criteria_here)
    

The using() method in your queryset is what allows you to select which
database to run the query against.

There's a lot to manage here potentially, so this would be a good time to look
at the docs: <https://docs.djangoproject.com/en/1.7/topics/db/multi-db/>

And if you haven't already, you really should work through the Django tutorial
at the very least before going much further.

