返回顶部
首页 > 资讯 > 后端开发 > Python >Django基础之(十)DRF
  • 475
分享到

Django基础之(十)DRF

基础DjangoDRF 2023-01-31 08:01:53 475人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

简介 官方文档 Requirements REST framework requires the following: python (2.7, 3.4, 3.5, 3.6, 3.7) Django (1.11, 2.0, 2.1)

简介

官方文档

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‘
    )
# 重新创建数据库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;',
        },
    }
}
  • 新建一个idc的app
mkdir apps
django-admin startapp idc
mv idc apps
touch apps/__init__.py
  • 将apps座位mainPath,并做配置
  • 加入settings.py环境变量
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'))
]

- 项目路由
from django.conf.urls import url,include
from . import views
urlpatterns = [
    url(r'idcs/$',views.idc_list)
]
  • 创建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联系电话",max_length=20,null=True)
    email = models.EmailField("IDC邮箱")

    def __str__(self):
        return self.name

    class Meta:
        db_table = "idc"
  • 创建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()
(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 = "北京机房"                                                           
In [4]: idc.address = "北京市酒仙桥"                                                    
In [5]: idc.phone = "123990131"                                                         
In [6]: idc.email = "beijing@idc.com"                                                   
In [7]: idc.save()                                                                      
In [8]: idc                                                                             
Out[8]: <Idc: 北京机房>
In [10]: data = {"name":"上海机房","address":"上海","phone":"90909931","email":"shanghai@idc.com"}                           In [11]:                                                                                
In [11]: data                                                                           
Out[11]: 
{'name': '上海机房',
 'address': '上海',
 'phone': '90909931',
 'email': 'shanghai@idc.com'}
In [12]: idc = Idc(**data)                                                              
In [13]: idc.save() 
In [14]: Idc.objects.all()                                                              
Out[14]: <QuerySet [<Idc: 北京机房>, <Idc: 上海机房>]>
In [15]: idc                                                                            
Out[15]: <Idc: 上海机房>
In [16]: from idc.serializers import IdcSerializer                                      
In [17]: serializer = IdcSerializer(idc)                                                
In [18]: serializer                                                                     
Out[18]: 
IdcSerializer(<Idc: 上海机房>):
    id = IntegerField()
    name = CharField()
    address = CharField()
    phone = CharField()
    email = EmailField()
In [19]: serializer.data                                                                
Out[19]: {'id': 2, 'name': '上海机房', 'address': '上海', 'phone': '90909931', 'email': 'shanghai@idc.com'}
  • 会出错的地方
In [21]: import JSON   
In [22]: json.dumps(serializer.data)                                                         
Out[22]: '{"id": 2, "name": "\\u4e0a\\u6d77\\u673a\\u623f", "address": "\\u4e0a\\u6d77", "phone": "90909931", "email": "shanghai@idc.com"}'
In [23]: from rest_framework.renderers import JSONRenderer               
In [24]: content = JSONRenderer().render(serializer.data)                     
In [25]: content                     #获取到浏览器的数据
Out[25]: b'{"id":2,"name":"\xe4\xb8\x8a\xe6\xb5\xb7\xe6\x9c\xba\xe6\x88\xbf","address":"\xe4\xb8\x8a\xe6\xb5\xb7","phone":"90909931","email":"shanghai@idc.com"}'
In [26]: from django.utils.six import BytesIO                                                                                                                                                                                                    
In [27]: stream = BytesIO(content)               #将获取的数据转换成一个流                                                                                                                                                                                        
In [28]: from rest_framework.parsers import JSONParser                                                                                                                                                                                           
In [29]: data = JSONParser().parse(stream)          #将数据转换成dict                                                                     
In [30]: data                                                                                                                                                                                                                                    
Out[30]: 
{'id': 2,
 'name': '上海机房',
 'address': '上海',
 'phone': '90909931',
 'email': 'shanghai@idc.com'}
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":"上海机房","address":"上海","phone":"90909931","email":"shanghai@idc.com"}                                                                                                                                           
In [2]: data                                                                                                                                                                                                                                     
Out[2]: 
{'name': '上海机房',
 'address': '上海',
 'phone': '90909931',
 'email': 'shanghai@idc.com'}
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]: <Idc: 上海机房>
  • 处理queryset
In [7]: from idc.models import Idc                                                                                                                                                                                                               
In [8]: Idc.objects.all()                                                                                                                                                                                                                        
Out[8]: <QuerySet [<Idc: 北京机房>, <Idc: 上海机房>, <Idc: 上海机房>]>
In [9]: queryset = Idc.objects.all()                                                                                                                                                                                                             
In [10]: IdcSerializer(queryset)    
In [15]: ser = IdcSerializer(queryset,many=True)        #many=False是要单个数据                                                                                                                                                                           
In [16]: ser.data                                                                                                                                                                                                                                
Out[16]: [OrderedDict([('id', 1), ('name', '北京机房'), ('address', '北京市酒仙桥'), ('phone', '123990131'), ('email', 'beijing@idc.com')]), OrderedDict([('id', 2), ('name', '上海机房'), ('address', '上海'), ('phone', '90909931'), ('email', 'shanghai@idc.com')]), OrderedDict([('id', 3), ('name', '上海机房'), ('address', '上海'), ('phone', '90909931'), ('email', 'shanghai@idc.com')])]

序列化模型

model obj ==== > JSON

反序列化模型

Http提交的数据 ==== > JSON =====> obj(model obj)

  • 创建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":"上海机房","address":"上海","phone":"90909931","email":"shanghai@idc.com"}                                                                                                                                         
In [20]: requests.post(url,data)                                                                                                                                                                                                                 
Out[20]: <Response [500]>
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":"\xe4\xb8\x8a\xe6\xb5\xb7\xe6\x9c\xba\xe6\x88\xbf","address":"\xe4\xb8\x8a\xe6\xb5\xb7","phone":"90909931","email":"shanghai@idc.com"}'
  • 详情相关的数据

idc/urls.py:

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

urlpatterns = [
    url(r'idcs/$',views.idc_list),
    url(r'idcs/(?P<pk>[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]: <Response [200]>
In [4]: requests.get(url).content                                                       
Out[4]: b'{"id":2,"name":"\xe4\xb8\x8a\xe6\xb5\xb7\xe6\x9c\xba\xe6\x88\xbf","address":"\xe4\xb8\x8a\xe6\xb5\xb7","phone":"90909931","email":"shanghai@idc.com"}'
In [5]: requests.delete(url)                                                            
Out[5]: <Response [204]>
[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":"beijing@idc.com"}[vagrant@localhost ~]$ 

--结束END--

本文标题: Django基础之(十)DRF

本文链接: https://lsjlt.com/news/193099.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
  • Django基础之(十)DRF
    简介 官方文档 Requirements REST framework requires the following: Python (2.7, 3.4, 3.5, 3.6, 3.7) Django (1.11, 2.0, 2.1) ...
    99+
    2023-01-31
    基础 Django DRF
  • SQL 基础之多表查询(十)
    JOINS 类型和它的语法Natural joins(自然连接):– NATURAL JOIN 子句– USING 子句– ON 子句自连接  非等值连接  Outer joi...
    99+
    2024-04-02
  • SQL 基础之子查询(十一)
    子查询:类型、语法、和注意事项使用子查询能解决哪些问题?子查询语法:select select_list from table where expr operator (selec...
    99+
    2024-04-02
  • Django基础之Model创建表
    一、创建单表models.py#!/usr/bin/env python # -*- coding:utf-8 -*- from __future__&nb...
    99+
    2024-04-02
  • day 71 Django基础六之ORM
        本节目录 一 锁 二 事务 三 xxx 四 xxx 五 xxx 六 xxx 七 xxx 八 xxx 一 锁   行级锁     select_for_update(nowa...
    99+
    2023-01-31
    基础 day ORM
  • day 52 Django基础一之web
      django第一天 本节目录 一 web框架的本质及自定义web框架 二 模板渲染JinJa2 三 MVC和MTV框架 四 Django的下载安装 五 基于Django实现的一个简单示例 一 w...
    99+
    2023-01-31
    基础 day web
  • web开发框架之Django基础
      在脚本中如何进行Django的运行 if __name__ == '__main__': import os import django # 注意路径(当前所在的位置,要加载Django的配置文件) ...
    99+
    2023-01-30
    框架 基础 web
  • Python全栈开发之Django基础
    No.1 MVC&MTV MVC M全拼为Model,主要封装对数据库层的访问,对数据库中的数据进行增、删、改、查操作 V全拼为View,用于封装结果,生成页面展示的html内容 C全拼为Controller,用于接收请求,处理业务...
    99+
    2023-01-31
    基础 Python Django
  • SQL 基础之时区函数(二十一)
    使用数据类型来存储两个日期时间值之间的时间差使用下列的日期时间函数:– CURRENT_DATE– CURRENT_TIMESTAMP– LOCALTIMESTAMP– DBTIMEZONE– SESSIO...
    99+
    2024-04-02
  • SQL 基础之DML 数据处理(十三)
    数据操作语言DML 可以在下列条件下执行:– 向表中插入数据– 修改现存数据– 删除现存数据事务是由完成若干项工作的DML语句组成的表中添加新的数据– INSERT 语句使用 INSERT 语句向表中插入数...
    99+
    2024-04-02
  • python之基础篇(十)——执行环境与
    防伪码:忘情公子著解释器环境与选项  python解释器启动:python [options] [-c cmd | filename | - ] [args]选项描述-3启用将从python3中删除或更改某些功能的警告-B阻止在导入时创建....
    99+
    2023-01-31
    环境 基础 python
  • django基础(一)
    项目的创建和启动 (venv3) [vagrant@localhost ~]$ cd /vagrant/ (venv3) [vagrant@localhost vagrant]$ django-admin startproject de...
    99+
    2023-01-31
    基础 django
  • Python基础(Django)
    介绍Django之前,先来明确几个基础概念:1、什么是Web框架?    Web框架其实是建立web应用的一种方式,它为应用程序提供一套程序框架,这样开发者可以专注于编写清晰、易维护的代码,而无需从头做起。    他们基本上都以相同的方式工...
    99+
    2023-01-31
    基础 Python Django
  • day 63 Django基础九之中间件
        本节目录 一 前戏 二 中间件介绍 三 自定义中间件 四 中间件的执行流程 五 中间件版登陆认证 六 xxx 七 xxx 八 xxx 一 前戏      我们在前面的课程中已经学会了...
    99+
    2023-01-31
    中间件 基础 day
  • Django学习之十: staticfi
    目录 Django学习之十: staticfile 静态文件 理解阐述 静态文件 Django对静态文件的处理 其它方...
    99+
    2023-01-30
    Django staticfi
  • Django零基础入门之运行Django版的hello world
    目录1.项目目录及文件说明:2.项目与应用app的关系:3.使用django框架编写hello world!1.项目目录及文件说明: manage.py django中的一个命令行...
    99+
    2024-04-02
  • SQL 基础之管理方案对象(十七)
    使用 ALTER TABLE 语句: 增加字段 修改字段 修改字段默认值 删除字段1、增加字段,新字段将成为最后一列:alter table tableadd (co...
    99+
    2024-04-02
  • Javascript基础学习之十个重要问题
    目录1.什么是Javascript?2.什么是DOM3. JS代码如何执行4. ==和===之间的区别5.Null(空值)与Undefined(未定义)6. Var vs Let v...
    99+
    2024-04-02
  • SQL 基础之索引、闪回、临时表(十八)
    创建索引:自动– 创建 PRIMARY KEY– 创建 UNIQUE KEY手动– CREATE INDEX 语句– CREATE TABLE 语句create table  语句中 create...
    99+
    2024-04-02
  • Python基础(Django三——Model)
    本篇内容接上篇Python基础(Django二)七、Model1、说明:Model是Django为方便程序操作数据库而诞生的,使用的是ORM模式。对象关系映射(Object Relational Mappi...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作