Python——Django-urls.py的做用

1、urls.py的做用是保存路徑和函數的對應關係

2、函數返回指定內容

from django.urls import path #引用HTTP協議的代碼
from django.shortcuts import HttpResponse def yimi(request): #request參數保存了全部和用戶瀏覽器請求相關的數據,返回指定內容
    return HttpResponse(r'hello world') urlpatterns = [ path('admin/', admin.site.urls), #yimi/是瀏覽器的路徑,yimi是函數
    path('yimi/',yimi), ]

3、函數返回頁面

一、使用HttpResponse返回html

def xiaohei(request): with open("./templates/xiao.html","r",encoding="utf-8") as f: data =f.read() return HttpResponse(data)

二、使用render返回django

from django.shortcuts import render def xiaohei(request): return render(request,"xiao.html")

 三、返回一些提示內容瀏覽器

3.1在HTML里加入 error 是標識符函數

<p>{{ error }}</p>

3.2使用render 標識符要一直url

def xiaohei(request): msg = '錯誤'
    return render(request,"zzz.html",{"error":msg})

4、函數跳轉頁面

from django.shortcuts import redirect def xiaohei(request): return redirect("http://www.baidu.com")

 5、引用應用的內容

from 應用名 import views urlpatterns = [ path('yimi/',views.yimi) ]
相關文章
相關標籤/搜索