如何从外部函数调用HttpResponse?

时间:2015-06-10 09:34:32

标签: django httpresponse

我有一个views.py(FBV):

def photoalbum_GET(request, album_id):
o = get_object_or_404_alt(PhotoAlbum, id=album_id)
return response_message('', 200)

从外部文件get_object_or_404_alt()调用函数my_shortcuts.py

def get_object_or_404_alt(klass, *args, **kwargs):
queryset = _get_queryset(klass)
try:
    object = queryset.get(*args, **kwargs)
    if object.is_deleted:
        return HttpResponse('Object was deleted', 404)
    if object.is_active == False:
        return HttpResponse('Object is not active', 403)
    ...

    return object
except queryset.model.DoesNotExist:
    raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)

但这个剪刀不起作用。 <{1}}中的方法HttpResponse()未被提升。

如何像我所描述的那样在外部python文件中调用它?

2 个答案:

答案 0 :(得分:2)

def photoalbum_GET(request, album_id):
    o = get_object_or_404_alt(PhotoAlbum, id=album_id)
    if isinstance(o, HttpResponse):
        return o
    return response_message('', 200)

HttpResponse不是方法,而是类。并且提出也不例外。

答案 1 :(得分:0)

除了@ f43d65的回答,HttpResponse必须是:

    if object.is_deleted:
        return HttpResponse('Object was deleted', status_code=404)
    if object.is_active == False:
        return HttpResponse('Object is not active', status_code=403)

参考:Django documentation: Request and response: HttpResponse