什么是django-rest-swagger?
用于Django REST框架的OpenAPI文档生成器,结合django-rest-framework可视化管理api。
环境需求
Python 2.7.15
Django 1.11.17
Django-rest-framework 3.9.0
Django-rest-swagger 2.2.0
安装
pip install django==1.11.17
pip install djangorestframework==3.9.0
pip install django-rest-swagger==2.2.0
配置
# urls.py
from rest_framework_swagger.views import get_swagger_view
schema_view = get_swagger_view(title='YwFuns API')
v1_api_patterns = [
url('v1/users/', include('User.api_urls', namespace='api-users')),
]
urlpatterns = [
url('api/', include(v1_api_patterns)),
url('api/docs/', schema_view, name="api-docs")
]
# settings.py
INSTALLED_APPS = (
"rest_framework",
"rest_framework_swagger",
"..."
)
SWAGGER_SETTINGS = {
'SECURITY_DEFINITIONS': {
"basic":{
'type': 'basic'
}
}
}
# User/api_urls.py
from django.conf.urls import include, url
from rest_framework import routers
from view import UserViewSet
route = routers.DefaultRouter()
route.register(r'users', UserViewSet, "user")
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
# User/view.py
from User.models import User
from rest_framework import viewsets
from .serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all().order_by('-last_login')
serializer_class = UserSerializer
# User/serializers.py
from User.models import User
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('username', 'nickname', 'email')
运行测试
python manage.py runserver 0.0.0.0:8000
Performing system checks...
System check identified no issues (0 silenced).
December 27, 2018 - 14:15:05
Django version 1.11.17, using settings 'mysite.settings'
Starting development server at http://0.0.0.0:8070/
Quit the server with CONTROL-C.
访问:http://127.0.0.1:8000/api/docs/
参考文档