【发布时间】:2015-02-23 19:39:03
【问题描述】:
我有一个 JSON 文件,其中包含这样的数据:
['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?模型、序列化程序、视图和 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
这是我目前正在使用的,开始。然而,问题在于模型类本质上应该是动态的。例如:如果 '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)
【问题讨论】:
-
你有数据模型的初始代码吗?这可能是一个很好的起点,可以解决一些更具体的问题。
-
到目前为止,我已经设置了一个基本的 API,它只是从数据库中检索数据并显示它。我试图弄清楚如何在浏览器中从用户那里获取 phone_no 输入并使用它来查询数据库中的帖子
-
太棒了。如果您有数据库,那么您至少已经开始使用数据模型。您是否有为此的 Django 模型类,或者它仍然只是一个 db 模式?不管怎样,让我们先来看看吧。
-
我已经添加了 models.py 类
-
太棒了。现在,当您说“数据库”时,您实际上是指不同的数据库连接,还是只是同一个数据库中的不同来源?
标签: python django mongodb rest django-rest-framework