djangorestframework develop your own interface documentation

After studying for two weeks, finally worked out. Prior to read a lot of blog is to create a database to increase the number, but not what I want. So it does not use a database to increase the parameter.

Background: java because the company staff developed a swagger own interface, because the leadership is not said python should be able to interface it developed a swagger? So put this task to the newly recruited employees for three months,

First, set up the environment:

Software Version own version also tried a lot, and finally get a version for the company. The python version is 2.7.12. Here is probably the packages you want to install. Please order the installation.

pytz==2019.1
django==1.11.22

simplejson==3.16.0
djangorestframework == 3.9.4

MarkupSafe == 1.1.1
Jinja2==2.10.1

0.0.4 == coreschema
itypes 1.1.0 ==
uritemplate == 3.0.0

setuptools_scm==3.3.2
setuptools==40.8.0
pytest_runner==5.0
certifi==2019.6.16
urllib3==1.25.2
chrdet==3.0.3
requests==2.22.0

coreapi==2.3.3
openapi-codec==1.3.1
django-rest-swagger == 2.2.0

Second, create a public swagger_schema.py

#-*- coding:UTF-8 -*-

import yaml
from urlparse import urljoin
from rest_framework.compat import coreapi
from rest_framework.schemas.generators import is_custom_action
from rest_framework.schemas.inspectors import AutoSchema

class CustomViewSchema(AutoSchema):
    def get_link(self, path, method, base_url):

        if hasattr(self.view, 'action'):
            action = self.view.action
        else:
            action = ''

        if not is_custom_action(action):
            return super(CustomViewSchema, self).get_link(path, method, base_url)

        fields = self.get_path_fields(path, method)

        yaml_doc = None
        if self.view and self.view.__doc__:
            try:
                yaml_doc = yaml.load(self.view.__doc__)
            except:
                yaml_doc = None

        if yaml_doc and 'desc' in yaml_doc:
            desc = yaml_doc.get('desc', '')
            _method_desc = desc
            params = yaml_doc.get('parameters', [])
            for i in params:
                _name = i.get('name')
                _desc = i.get('desc')
                _required = i.get('required', True)
                _type = i.get('type')
                _location = i.get('location', 'query')
                f = coreapi.Field(
                    name=_name,
                    location=_location,
                    required=_required,
                    description=_desc,
                    type=_type
                )
                fields.append(f)
        else:
            _method_desc = self.view.__doc__ if self.view and self.view.__doc__ else ''
            fields += self.get_serializer_fields(path, method)

        fields += self.get_pagination_fields(path, method)
        fields += self.get_filter_fields(path, method)

        te = []
        for field in fields:
            if field.location in 'query':
                te.append(field.location)

        if fields and any(te):
            encoding = self.get_encoding(path, method)
        else:
            encoding = None

        if base_url and path.startswith('/'):
            path = path[1:]

        return coreapi.Link(
            url=urljoin(base_url, path),
            encoding=encoding,
            action=method.lower(),
            fields=fields,
            description=_method_desc
        )

 

Three, APP in their django project modifications views

from common.swagger_schema Import CustomViewSchema
 from rest_framework.decorators Import api_view, Schema 

@api_view ([ ' the GET ' ]) # POST method can be changed 
@schema (CustomViewSchema ()) 
DEF GetFiles (Request):
     "" " 
    desc: Get a a road 
    the parameters: 
    - name: SPATH 
      desc: remote address,     
      of the type: string # control type your input, such as strings, numbers and other 
      required: true # control parameter is a mandatory 
      location: query # can be modified to form and so on 

    - name: ip 
      desc: remote ip 
      of the type: String 
      required: to true 
      LOCATION: Query

    - name: port
      desc: 远程端口,
      type: string
      required: true
      location: query

    - name: username
      desc: 远程ip的用户
      type: string
      required: true
      location: query

    - name: password
      desc: 远程ip的密码
      type: string
      required: true
      location: query

    """
    spath = request.GET.get("spath",".")
    ip = request.GET.get("ip","")
    port = request.GET.get("port",22)
    username = request.GET.get("username","")
    password = request.GET.get("password","")
    return HttpResponse('get')

 

Four, setting modification under the project root directory

1, the increase in INSTALLED_APPS 

rest_framework_swagger 和 rest_framework


Five, url modify a project under the root directory
from rest_framework.schemas import get_schema_view
from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer
schema_view = get_schema_view(title='jobapp API',renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer])

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^app/', include(device_urls)),#这个是你自己创建的app 
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^api/', schema_view),
]

 



Do this step, use runsever should be able to swagger interface. However, so the company will continue to go down uwsgi used to start the project.
To use uwsgi need to configure the nginx.

Sixth, the implementation of python manage.py collectstatic to collect static from setting in INSTALLED_APPS.
There will be a directory collected_static. There are three files: ADMIN rest_framework rest_framework_swagger

seven modifications setting under the project root directory
= STATIC_URL '/ static /' 
STATIC_ROOT = the os.path.join (base_dir, 'collected_static')
STATICFILES_DIRS = (
the os.path.join (base_dir, "static"),

)
eight, the increase in file uwsgi.ini
static-map = /static=/home/appuser/jobapp/collected_static
 











Guess you like

Origin www.cnblogs.com/qyk1995/p/11201869.html