django框架学习一:get、post请求demo
django项目搭建省略,这里直接记录简单的get和post请求demo:
views.py代码:
from django.http import HttpResponse, JsonResponse from django.views import View class Index(View): def get(self, request): return HttpResponse("类中的django的get请求") def post(self, request): data = [ { "name": "奔奔", "age": 18 }, { "name": "小小", "age": 20 } ] # 返回字典,需要使用JsonResponse # 如果返回的非字典,需要设置safe=False return JsonResponse(data, safe=False)
项目中urls.py代码:
from django.urls import path from projects import views urlpatterns = [ path('class_index/', views.Index.as_view()) ]
全局中urls.py代码:
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('projects/', include('projects.urls')) ]
使用浏览器访问时,访问的是get请求:
使用postman接口工具,访问post请求,可以看到接口返回结果: