2011-12-29 88 views
3

刚刚用Django TastyPie开始使用JSON公开数据。 试图把使用tastypie.Api资源一起urls.pytastypie注册问题

http://django-tastypie.readthedocs.org/en/latest/tutorial.html#creating-resources 不开箱的工作给出的例子。

urls.py项:

#now for the api 
from tserver.api import PurchaseResource,DataResource 

#combine several APIs 
from tastypie.api import Api 

api = Api(api_name='') 
api.register(PurchaseResource(),canonical=True) 
api.register(DataResource(),canonical=True) 

urlpatterns = patterns('', (r'^api/',include(api.urls)), 
        ) 

api.py

#!/bin/env python 

from tastypie.resources import ModelResource 
from tastypie import fields 
from tserver.models import Purchase,Data 

class DataResource(ModelResource): 
    class Meta: 
     queryset = Data.objects.all() 


class PurchaseResource(ModelResource): 
    Info = fields.ForeignKey(DataResource,'data') 
    class Meta: 
     queryset = Purchase.objects.all() 
     resource_name = 'purchase' 

models.py

class Data(models.Model): 
    tagID = models.CharField(max_length=40) 
    dtime = models.DateTimeField() 
    vcardf = models.CharField(max_length = 600) 


class Purchase(models.Model): 
    Info  = models.ForeignKey('Data',unique=True) 
    payment_method = models.CharField(max_length=20,choices=PAYMENT_METHOD) 
    TotalAmount = models.DecimalField(max_digits = 20, decimal_places=2) 
    TotalDiscount = models.DecimalField(max_digits = 20, decimal_places=2) 
    valid_upto  = models.DateTimeField() 

最后当我尝试一下,错误:

http://localhost:8000/api/data/1/?format=json 

结果:

Page not found (404) 
Request Method:  GET 
Request URL: http://localhost:8000/api/data/1/?format=json 

Using the URLconf Django tried these URL patterns, in this order: 

^admin/ 
^(?P<api_name>)/$ [name='api__top_level'] 
^(?P<api_name>)/ 
^(?P<api_name>)/ 

The current URL, api/data/1/, didn't match any of these. 

但这个问题是不存在的,如果我只是在urls.py使用:

urlpatterns = patterns('', (r'^api/',include(DataResoure().urls)), 
         ) 

什么是这里的问题,当我们试图用api.register(...)绑在一起的东西呢?

回答

2

我们总是指定api_name和资源名称。像

注册文件

public_api = Api(api_name='public') 
public_api.register(BookingPostResource()) 
public_api.register(SearchResource()) 

private_api = Api(api_name='private') 
private_api.register(BookingPostResource()) 
private_api.register(SearchResource()) 

urls.py

urlpatterns = patterns('', 
    url(r'^api/', include(public_api.urls)), 
    url(r'^api/', include(private_api.urls)), 
) 

,我们得到网址:

http://www.mysite.com/api/public/ {} RESOURCE_NAME

http://www.mysite.com/api/private/ {} RESOURCE_NAME

我想警告你,tastypie显示出很差的生产力,并且包含一些可能导致数据丢失的严重问题,我们在开始工作之前做了很多猴子修补。目前我们正在转向我们自己的框架。我强烈建议你使用像活塞一样小的东西,但它也不是一颗银色的子弹。

+0

感谢您的意见。你有什么样的问题,你面对tastypie?是安全漏洞还是性能问题?请您详细说明......这将有助于我做出决定......并可帮助其他想要使用此功能的人。 – user1102171 2012-01-02 14:09:13

+0

性能问题很重要,序列化非常慢。节省大量的模型是非常密集的数据库。 发送模型的PUT和POST可能会导致数据丢失。 使用相关模型(ForeignKey和M2M)很麻烦。没有代码重复,很难禁止保存相关模型。 嵌套资源很难使用。 开箱即不支持文件上传。 创建多个模型时根本不返回位置标题。 可能我忘记了一些东西。 – Ilya 2012-01-03 12:06:19

+0

我回答你的问题吗? – Ilya 2012-01-05 00:40:01