FBV:Function base views
def index(request):
if request.method == 'POST':
return HTTPresponse(‘ok’)
elif request.method == 'GET':
return render(request,'index.html')
CBV : class base views
URLS:
urlpatterns=[
url(r'^index/',views.Index.as_view())
]
注:url(r'^index/',views.Index.as_view())是固定用法html
views.py
from django import views
class Index(views.View):
def get(self,request):
return render(request,'index.html')
def post(self,request):
print(request.POST)
return render(request,'index.html')
注意事項:
1.CBV定義時必定要繼承django.views.View
2.註冊路由的時候要寫類名 .as_view()
3.具體原理:dispatch()方法中利用反射找到每一個請求要執行的
2.先後端分離
1.前端:
- APP
- PC網站
- 移動端網站
2.後端提供 JSON格式數據
3.接口(API)是什麼?
URL
4.小項目
1. 使用Django 的視圖 本身序列化
1. HttpResponse
2. JsonResponse
2. 使用Django REST Framework 框架的序列化工具類
1. 安裝
pip install djangorestframework
2. 導入
from rest_framework import serializers
3. 使用
class ArticleSerializer(serializers.Serializer):前端
http://www.django-rest-framework.org/git
https://q1mi.github.io/Django-REST-framework-documentation/github
實例:
from django.http import JsonResponse from app01 import models from rest_framework import serializers class DBG(serializers.Serializer): id = serializers.IntegerField() title = serializers.CharField() create_time = serializers.DateField() update_time = serializers.DateField() type = serializers.CharField(source='get_type_display') school = serializers.CharField(source="school.name")
#和ORM類綁定的序列化
class CYM(serializers.ModelSerializer): class Meta: model = models.Article #綁定的哪個類 fields = '__all__' #['id','name','title'] depth = 1 #官方推薦不超過10層 有外鍵關聯時,才須要設置depth參數!
def list1(request): query_set = models.Article.objects.all() print(query_set) xbg = CYM(query_set,many = True)
return JsonResponse(xbg.data,safe=False)
參數解釋:django
many=True 表示能序列化多個對象。後端
補充知識點:
1. pip
1. pip安裝包臨時指定 從國內的清華pip源下載:
pip install django==1.11.11 -i https://pypi.tuna.tsinghua.edu.cn/simple
2. 將虛擬環境的依賴包關係導出到requirements.txt
pip freeze > requirements.txt
3. 按照 requirements.txt 安裝項目依賴的第三方包
pip install -r requirements.txt
2. 在單獨py文件運行django orm語句
import os
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "about_drf.settings")
import django
django.setup()
from app01 import models
...
3. 可調用對象
def xx(arg):
if callable(arg):
print(arg())
else:
print(arg)
xx('呵呵')
xx(lambda:'嘿嘿嘿')app