1.1
提取query参数
发送请求:127.0.0.1:8000/index/?id=1&name=Tom
视图代码:
def index(request):
# 提取查询字符串、query参数
print(request.GET)
# 通过request的GET获取查询字符串
id = request.GET.get('id')
name = request.GET.get('name')
content = f"提取到的id为{id},提取到的name为{name}"
# return HttpResponse("这是一个简单的响应")
return HttpResponse(content)
1.2提取post请求体中的数据
视图代码:
# 提取post中得数据
def index3(request):
print(request.POST)
user = request.POST.get('user')
pwd = request.POST.get('pwd')
hobbies = request.POST.getlist('hobbies')
content = f"账号为{user},密码为{pwd},爱好为{hobbies}"
return HttpResponse(content)
1.3
视图响应
HttpResponse是所有响应的基类,其他响应都由HttpResponse继承而来
from django.http import HttpResponse
return HttpResponse("这是一个简单的响应")
JsonResponse返回一个Json格式的字符串,常用于响应axios请求
from django.http import JsonResponse
JsonResponse({"id":1001, "name":"Tom", "score":80})
render返回一个模板页面
from django.shortcuts import render
return render(request, 'index.html', {"id":1001, "name":"大帅", "score":80})
redirect重定向
from django.shortcuts import redirect
return redirect('/index2', permanent=True)
# 重定向 permanent为True永久重定向301 默认临时重定向302
edirect重定向
第四单元 路由配置
1.静态路由(GET参数)
127.0.0.1:8000/article/?page=1
127.0.0.1:8000/article/?page=2
127.0.0.1:8000/article/?page=3
2.动态路由
127.0.0.1:8000/article/1/
127.0.0.1:8000/article/2/
127.0.0.1:8000/article/3/
上下两种的区别:
1.动态路由传参,参数需要参与路由匹配,在路由匹配中获取参数
2.GET参数,参数部分不需要参与路由匹配,在视图中提取参数
动太路由案例
# 路由配置 from django.urls import path,re_path from users import views urlpatterns = [ # 动态路由 path('article/<str:page>/', views.ArticleView), path('<int:x>/<str:y>/', views.Index), re_path(r'^(?P<aaa>\d+)/$', views.Index2) ] # 视图代码 def ArticleView(request, page): print(type(page)) return HttpResponse(f"这是第{page}页") def Index(request, x, y): return HttpResponse(f"x:{x},y:{y}") def Index2(request, aaa): return HttpResponse(f"正则表达式路由,aaa:{aaa}")
路由分发:
1.在子应用的文件夹下创建一个urls.py文件, 将子应用的代码放在该文件下
from django.contrib import admin
from django.urls import path,include
# 导入子路由
from users import urls
# 主路由
urlpatterns = [
path('admin/', admin.site.urls),
# 路由分发
path('', include(urls)),
]
from django.urls import path,re_path
from users import views
# 子应用下的子路由
urlpatterns = [
# 静态路由
path('register/', views.RegisterView.as_view()),
path('login/', views.LoginView.as_view()),
path('index/', views.IndexView.as_view()),
# 动态路由
path('article/<str:page>/', views.ArticleView),
path('<int:x>/<str:y>/', views.Index),
re_path(r'^(?P<aaa>\d+)/$', views.Index2)
]