成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

Django基礎(chǔ)之(十)DRF

eccozhou / 559人閱讀

摘要:基礎(chǔ)之二簡介官方文檔安裝與配置安裝配置重新創(chuàng)建數(shù)據(jù)庫并配置新建一個(gè)的將座位,并做配置加入環(huán)境變量定義好主備路由主路由項(xiàng)目路由創(chuàng)建名稱地址聯(lián)系電話郵箱創(chuàng)建數(shù)據(jù)庫同步生成數(shù)據(jù)北京機(jī)房北京市酒仙橋北京機(jī)房上海機(jī)房上海上

DRF基礎(chǔ)之二 簡介

官方文檔

Requirements

REST framework requires the following:

Python (2.7, 3.4, 3.5, 3.6, 3.7)

Django (1.11, 2.0, 2.1)

The following packages are optional:

coreapi (1.32.0+) - Schema generation support.
Markdown (2.1.0+) - Markdown support for the browsable API.
django-filter (1.0.1+) - Filtering support.
django-crispy-forms - Improved HTML display for filtering.
django-guardian (1.1.1+) - Object level permissions support

安裝與配置

安裝

pip3 install djangorestframework
pip3 install markdown # Markdown support for the browsable API.
pip3 install django-filter # Filtering support

配置

django-admin startproject devops
vim devops/settings.py
INSTALLED_APPS = (
       ...
        "rest_framework‘
    )
# 重新創(chuàng)建數(shù)據(jù)庫day4,并配置vim devops/settings.py
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": "day4",
        "USER": "root",
        "PASSWORD": "123456",
        "HOST": "localhost",
        "PORT": 3306,
        "OPTIONS": {
            "init_command": "SET default_storage_engine=INNODB;",
        },
    }
}

新建一個(gè)idc的app

mkdir apps
django-admin startapp idc
mv idc apps
touch apps/__init__.py

將apps座位mainPath,并做配置

加入settings.py環(huán)境變量

import sys
sys.path.insert(0,os.path.join(BASE_DIR,"apps"))
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "rest_framework",
    "idc.apps.IdcConfig"
]

定義好主備路由

- 主路由
from django.conf.urls import url,include
from django.contrib import admin

urlpatterns = [
    url(r"^admin/", admin.site.urls),
    url(r"^",include("idc.urls"))
]

- 項(xiàng)目路由
from django.conf.urls import url,include
from . import views
urlpatterns = [
    url(r"idcs/$",views.idc_list)
]

創(chuàng)建idc/models.py

from django.db import models

class Idc(models.Model):
    name = models.CharField("IDC名稱",max_length=128,blank=False,null=True)
    address = models.CharField("IDC地址",max_length=200,default="")
    phone = models.CharField("IDC聯(lián)系電話",max_length=20,null=True)
    email = models.EmailField("IDC郵箱")

    def __str__(self):
        return self.name

    class Meta:
        db_table = "idc"

創(chuàng)建idc/serializers.py

from rest_framework import serializers
from .models import Idc
class IdcSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField()
    address = serializers.CharField()
    phone = serializers.CharField()
    email = serializers.EmailField()

數(shù)據(jù)庫同步&生成數(shù)據(jù)

(venv3) [vagrant@localhost devops]$ python3 manage.py makemigrations
(venv3) [vagrant@localhost devops]$ python3 manage.py migrate
(venv3) [vagrant@localhost devops]$ python3 manage.py shell
In [1]: from idc.models import Idc                                                      
In [2]: idc = Idc()                                                                     
In [3]: idc.name = "北京機(jī)房"                                                           
In [4]: idc.address = "北京市酒仙橋"                                                    
In [5]: idc.phone = "123990131"                                                         
In [6]: idc.email = "[email protected]"                                                   
In [7]: idc.save()                                                                      
In [8]: idc                                                                             
Out[8]: 
In [10]: data = {"name":"上海機(jī)房","address":"上海","phone":"90909931","email":"[email protected]"}                           In [11]:                                                                                
In [11]: data                                                                           
Out[11]: 
{"name": "上海機(jī)房",
 "address": "上海",
 "phone": "90909931",
 "email": "[email protected]"}
In [12]: idc = Idc(**data)                                                              
In [13]: idc.save() 
In [14]: Idc.objects.all()                                                              
Out[14]: , ]>
In [15]: idc                                                                            
Out[15]: 
In [16]: from idc.serializers import IdcSerializer                                      
In [17]: serializer = IdcSerializer(idc)                                                
In [18]: serializer                                                                     
Out[18]: 
IdcSerializer():
    id = IntegerField()
    name = CharField()
    address = CharField()
    phone = CharField()
    email = EmailField()
In [19]: serializer.data                                                                
Out[19]: {"id": 2, "name": "上海機(jī)房", "address": "上海", "phone": "90909931", "email": "[email protected]"}

會(huì)出錯(cuò)的地方

In [21]: import json   
In [22]: json.dumps(serializer.data)                                                         
Out[22]: "{"id": 2, "name": "u4e0au6d77u673au623f", "address": "u4e0au6d77", "phone": "90909931", "email": "[email protected]"}"
In [23]: from rest_framework.renderers import JSONRenderer               
In [24]: content = JSONRenderer().render(serializer.data)                     
In [25]: content                     #獲取到瀏覽器的數(shù)據(jù)
Out[25]: b"{"id":2,"name":"xe4xb8x8axe6xb5xb7xe6x9cxbaxe6x88xbf","address":"xe4xb8x8axe6xb5xb7","phone":"90909931","email":"[email protected]"}"
In [26]: from django.utils.six import BytesIO                                                                                                                                                                                                    
In [27]: stream = BytesIO(content)               #將獲取的數(shù)據(jù)轉(zhuǎn)換成一個(gè)流                                                                                                                                                                                        
In [28]: from rest_framework.parsers import JSONParser                                                                                                                                                                                           
In [29]: data = JSONParser().parse(stream)          #將數(shù)據(jù)轉(zhuǎn)換成dict                                                                     
In [30]: data                                                                                                                                                                                                                                    
Out[30]: 
{"id": 2,
 "name": "上海機(jī)房",
 "address": "上海",
 "phone": "90909931",
 "email": "[email protected]"}

新創(chuàng)建數(shù)據(jù)并測試

from rest_framework import serializers
from .models import Idc

class IdcSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField()
    address = serializers.CharField()
    phone = serializers.CharField()
    email = serializers.EmailField()
    def create(self, validated_data):
        return Idc.objects.create(**validated_data)

測試:

In [1]: data = {"name":"上海機(jī)房","address":"上海","phone":"90909931","email":"[email protected]"}                                                                                                                                           
In [2]: data                                                                                                                                                                                                                                     
Out[2]: 
{"name": "上海機(jī)房",
 "address": "上海",
 "phone": "90909931",
 "email": "[email protected]"}
In [3]: from idc.serializers import IdcSerializer                                                                                                                                                                                                
In [4]: idc = IdcSerializer(data=data)                                                                                                                                                                                                           
In [5]: idc.is_valid()                                                                                                                                                                                                                           
Out[5]: True
In [6]: idc.save()                                                                                                                                                                                                                               
Out[6]: 

處理queryset

In [7]: from idc.models import Idc                                                                                                                                                                                                               
In [8]: Idc.objects.all()                                                                                                                                                                                                                        
Out[8]: , , ]>
In [9]: queryset = Idc.objects.all()                                                                                                                                                                                                             
In [10]: IdcSerializer(queryset)    
In [15]: ser = IdcSerializer(queryset,many=True)        #many=False是要單個(gè)數(shù)據(jù)                                                                                                                                                                           
In [16]: ser.data                                                                                                                                                                                                                                
Out[16]: [OrderedDict([("id", 1), ("name", "北京機(jī)房"), ("address", "北京市酒仙橋"), ("phone", "123990131"), ("email", "[email protected]")]), OrderedDict([("id", 2), ("name", "上海機(jī)房"), ("address", "上海"), ("phone", "90909931"), ("email", "[email protected]")]), OrderedDict([("id", 3), ("name", "上海機(jī)房"), ("address", "上海"), ("phone", "90909931"), ("email", "[email protected]")])]
序列化模型

model obj ==== > JSON

反序列化模型

http提交的數(shù)據(jù) ==== > JSON =====> obj(model obj)

創(chuàng)建idc/views.py

from .models import Idc
from .serializers import IdcSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from django.http import HttpResponse,JsonResponse

class JSONResponse(HttpResponse):
    def __init__(self,data,**kwargs):
        kwargs.setdefault("content_type", "application/json")
        content = JSONRenderer().render(data)
        super(JSONResponse,self).__init__(content=content,**kwargs)

def idc_list(request,*args,**kwargs):
    if request.method == "GET":
        queryset = Idc.objects.all()
        serializer = IdcSerializer(queryset,many=True)
        return JSONResponse(serializer.data)
        # content = JSONRenderer().render(serializer.data)
        # return HttpResponse(content,content_type="application/json")

    elif request.method == "POST":
        content = JSONParser().parse(request)
        serializer = IdcSerializer(data=content)
        if serializer.is_valid():
            serializer.save()
            content = JSONRenderer().render(serializer.data)
            return HttpResponse(content, content_type="application/json")

測試

In [17]: import requests                                                                                                                                                                                                                         
In [18]: url = "http://192.168.33.10:8080/idcs/"                                                                                                                                                                                                 
In [19]: data = {"name":"上海機(jī)房","address":"上海","phone":"90909931","email":"[email protected]"}                                                                                                                                         
In [20]: requests.post(url,data)                                                                                                                                                                                                                 
Out[20]: 
In [21]: r = requests.post(url,json=data)                                                                                                                                                                                                        
In [22]: r.status_code                                                                                                                                                                                                                           
Out[22]: 500
In [23]: r = requests.post(url,json=data)                                                                                                                                                                                                        
In [24]: r.status_code                                                                                                                                                                                                                           
Out[24]: 200
In [25]: r.content                                                                                                                                                                                                                               
Out[25]: b"{"id":5,"name":"xe4xb8x8axe6xb5xb7xe6x9cxbaxe6x88xbf","address":"xe4xb8x8axe6xb5xb7","phone":"90909931","email":"[email protected]"}"

詳情相關(guān)的數(shù)據(jù)

idc/urls.py:

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r"idcs/$",views.idc_list),
    url(r"idcs/(?P[0-9]+)/$",views.idc_detail),
]

views.py

from .models import Idc
from .serializers import IdcSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from django.http import HttpResponse,JsonResponse

class JSONResponse(HttpResponse):
    def __init__(self,data,**kwargs):
        kwargs.setdefault("content_type", "application/json")
        content = JSONRenderer().render(data)
        super(JSONResponse,self).__init__(content=content,**kwargs)

def idc_list(request,*args,**kwargs):
    if request.method == "GET":
        queryset = Idc.objects.all()
        serializer = IdcSerializer(queryset,many=True)
        return JSONResponse(serializer.data)
        # content = JSONRenderer().render(serializer.data)
        # return HttpResponse(content,content_type="application/json")

    elif request.method == "POST":
        content = JSONParser().parse(request)
        serializer = IdcSerializer(data=content)
        if serializer.is_valid():
            serializer.save()
            content = JSONRenderer().render(serializer.data)
            return HttpResponse(content, content_type="application/json")

def idc_detail(request,pk,*args,**kwargs):
    try:
        idc = Idc.objects.get(pk=pk)
    except Idc.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == "GET":
        serializer = IdcSerializer(idc)
        return JSONResponse(serializer.data)

    elif request.method == "POST":
        content = JSONParser().parse(request)
        serializer = IdcSerializer(data=content)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)

    elif request.method == "PUT":
        content = JSONParser().parse(request)
        serializer = IdcSerializer(idc,data=content)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)

    elif request.method == "DELETE":
        idc.delete()
        return HttpResponse(status=204)

測試:

In [1]: import requests                                                                 
In [2]: url = "http://192.168.33.10:8080/idcs/2/"                                       
In [3]: requests.get(url)                                                               
Out[3]: 
In [4]: requests.get(url).content                                                       
Out[4]: b"{"id":2,"name":"xe4xb8x8axe6xb5xb7xe6x9cxbaxe6x88xbf","address":"xe4xb8x8axe6xb5xb7","phone":"90909931","email":"[email protected]"}"
In [5]: requests.delete(url)                                                            
Out[5]: 
[vagrant@localhost ~]$ curl -s -X PUT -d "{"name":"wanghui"}" http://192.168.33.10:8080/idcs/1/     #更新操作
{"id":1,"name":"wanghui","address":"北京市酒仙橋","phone":"123990131","email":"[email protected]"}[vagrant@localhost ~]$ 

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/42681.html

相關(guān)文章

  • Django 基礎(chǔ)(九)drf介紹.md

    摘要:為什么要進(jìn)行前后端分離多端適配開發(fā)模式的流行前后端職責(zé)不清前后端開發(fā)效率問題,前后端相互等待前段一直配合后端,能力受到限制后端開發(fā)語言和模板高度耦合,導(dǎo)致開發(fā)語言依賴嚴(yán)重前后端分離的缺點(diǎn)前后端學(xué)習(xí)門檻增加數(shù)據(jù)依賴,導(dǎo)致文檔的重要性增加前段工 DRF 為什么要進(jìn)行前后端分離 PC,APP,PAD多端適配 SPA開發(fā)模式的流行 前后端職責(zé)不清 前后端開發(fā)效率問題,前后端相互等待 前段一直...

    ?。?。 評(píng)論0 收藏0
  • Django基礎(chǔ)二) DRF綜合小練習(xí)

    摘要:實(shí)戰(zhàn)小練習(xí)需求獲取指定組下的列表往用戶組添加用戶從組中刪除用戶需求分析獲取指定組下的列表網(wǎng)用戶組添加用戶從組中刪除用戶走界面不行項(xiàng)目結(jié)構(gòu)主路由配置文件開源運(yùn)維平臺(tái)子路由配置文件序列 實(shí)戰(zhàn)小練習(xí) 需求 users userGroups groups groupUsers---- get : 獲取指定組下的user列表-----put:往用戶組添加用戶-----delete:從組中刪除用...

    lemon 評(píng)論0 收藏0
  • DRF跨域后端解決django-cors-headers

    摘要:后端實(shí)現(xiàn)跨域第三方擴(kuò)展在介紹之前,我先介紹兩個(gè)概念同源策略跨域同源策略同源策略是一種約定,是瀏覽器的一種安全機(jī)制。這里同源需要協(xié)議域名端口三者都相同,否則不能進(jìn)行訪問??缬虿煌粗g的網(wǎng)站通信就是跨域。 在使用django-rest-framework開發(fā)項(xiàng)目的時(shí)候我們總是避免不了跨域的問題,因?yàn)楝F(xiàn)在大多數(shù)的項(xiàng)目都是前后端分離,前后端項(xiàng)目部署在不同的web服務(wù)器上,因?yàn)槲覀兪呛蠖顺绦騿T...

    lingdududu 評(píng)論0 收藏0
  • DRF跨域后端解決django-cors-headers

    摘要:后端實(shí)現(xiàn)跨域第三方擴(kuò)展在介紹之前,我先介紹兩個(gè)概念同源策略跨域同源策略同源策略是一種約定,是瀏覽器的一種安全機(jī)制。這里同源需要協(xié)議域名端口三者都相同,否則不能進(jìn)行訪問??缬虿煌粗g的網(wǎng)站通信就是跨域。 在使用django-rest-framework開發(fā)項(xiàng)目的時(shí)候我們總是避免不了跨域的問題,因?yàn)楝F(xiàn)在大多數(shù)的項(xiàng)目都是前后端分離,前后端項(xiàng)目部署在不同的web服務(wù)器上,因?yàn)槲覀兪呛蠖顺绦騿T...

    leeon 評(píng)論0 收藏0
  • DRF跨域后端解決django-cors-headers

    摘要:后端實(shí)現(xiàn)跨域第三方擴(kuò)展在介紹之前,我先介紹兩個(gè)概念同源策略跨域同源策略同源策略是一種約定,是瀏覽器的一種安全機(jī)制。這里同源需要協(xié)議域名端口三者都相同,否則不能進(jìn)行訪問??缬虿煌粗g的網(wǎng)站通信就是跨域。 在使用django-rest-framework開發(fā)項(xiàng)目的時(shí)候我們總是避免不了跨域的問題,因?yàn)楝F(xiàn)在大多數(shù)的項(xiàng)目都是前后端分離,前后端項(xiàng)目部署在不同的web服務(wù)器上,因?yàn)槲覀兪呛蠖顺绦騿T...

    yanwei 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

閱讀需要支付1元查看
<