很多内容官方文档都不是最新的,需要结合github上的doc,以及自己的实战经验进行分析
https://github.com/evonove/django-oauth-toolkit/blob/master/docs/rest-framework/getting_started.rst
Getting started
Django OAuth Toolkit provide a support layer for Django REST Framework. This tutorial is based on the Django REST Framework example and shows you how to easily integrate with it.
NOTE
The following code has been tested with django 1.7.7 and Django REST Framework 3.1.1
第一步:安装配置
Step 1: Minimal setup
Create a virtualenv and install following packages using pip…
pip install django-oauth-toolkit djangorestframework
A–自己新建一个项目,配置apps和rest框架
Start a new Django project and add ‘rest_framework’ and ‘oauth2_provider’ to your INSTALLED_APPS setting.
INSTALLED_APPS = (
'django.contrib.admin',
...
'oauth2_provider',
'rest_framework',
)
Now we need to tell Django REST Framework to use the new authentication backend. To do so add the following lines at the end of your settings.py module:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
)
}
第二步:创建简单的受oauth保护的api
Step 2: Create a simple API
Let’s create a simple API for accessing users and groups.
Here’s our project’s root urls.py module:
from django.conf.urls import url, include
from django.contrib.auth.models import User, Group
from django.contrib import admin
admin.autodiscover() # 高版本不需要
from rest_framework import permissions, routers, serializers, viewsets
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope
# first we define the serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:<