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
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'))
]
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/
结果
Authentication credentials were not provided.
# 这句话的意思是你没有登录