Django-视图层

视图函数

视图函数,简称视图,是一个简单的Python 函数,它接受Web请求并且返回Web响应。

无论视图本身包含什么逻辑,都要返回响应

请求对象

urls.py

from django.contrib import admin
from django.urls import path,re_path

from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),

    re_path(r"index/",views.index),   #调用的是index(request)
    re_path('^$',views.index),  # 啥都不写,访问的是根路径(IP+端口)
]

 views

from django.shortcuts import render, HttpResponse

# Create your views here.


'''
http://127.0.0.1:8000/index/
协议://IP:port/路径/?get请求数据
url:协议、路径(端口之后,问号之前)、get请求数据(问号后面的)。
'''


def index(request):
    print('method', request.method)  # GET  or POST

    print(request.GET)  # 如果是get请求这个字典里就有值 request.GET.get('name')
    print(request.POST)  # 如果是post请求这个字典里就有值 request.POST.get('name')

    print(request.path)  # /index/ 或 /

    print(request.get_full_path())  # 可以获得get请求数据 /index/?a=1

    print(request.is_ajax())  # 判断是不是ajax方法,返True或False

    return render(request, 'index.html')

响应对象

响应对象主要有三种形式:

  • HttpResponse()

  • render()

  • redirect()

# return HttpResponse('<h1>OK</h1>')
# return redirect('http://example.com/') 

import datetime
now = datetime.datetime.now()
return render(request, 'index.html', {'time': now})

'''
    render方法会检测模板文件有没有模板语法,如果有的话就渲染成html文件。index.html --> 模板文件
    '''

猜你喜欢

转载自www.cnblogs.com/hexiaorui123/p/10503150.html