# 視圖函數
## 定義視圖
* 本質就是一個質數
* 視圖的參數:
* 一個HttpRequest實例
* 通過正則表達式組獲取的位置參數
* 通過正則表達式組獲得的關鍵字參數
* 在應用目錄下默認有views.py文件,一般視圖都定義在這個文件中
* 如果處理功能過多,可以將函數定義到不同的py文件中
```text
配置路由urls.py文件
"""
url(r'^index/$',views.index,name="index"),
"""
views.py
"""
from django.http import HttpResponse
def index(request):
return HttpResponse("helloworld")
"""
```
## 錯誤視圖
* Django原生自帶幾個默認的視圖用于處理HTTP錯誤
### 404\(page not found\)視圖
* defaults.page\_not\_found\(request,template\_name="404.html"\)
* 默認的404視圖將傳遞一個變量給模板:request\_path,是導致錯誤的URL
* 如果Django在檢測URLconf中的每個正則表達式后沒有找到匹配的內容也將調用404視圖
* 如果在settings中DEBUG設置為True,name將永遠不會調用404視圖,而是顯示URLconf并帶有一些調試信息
* 在templates中創建404.html
```text
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Not Found</title>
</head>
<body>
Not Found
</body>
</html>
```
* 在settings.py中·修改調試
```text
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["*",]
```
* 請求一個不存在的地址
```text
localhost:8000/notfound/
```
### 500\(server error\)視圖
* defaults.server\_error\(request,template\_name="500.html"\)
* 在視圖代碼中出現運行時錯誤
* 默認的500視圖不會傳遞變量給500.html模板URLconf并帶有一些調試信息
### 400\(bad request\)視圖
* defaults.bad\_request\(request,template\_name="400.html"\)
* 錯誤來自客戶端的操作
* 當用戶進行的操作在安全方面可疑的時候,例如篡改會話cookie