DjangorestFramework的学习记录

环境

Ubuntu18.04 LTS Django2.0

安装虚拟环境

pip install virtualenv

创建学习目录并进入

mkdir tutorial
cd tutorial

创建虚拟环境并启动

virtualenv env
source env/bin/activate

安装django和djangorestframework

pip install django
pip install djangorestframework

查看路径和目录结构

#pwd
#find .

第一次同步数据库

python3 manage.py migrate

创建一个超级用户备用,密码(password123)

# python3 manage.py createsuperuser --email [email protected] --username admin

序列化Serializers

创建一个名为 tutorial/quickstart/serializers.py的文件

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

打开 tutorial/quickstart/views.py 文件开始写代码

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from quickstart.serializers import UserSerializer, GroupSerializer #直接从app:quickstart里面导入模块即可


class UserViewSet(viewsets.ModelViewSet):
    """
    允许用户查看或编辑的API路径。
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    允许组查看或编辑的API路径。
    """
    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

现在我们在tutorial/urls.py中开始写连接API的URLs。

from django.contrib import admin
from django.urls import path,include
from rest_framework import routers
#from tutorial.quickstart import views 出错,下面的那种就可以
from quickstart import views

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

#使用自动URL路由链接我们的API
#另外,我们还包括支持浏览器浏览API的登录URL

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include(router.urls)),
    path('api-auth/',include('rest_framework.urls',namespace='rest_framework')),
]

注意:导入包的时候只需要在对应的app下面进行导入即可,不用写全路径名
Settings

我们也想设置一些全局设置。我们想打开分页,我们希望我们的API只能由管理员使用。设置模块都在 tutorial/settings.py 中。

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',	
    'rest_framework',
]

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

一切设置完成之后,就可以启动服务器了:

 python3 manage.py runserver 0.0.0.0:8000

使用工具访问:

curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/

或者使用httpie:

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

会得到下面的响应

HTTP/1.1 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Length: 101
Content-Type: application/json
Date: Mon, 08 Apr 2019 04:04:51 GMT
Server: WSGIServer/0.2 CPython/3.6.7
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN

[
    {
        "email": "[email protected]",
        "groups": [],
        "url": "http://127.0.0.1:8000/users/1/",
        "username": "admin"
    }
]

也可以使用浏览器访问http://127.0.0.1:8000/users/user,点击右上角登录admin即可。

你可能感兴趣的:(Python,Django)