步骤:
安装:
sudo pip install djangorestframework
sudo pip install markdown
sudo pip install django-filter
或者直接从github克隆下来:
git clone git@github.com:encode/django-rest-framework.git
settings中配置:
INSTALLED_APPS = (
...
'rest_framework',
)
urls中配置
urlpatterns = [
...
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
Note that the URL path can be whatever you want, but you must include 'rest_framework.urls' with the 'rest_framework' namespace. You may leave out the namespace in Django 1.9+, and REST framework will set it for you.
示例:
在settings.py
中:
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_APPS
中。
我们就最好了写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.0.1:8000/
,查看你的users
API。
网友评论