http://www.django-rest-framework.org/#
我們會創(chuàng)建一個讀-寫用戶信息的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'
]
}
不要忘了確保你已經(jīng)把 rest_framework添加到了INSTALLED_APP里面了。
我們現(xiàn)在已經(jīng)準(zhǔn)備好創(chuàng)建我們的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'))
]
現(xiàn)在你就可以在你的瀏覽器你面打開 http://127..0.1:8000/ 來打開你的API了,并且可以看你的新的‘users’API。