(1)views.py
import json from django.http import HttpResponse, JsonResponse from rest_framework import viewsets from rest_framework.decorators import list_route logger = getLogger('test_view.log') class TestView(viewsets.ViewSet): @list_route(methods=["GET"]) def hello(self, request): logger.info("测试日志") result = {"code": 200, "data": [], "message":"success"} return HttpResponse(json.dumps(result))
(2)urls.py
import traceback from django.conf.urls import url, patterns from rest_framework import routers from test_view import TestView urlpatterns = patterns('', url(r'^$', 'views.index'), url(r'^/s$', 'views.index')) router = routers.DefaultRouter() router.register(r'/test', TestView, base_name='test') urlpatterns += router.urls二、第二种
(1)views.py
from django.views.decorators.http import require_GET, require_http_methods, require_POST from rest_framework.decorators import api_view # 只能接收get的请求,如果是post请求访问则直接报错,无法接收 @require_GET def rgt(request): return HttpResponse('GET请求') # 只能接收post的请求,如果是get请求访问则直接报错,无法接收 @require_POST def rpt(request): return HttpResponse('POST请求') # 可以接收到列表中的规定的请求,列表中的请求方法必须大写 @require_http_methods(['GET', 'POST']) def gpt(request): return HttpResponse('收到') # 可以接收到列表中的规定的请求 @api_view(['GET', 'POST']) def test(request): return HttpResponse('收到')
(2)urls.py
from django.conf.urls import url from views import test_view urlpatterns = [ url(r'^/test1', test_view.rgt), url(r'^/test2', test_view.rpt), url(r'^/test3', test_view.gpt), ]三、第三种
(1)views.py
import json from django.http import HttpResponse, JsonResponse from rest_framework.views import APIView class TestView(APIView): def get(self, request): result = {"code":200} return HttpResponse(json.dumps(result))
(2)urls.py
from django.conf.urls import url, include from django.contrib import admin from views import test_view urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^test1', test_view.TestView.as_view()) ]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)