我有数据的JSON文件这样:创建一个Django的休息API为我的Python脚本
['dbname' : 'A', 'collection' : 'ACollection', 'fields' : ['name', 'phone_no', 'address']}
['dbname' : 'B', 'collection' : 'BCollection', 'fields' : ['name', 'phone_no', 'address', 'class']}
这些是2个例子当中相同格式的多部辞书。
我有一个python代码,执行以下操作:接受来自用户的2个输入 - phone_no和dbname。例如,用户将phone_no输入为xxxxxxxxxx,将dbname输入为A.然后,python代码读取JSON文件,并将用户输入与具有数据库名称的词典元素匹配为“A”。然后打开数据库'A',打开相应的集合'ACollection'并打印集合中phone_no值为xxxxxxxxxx的帖子的相应字段。数据库是用mongoDB实现的。
我需要为此代码构建一个django rest api。最终目标是从浏览器访问代码。用户在浏览器中提供2个输入,并执行代码,返回浏览器上显示的数据。我已经浏览了django-rest框架文档,但我对这个概念很陌生,希望得到一些指导。
如何实现这些功能并创建API?模型,序列化器,视图和URL文件与我的程序有什么关系?
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
这就是我的工作,到目前为止,上手。但问题是,模型类应该基本上是动态的。例如:如果'A'是数据库,程序返回3个字段,但如果'B'是数据库,程序返回4个值,所以我不确定模型类是什么样的。
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)
您对数据模型有任何初始代码吗?这可能是一个开始的好地方,可以得到更具体的问题。 – dylrei 2015-02-23 23:02:20
到目前为止,我有一个基本的API设置,仅从数据库中检索数据并显示它。我试图找出如何在浏览器中获取用户的phone_no输入,并用它来查询数据库中的帖子。 – user3799658 2015-02-23 23:13:22
太棒了。如果你有一个数据库,你至少有一个数据模型的开始。你有没有Django模型类,或者它仍然只是一个数据库模式?无论哪种方式,让我们先看看。 – dylrei 2015-02-24 00:00:56