2018-10-15-djangorestframework

本文详细介绍Django REST framework的功能和优势,包括强大的Web API构建工具、认证策略、序列化支持等。并提供了一个使用该框架创建简单模型支持API的实例教程。

个人博客地址——https://www.dogebug.cn/
GitHub地址——https://github.com/yanshigou/


layout: post
title: Djangorestframework
date: 2018-10-15 13:28:00
comments: true
subtitle: Django REST framework is a powerful and flexible toolkit for building Web APIs.
author: dzt
tags:

  • python
  • Django

先来看一下官方文档

Django REST framework is a powerful and flexible toolkit for building Web APIs.
Some reasons you might want to use REST framework:

  • The Web browsable API is a huge usability win for your developers.
  • Authentication policies including packages for OAuth1a and OAuth2.
  • Serialization that supports both ORM and non-ORM data sources.
  • Customizable all the way down - just use regular function-based views if you don’t need the more powerful features.
  • Extensive documentation, and great community support.
  • Used and trusted by internationally recognised companies including Mozilla, Red Hat, Heroku, and Eventbrite.

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:

Installation

Install using pip, including any optional packages you want…

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

…or clone the project from github.

git clone git@github.com:encode/django-rest-framework.git

Add 'rest_framework' to your INSTALLED_APPS setting.

INSTALLED_APPS = (
    ...
    'rest_framework',
)

If you’re intending to use the browsable API you’ll probably also want to add REST framework’s login and logout views. Add the following to your root urls.py file.

urlpatterns = [
    ...
    url(r'^api-auth/', include('rest_framework.urls'))
]

Note that the URL path can be whatever you want.

Example

Let’s take a look at a quick example of using REST framework to build a simple model-backed API.

We’ll create a read-write API for accessing information on the users of our project.

Any global settings for a REST framework API are kept in a single configuration dictionary named REST_FRAMEWORK. Start off by adding the following to your settings.py module:

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}

Don’t forget to make sure you’ve also added rest_framework to your INSTALLED_APPS.

We’re ready to create our API now. Here’s our project’s root urls.py module:

from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets

# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'is_staff')

# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

# 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'))
]

You can now open the API in your browser at http://127.0.0.1:8000/, and view your new ‘users’ API. If you use the login control in the top right corner you’ll also be able to add, create and delete users from the system.

个人博客地址——https://www.dogebug.cn/
GitHub地址——https://github.com/yanshigou/

禁止不留原创地址、署名的转载
本人保留所有法定权利。违者必究

### 安装 `djangorestframework-authtoken` 的方法 为了安装并配置 Django REST Framework (DRF) 中的 Token 认证功能,需遵循一系列操作来确保应用能够正常工作。 #### 准备环境 确保已经创建了一个虚拟环境,并激活该环境。这有助于隔离项目依赖项,防止不同项目的库之间发生冲突。 #### 安装必要的包 通过 pip 工具可以方便地安装所需的 Python 包: ```bash pip install djangorestframework drf-yasg django-rest-framework-simplejwt ``` 注意这里除了 `djangorestframework-authtoken` 外还额外推荐安装了两个常用的扩展包用于增强 API 文档展示以及 JWT 支持[^4]。 #### 修改 settings.py 文件 编辑Django项目的设置文件,在INSTALLED_APPS列表中加入'rest_framework'和'rest_framework.authtoken': ```python INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework.authtoken', # 添加这一行以启用Token认证支持 ] ``` 同时还需要定义默认的身份验证类为TokenAuthentication: ```python REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), } ``` 以上更改使得应用程序能识别基于token的身份验证请求[^5]。 #### 创建超级用户账号 运行命令创建一个新的超级管理员账户以便后续测试API接口时使用: ```bash python manage.py createsuperuser ``` 按照提示输入用户名、邮箱地址及密码完成创建过程。 #### 运行迁移脚本 为了让数据库表结构同步最新的模型变更情况,执行如下指令来进行数据迁移: ```bash python manage.py migrate ``` 此步会自动在数据库内建立相应的表格存储用户的令牌信息。 #### 获取访问令牌 登录到管理后台或者利用其他方式获取当前用户的个人访问令牌。可以通过发送POST请求至 `/api-token-auth/` 接口实现自动化流程,传入有效的凭证参数即可返回对应的 token 值。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值