1. urls.py
from django.contrib import admin
from django.urls import path
from App.views import *
urlpatterns = [
path('request/',request_views),
path('response/', response_views),
path('admin/', admin.site.urls),
]
2. views.py
from django.core.handlers.wsgi import WSGIRequest
from django.http import JsonResponse
from django.shortcuts import render,HttpResponse,redirect,reverse,HttpResponseRedirect
# Create your views here.
# 请求
def request_views(request):
# GET请求地址 http://127.0.0.1:8000/request/?name=lisi&age=44&name=zhansan
print(request) # 请求对象
# <WSGIRequest: GET '/request/'>
# request对象的属性和方式
print(request.method) # 请求方式 GET POST
print(request.GET) # GET请求参数 <QueryDict: {}> 类字典对象 <QueryDict: {'name': ['lisi'], 'age': ['44']}>
print(request.GET['name']) # 如果name不存在,则报错 lisi
print(request.GET.get('name',default='匿名用户')) # 如果name不存在,不会报错,返回None或者默认值 lisi
print(request.GET.getlist('name')) # 如果name有多个值,都会获取,以列表的形式返回 ['lisi']
print(request.POST) # POST请求参数
print(request.path) # 路径 /request/
print(request.get_full_path()) # /request/?name=lisi&age=44&name=zhansan
print(request.COOKIES) # cookies 会话技术 {'csrftoken': 'vHWJVVpffWvwOIfr1EPVe42nVPc2Nwqi', 'sessionid': 's2gr1tq80btzyeo3jciewigmuq5ftb38'}
print(request.session) # session 会话技术 {'csrftoken': 'vHWJVVpffWvwOIfr1EPVe42nVPc2Nwqi', 'sessionid': 's2gr1tq80btzyeo3jciewigmuq5ftb38'}
print(request.FILES) # 文件,前端上传的文件对象 <MultiValueDict: {}>
print(request.META['REMOTE_ADDR']) # 客户端的IP地址 127.0.0.1
return HttpResponse('ok')
# 响应
def response_views(request):
# 1.返回字符串
# return HttpResponse('ok')
# 2.返回模板 : 前后端不分离时使用
# return render(request,'index.html')
# 3.重定向 :跳转页面
# return redirect('/request/')
# return HttpResponseRedirect('/request/')
# 4.返回json数据 :前后端分离的方式
# return JsonResponse({'data':"hello"})
response = HttpResponse('ok')
response.content = 'hello'
response.status_code = 400
return response