标签:登录接口 应用 Staff color 数据 mis start taf migration
软件测试工程师:
打开pycharm
创建项目
在Terminal中运行python manage.py runserver
, 在浏览器中访问, 如果出现如下页面代表成功
# 在Terminal中创建子应用
python manage.py startapp users
# 进行数据库迁移
python manage.py makemigrations
python manage.py migrate
在CreateRestfulAPI/settings.py中添加如下配置:
# 将'rest_framework'和'users.apps.UsersConfig'加入到INSTALLED_APPS列表中
INSTALLED_APPS = [
# restframework子应用
'rest_framework',
# users子应用
'users.apps.UsersConfig',
]
# restframework的全局配置放在REST_FRAMEWORK字典中
REST_FRAMEWORK = {
# 使用Django自带permission_class来进行认证
# 为认证的用户只有读的权限
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
from django.contrib.auth.models import User
from rest_framework.serializers import HyperlinkedModelSerializer
# 创建序列化器
class UsersModelSerializer(HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'is_staff', 'is_active', 'last_login')
from rest_framework import viewsets
from django.contrib.auth.models import User
from users.serializers import UsersModelSerializer
# 定义视图集
class UsersViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UsersModelSerializer
from rest_framework.routers import DefaultRouter
from .views import UsersViewSet
# 创建DefaultRouter对象
router = DefaultRouter()
# 批量添加路由
router.register(r'users', UsersViewSet)
urlpatterns = [
]
urlpatterns += router.urls
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
# 添加restframework自带的登录接口路由
path('', include('rest_framework.urls', namespace='rest_framework')),
# 添加子路由
path('', include('users.urls')),
]
python manage.py runserver
测开大佬告诉你:如何5分钟快速创建restful风格的API接口-使用django restframework框架
标签:登录接口 应用 Staff color 数据 mis start taf migration
原文地址:https://www.cnblogs.com/keyou1/p/12072107.html