我有一个包含如下数据的JSON文件:
['dbname' : 'A', 'collection' : 'ACollection', 'fields' : ['name', 'phone_no', 'address']}
['dbname' : 'B', 'collection' : 'BCollection', 'fields' : ['name', 'phone_no', 'address', 'class']}
这是许多其他相同格式的词典中的两个例子。
我有一段执行以下操作的python代码:接受来自用户的两个输入- phone_no和dbname。例如,用户输入phone_no为xxxxxxxxxx,dbname为A。然后,python代码读取JSON文件,并将用户输入的内容与数据库名称为'A‘的字典元素进行匹配。然后,它打开数据库'A',打开相应的集合'ACollection‘,并打印集合中phone_no值为xxxxxxxxxx的posts的相应字段。数据库采用mongoDB实现。
我需要为此代码构建一个django rest api。最终目标是从浏览器访问代码。用户在浏览器中提供两个输入,并执行代码,返回在浏览器上显示的数据。我已经看过django-rest框架文档,但我对整个概念还不熟悉,需要一些指导。
如何实现这些函数并创建API?模型、序列化程序、视图和urls文件应该包含哪些与我的程序相关的代码?
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
这就是我到目前为止正在使用的,作为开始。然而,问题在于models类本质上应该是动态的。例如:如果'A‘是数据库,程序会返回3个字段,但如果'B’是数据库,程序会返回4个值,所以我不确定models类是什么样子的。
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)
发布于 2015-02-24 02:16:45
假设您在两个不同的数据库中有相同的表。我们首先在settings.py中创建两个数据库连接。假设它们被称为db_a和db_b。我们可以这样建模:
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
这给了我们一个模型。现在,我们根据用户输入选择要从哪个数据库中拉出。在视图中,您可能会看到类似以下内容:
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)
查询集中的using()方法允许您选择要对哪个数据库运行查询。
这里有很多潜在的需要管理的内容,所以现在是查看文档的好时机:https://docs.djangoproject.com/en/1.7/topics/db/multi-db/
如果您还没有学习过Django教程,那么在深入学习之前,您至少应该学习一下Django教程。
https://stackoverflow.com/questions/28681960
复制相似问题