python django rest framework 快速入门

安装环境

pip install django
pip install djangorestframework
pip install pygments # 代码高亮

创建项目

1.使用ide开发工具创建项目

2. 使用命令

添加数据库配置

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': "my_db",
        'USER': "root",
        'PASSWORD': "",
        'HOST': "",
        'PORT':'3306',
    }
}

同步数据库并创建用户

# 同步数据库
python manage.py migrate
# 创建用户
python manage.py createsuperuser

定义序列化

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

视图

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端点
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    允许查看或编辑组的API端点。 
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

urls配置

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)

# 使用自动URL路由来连接我们的API。
# 此外,我们包括登录网址为浏览器API。
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

settings配置文件修改

INSTALLED_APPS = (
    ...
    'rest_framework',
)

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

启动项目并访问

# 可以使用工具启动,也可以使用如下命令启动
python manage.py runserver

访问 http://127.0.0.1:8000/users/
结果
python django rest framework 快速入门_第1张图片

Authentication credentials were not provided.
# 这句话的意思是你没有登录

点击右上角的登录按钮log in,使用’同步数据库并创建用户’中创建的用户登录,然后在访问
python django rest framework 快速入门_第2张图片

你可能感兴趣的:(django,django)