2

我正在尝试使用tastepie 实现一个带有RESTful API 的简单Django 服务。我的问题是,当我尝试使用 PUT 创建 WineResource 时,它​​工作正常,但是当我使用 POST 时,它返回 HTTP 501 错误。阅读美味派文档,它似乎应该可以工作,但事实并非如此。

这是我的 api.py 代码:

    class CustomResource(ModelResource):
    """Provides customizations of ModelResource"""
    def determine_format(self, request):
    """Provide logic to provide JSON responses as default"""
    if 'format' in request.GET:
        if request.GET['format'] in FORMATS:
        return FORMATS[request.GET['format']]
        else:
        return 'text/html' #Hacky way to prevent incorrect formats
    else:
        return 'application/json'

class WineValidation(Validation):
    def is_valid(self, bundle, request=None):
    if not bundle.data:
        return {'__all__': 'No data was detected'}

    missing_fields = []
    invalid_fields = []

    for field in REQUIRED_WINE_FIELDS:
        if not field in bundle.data.keys():
        missing_fields.append(field)
    for key in bundle.data.keys():
        if not key in ALLOWABLE_WINE_FIELDS:
        invalid_fields.append(key)

    errors = missing_fields + invalid_fields if request.method != 'PATCH' \
        else invalid_fields

    if errors:
        return 'Missing fields: %s; Invalid fields: %s' % \
            (', '.join(missing_fields), ', '.join(invalid_fields))
    else:
        return errors

class WineProducerResource(CustomResource):
    wine = fields.ToManyField('wines.api.WineResource', 'wine_set', 
                 related_name='wine_producer')
    class Meta:
    queryset = WineProducer.objects.all()
    resource_name = 'wine_producer'
    authentication = Authentication() #allows all access
    authorization = Authorization() #allows all access

class WineResource(CustomResource):
    wine_producer = fields.ForeignKey(WineProducerResource, 'wine_producer')

    class Meta:
    queryset = Wine.objects.all()
    resource_name = 'wine'
    authentication = Authentication() #allows all access
    authorization = Authorization() #allows all access
    validation = WineValidation()
    filtering = {
        'percent_new_oak': ('exact', 'lt', 'gt', 'lte', 'gte'),
        'percentage_alcohol': ('exact', 'lt', 'gt', 'lte', 'gte'),
        'color': ('exact', 'startswith'),
        'style': ('exact', 'startswith')

    }

    def hydrate_wine_producer(self, bundle):
    """Use the provided WineProducer ID to properly link a PUT, POST,
    or PATCH to the correct WineProducer instance in the db"""
    #Workaround since tastypie has bug and calls hydrate more than once
    try:
        int(bundle.data['wine_producer'])
    except ValueError:
        return bundle
    bundle.data['wine_producer'] = '/api/v1/wine_producer/%s/' % \
                        bundle.data['wine_producer']
    return bundle

任何帮助是极大的赞赏!:-)

4

1 回答 1

7

这通常意味着您将 POST 发送到详细 uri,例如/api/v1/wine/1/. 由于 POST 意味着将封闭的实体视为从属实体,因此将 POST 发送到列表 uri,例如/api/v1/wine/,可能是您想要的。

于 2012-10-18T03:25:20.653 回答