django rest-farme-work 的使用(1)

Django REST框架是一個用於構建Web API的強大且靈活的工具包python

您可能想要使用REST框架的一些緣由:django

  • 可瀏覽性
  • 身份認證
  • 支持ORM和非ORM的序列化
  • 良好的文檔支持

安裝初步

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

可選包:
可選包.pngapi

文件配置

在配置文件setting 中添加 APP以下圖markdown

INSTALLED_APPS = (
    ...
    'rest_framework',
)

在url 中添加路由以下架構

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

example (例子)

咱們來看看使用REST框架構建簡單模型支持的API的一個簡單例子。
咱們將建立一個讀寫API來訪問咱們項目用戶的信息。
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。這是咱們項目的根urls.py模塊:ide

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'))
]

打開 127.0.0.1:8080,能夠添加刪除,建立用戶

image.png

相關文章
相關標籤/搜索