iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Django-REST-Framewo
  • 384
分享到

Django-REST-Framewo

DjangoRESTFramewo 2023-01-31 08:01:08 384人浏览 安东尼

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

摘要

We're Going to create a simple api to allow admin users to view and edit the users and groups in the system. Project se

We're Going to create a simple api to allow admin users to view and edit the users and groups in the system.

Project setup

Create a new Django project named tutorial, then start a new app called quickstart.

# Create the project directory
$ mkdir tutorial; cd tutorial

# Create a virtualenv to isolate our package dependencies locally
$ virtualenv env
$ source -p /usr/bin/python3 env/bin/activate

# Install Django and Django REST framework into the virtualenv
pip install django
pip install djangorestframework

# Set up a new project with a single application
django-admin.py startproject tutorial .  # Note the trailing '.' character
cd tutorial
django-admin.py startapp quickstart
cd ..

Now sync your database for the first time:

python manage.py migrate

We'll also create an initial user named admin with a passWord of password123. We'll authenticate as that user later in our example.

Python manage.py createsuperuser

Once you've set up a database and initial user created and ready to go, open up the app's directory and we'll get coding...

Serializers

First up we're going to define some serializers. Let's create a new module named tutorial/quickstart/serializers.py that we'll use for our data representations.

from django.contrib.auth.models import User, Group
from rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups')


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ('url', 'name')

Notice that we're using hyperlinked relations in this case, with HyperlinkedModelSerializer. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.

Views

Right, we'd better write some views then. Open tutorial/quickstart/views.py and get typing.

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer


class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

Rather than write multiple views we're grouping together all the common behavior into classes called ViewSets.

We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.

URLS

Okay, now let's wire up the API URLs. On to tutorial/urls.py...

from django.conf.urls import url, include
from rest_framework import routers
from tutorial.quickstart import views

router = routers.DefaultRouter()
router.reGISter(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.

Again, if we need more control over the API URLs we can simply drop down to using regular class-based views, and writing the URL conf explicitly.

Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.

Settings

We'd also like to set a few global settings. We'd like to turn on pagination, and we want our API to only be accessible to admin users. The settings module will be in tutorial/settings.py

INSTALLED_APPS = (
    ...
    'rest_framework',
)

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAdminUser',
    ],
    'PAGE_SIZE': 10
}

Okay, we're done.

Testing our API

We're now ready to test the API we've built. Let's fire up the server from the command line.

$ python manage.py runserver

1.Directly through the browser, by going to the URL Http://127.0.0.1:8000/users/...

ps: make sure to login using the control in the top right corner.

2.We can now access our API, both from the command-line, using tools like curl...

bash: curl -H 'Accept: application/JSON; indent=4' -u admin:password123 http://127.0.0.1:8000/users/
{
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        {
            "email": "admin@example.com",
            "groups": [],
            "url": "http://127.0.0.1:8000/users/1/",
            "username": "admin"
        },
        {
            "email": "tom@example.com",
            "groups": [                ],
            "url": "http://127.0.0.1:8000/users/2/",
            "username": "tom"
        }
    ]
}

3.Or using the httpie, command line tool...

$ http -a admin:password123 http://127.0.0.1:8000/users/

HTTP/1.1 200 OK
...
{
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        {
            "email": "admin@example.com",
            "groups": [],
            "url": "http://localhost:8000/users/1/",
            "username": "paul"
        },
        {
            "email": "tom@example.com",
            "groups": [                ],
            "url": "http://127.0.0.1:8000/users/2/",
            "username": "tom"
        }
    ]
}

If you want to get a more in depth understanding of how REST framework fits together head on over to the tutorial, or start browsing the API guide.

--结束END--

本文标题: Django-REST-Framewo

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

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

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Django-REST-Framewo
    We're going to create a simple API to allow admin users to view and edit the users and groups in the system. Project se...
    99+
    2023-01-31
    Django REST Framewo
  • django-rest-framewor
    源码繁琐,多说无益,耐心细读官方文档: https://www.django-rest-framework.org/   个人总结:   REST是一种软件架构设计风格,不是标准,也不是具体的技术实现,只是提供了一组设计原则和约束条件。 ...
    99+
    2023-01-30
    django rest framewor
  • Django Rest Framewor
    REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移” REST从资源的角度类审视整个网络,它将分布在网络中某个节点的资源通过URL进行...
    99+
    2023-01-30
    Django Rest Framewor
  • django rest framework http status code
    判断请求是否成功,可以从返回的状态码来区别,所以当写接口的时候也要这样做,标准化.from rest_framework import status通过导入status,里面已经定义好了状态码,源码如下:"""...
    99+
    2023-01-31
    framework rest django
  • Django REST framework 异常处理
    目录写在前面DRF异常处理1. DRF 常见的异常2. 自定义异常3. 使用自定义异常4. 验证结果异常处理进阶1. 修改自定义异常2. 自定义更多异常3. 新增测试接口4. 验证结...
    99+
    2024-04-02
  • python+robot framewo
    python+requests实现接口的请求前篇已经介绍,还有不懂或者疑问的可以访问python+request接口自动化框架目前我们需要考虑的是如何实现关键字驱动实现接口自动化输出,通过关键字的封装实现一定意义上的脚本与用例的脱离!rob...
    99+
    2023-01-31
    python robot framewo
  • Python Robot Framewo
    1、使用命令行安装:pip install robotframework -U 2、另外在python安装目录下的Lib\site-packages\robot会找到其核心代码文件 3、如何使用? 可阅读在线文档,地址:htt...
    99+
    2023-01-31
    Python Robot Framewo
  • Django REST Framework该怎么理解
    今天就跟大家聊聊有关Django REST Framework该怎么理解,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。1.Django REST framework框架介绍Djang...
    99+
    2023-06-02
  • Django REST framework 限流功能的使用
    目录正文开始 1. DRF 中的限流 2. 限流进阶配置 3. 限流思路分析 4. 源码分析 5. 其它注意事项 参考资料 正文开始 先说一个限流这个概念,最早接触这个概念是在前端...
    99+
    2024-04-02
  • Django rest framework如何自定义用户表
    目录说明1. Django项目和应用创建2. 自定义User表3. 序列化和路由3. DRF配置4. 同步数据库5. 测试6. 命令行注册用户说明 Django 默认的用户表 aut...
    99+
    2024-04-02
  • 深度解析Django REST Framework 批量操作
    目录DRF基本情况自定义批量操作批量创建批量删除批量更新djangorestframework-bulk依赖安装范例路由测试DRF3相关注意事项源码解读我们都知道Django res...
    99+
    2024-04-02
  • Django REST Framework 批量操作的示例分析
    这篇文章将为大家详细讲解有关Django REST Framework 批量操作的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。DRF基本情况我们以下面的代码作为例子:models:from&nb...
    99+
    2023-06-15
  • Django rest framework自定义用户表的方法
    这篇文章主要介绍了Django rest framework自定义用户表的方法,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。说明Django 默认的用户表 auth_user...
    99+
    2023-06-15
  • Django Rest Framework实现身份认证源码详解
    目录一.Django框架二.身份认证的两种实现方式:三.身份认证源码解析流程一.Django框架 Django确实是一个很强大,用起来很爽的一个框架,在Rest Framework中...
    99+
    2024-04-02
  • Django REST框架:如何使用HTTP API构建Web服务?
    Django REST框架是一个基于Django的强大的Web API框架,它使得构建Web服务变得更加容易和快速。本文将介绍如何使用Django REST框架来构建HTTP API服务。 安装Django REST框架 首先,需要安...
    99+
    2023-11-12
    django http git
  • 一步步教你如何在 Django REST API 中构建使用 JWT 验证
    基于令牌的身份验证,允许后端服务与前端(无论是web端,原生移动端或其他端)分离,并驻留在不同域中。 JSON Web Tokens (JWT) 是一种流行的令牌认证实现, 在本文中,我们使用它来验证,通过Django REST 框架.构建...
    99+
    2023-02-09
    Django API python爬虫
  • golang实现rest server
    背景 用golang对数据库标准操作进行封装,为后面的rest server提供数据库访问层。实现的目标是:能根据rest请求参数自动生成数据库操作语句,提供增、删、改、查、批量写入、事务等必要的数据库操作封装。并可以方便的扩展到多种数...
    99+
    2023-01-31
    golang rest server
  • python调用rest接口
    #!/usr/bin/env python # -*- coding: utf-8 -*-   import requests import json   def call(body,url):     headers = {}   # ...
    99+
    2023-01-31
    接口 python rest
  • ribbon+rest怎么使用
    本篇内容主要讲解“ribbon+rest怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“ribbon+rest怎么使用”吧!在微服务架构中,业务都会被拆分成一个独立的服务,服务与服务的通讯...
    99+
    2023-06-05
  • RyuBook1.0案例三:REST L
    该小结主要介绍如何添加一个REST Link 函数 RYU本身提供了一个类似WSGI的web服务器功能。借助这个功能,我们可以创建一个REST API。 基于创建的REST API,可以快速的将RYU系统与其他系统或者是浏览器相连接,非...
    99+
    2023-01-30
    案例 REST
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作