http://www.django-rest-framework.org/#
我们会创建一个读-写用户信息的api在我们的工程里。
所有REST framework API 的全局配置都放在一个单独的配置字典里面,字典名为REST_FRAMEWORK
。第一步把下面的代码加到settings
模块里面:
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
不要忘了确保你已经把 rest_framework
添加到了INSTALLED_APP
里面了。
我们现在已经准备好创建我们的api了。下面是你的工程的根urls.py
模块:
from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'is_staff')
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
现在你就可以在你的浏览器你面打开 http://127..0.1:8000/ 来打开你的API了,并且可以看你的新的‘users’API。