Django Rest Framework-从现有视图定义API

时间:2018-10-20 07:56:18

标签: python django api django-rest-framework

我正在编写django应用程序,并且有很多视图已经返回JSONResponse对象,例如:

def power_on_relay(request):
'''View that Power on one of the available relays'''
try:
    relay_id = get_or_raise(request, 'relay_id')


    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(relay_id, GPIO.OUT)
    GPIO.output(relay_id, True)
    pin_status = GPIO.input(relay_id)


    return JsonResponse({'success': True, 'message': 'Relay {0} was powered on'.format(relay_id), 'data': None})
except Exception as ex:
    return JsonResponse({'success': False, 'message': str(ex), 'data': ''})

现在,我需要将其中一些视图公开为“ API”,并且需要管理身份验证,限制等。 因此,我想知道是否有可能使用DRF而不编写大量冗余代码。

我的意思是,有一个简短的方法吗?像装饰器这样的东西不会改变我的Web应用程序行为吗?

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您将需要使用api_view装饰器

from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET'])
def power_on_relay(request):
    '''View that Power on one of the available relays'''
    try:
        relay_id = get_or_raise(request, 'relay_id')


        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(relay_id, GPIO.OUT)
        GPIO.output(relay_id, True)
        pin_status = GPIO.input(relay_id)

        return Response({'success': True, 'message': 'Relay {0} was powered on'.format(relay_id), 'data': None})
    except Exception as ex:
        return Response({'success': False, 'message': str(ex), 'data': ''})