django的rest_framwork框架

官方文档

https://www.django-rest-framework.org/#

安装

pip install djangorestframework
pip install markdown       # Markdown support for the browsable API.
pip install django-filter  # Filtering support

配置

Add ‘rest_framework’ to your INSTALLED_APPS setting.

INSTALLED_APPS = [
    ...
    'rest_framework',
]

If you’re intending to use the browsable API you’ll probably also want to add REST framework’s login and logout views. Add the following to your root urls.py file.

urlpatterns = [
    ...
    path('', include('rest_framework.urls'))
    # url(r'^api-auth/', include('rest_framework.urls'))
]

例子

REST框架API的任何全局设置都保存在一个名为REST_FRAMEWORK的配置字典中。首先在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'
    ]
}

现在我们已经准备好创建API了。这是我们项目的根url .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'))
]

从这里我们可以看到,视图和urls都被写道同一个文件里面了。这是官方为了给我们演示方便而采取的方式,实际开发会采用新建serializers的方式。请看我下一篇博文:
https://blog.csdn.net/weixin_43431593/article/details/107142415

你可能感兴趣的:(Django)