Python 版本 2.7.18
在 Python 中有很多 RESTful Web 框架,如 Django REST framework,Flask-RESTful,FastAPI等等。fastapi 需要 Python 3.6+,本次环境不支持。。。
本次使用 Django rest framework
django-rest-framework https://www.django-rest-framework.org/
配置依赖
django,djangorestframework 等
C:\xiaohui\python-u8\demo\web\fastapi>pip install djangorestframeworkDEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-supportCollecting djangorestframeworkDownloading https://files.pythonhosted.org/packages/1b/fe/fcebec2a98fbd1548da1c12ce8d7f634a02a9cce350833fa227a625ec624/djangorestframework-3.9.4-py2.py3-none-any.whl (911kB)|████████████████████████████████| 921kB 19kB/sInstalling collected packages: djangorestframeworkSuccessfully installed djangorestframework-3.9.4WARNING: You are using pip version 19.2.3, however version 20.3.4 is available.You should consider upgrading via the 'python -m pip install --upgrade pip' command.C:\xiaohui\python-u8\demo\web\fastapi>C:\xiaohui\python-u8\demo\web\fastapi>C:\xiaohui\python-u8\demo\web\fastapi>pip listDEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-supportPackage Version----------------------------- -------astroid 1.6.6autopep8 1.6.0backports.functools-lru-cache 1.6.4colorama 0.4.4configparser 4.0.2Django 1.11.29djangorestframework 3.9.4enum34 1.1.10futures 3.3.0isort 4.3.21lazy-object-proxy 1.6.0mccabe 0.6.1pip 19.2.3pycodestyle 2.8.0pycparser 2.21pylint 1.9.5pythonnet 2.5.2pytz 2021.3setuptools 41.2.0singledispatch 3.7.0six 1.16.0toml 0.10.2wrapt 1.13.3WARNING: You are using pip version 19.2.3, however version 20.3.4 is available.You should consider upgrading via the 'python -m pip install --upgrade pip' command.C:\xiaohui\python-u8\demo\web\fastapi>
重新开始
环境 python 2.7.18 64bit
使用 virtualenv 创建的 python2.7.18 来测试 Django、django-rest-framework
# 激活python 虚拟环境 python2.7.18PS D:\OtherProjects\other\python\python_env27\python27_env\Scripts> .\activate(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\Scripts># 查看已安装的python 依赖(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\Scripts> pip listDEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality.Package Version---------- ---------certifi 2021.10.8minio 7.1.3pip 20.3.4setuptools 44.1.1urllib3 1.26.8wheel 0.37.1(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\Scripts># 安装 Django、djangorestframework(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\Scripts> pip install django djangorestframeworkDEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip canbe found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality.Looking in indexes: https://mirrors.aliyun.com/pypi/simple/Collecting djangoDownloading https://mirrors.aliyun.com/pypi/packages/49/49/178daa8725d29c475216259eb19e90b2aa0b8c0431af8c7e9b490ae6481d/Django-1.11.29-py2.py3-none-any.whl (6.9 MB)|████████████████████████████████| 6.9 MB 5.4 MB/sCollecting djangorestframeworkDownloading https://mirrors.aliyun.com/pypi/packages/1b/fe/fcebec2a98fbd1548da1c12ce8d7f634a02a9cce350833fa227a625ec624/djangorestframework-3.9.4-py2.py3-none-any.whl (911 kB)|████████████████████████████████| 911 kB 5.1 MB/sCollecting pytzDownloading https://mirrors.aliyun.com/pypi/packages/d3/e3/d9f046b5d1c94a3aeab15f1f867aa414f8ee9d196fae6865f1d6a0ee1a0b/pytz-2021.3-py2.py3-none-any.whl (503 kB)|████████████████████████████████| 503 kB 5.4 MB/sInstalling collected packages: pytz, django, djangorestframeworkSuccessfully installed django-1.11.29 djangorestframework-3.9.4 pytz-2021.3(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\Scripts># 查看已安装的 django、djangorestframework(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\Scripts> pip listDEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip canbe found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality.Package Version------------------- ---------certifi 2021.10.8Django 1.11.29djangorestframework 3.9.4minio 7.1.3pip 20.3.4pytz 2021.3setuptools 44.1.1urllib3 1.26.8wheel 0.37.1(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\Scripts>
创建 Django 项目 django-admin startproject my_django
# django-admin startproject my_django 创建项目 my_django# 注意项目名称只能是字母、数字、下划线,其它的该本版要报错(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env>django-admin startproject my_django# 查看看目录(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env> dir目录: D:\OtherProjects\other\python\python_env27\python27_envMode LastWriteTime Length Name---- ------------- ------ ----d----- 2022/2/12 15:16 Included----- 2022/2/12 15:31 Libd----- 2022/2/12 15:16 libsd----- 2022/2/15 10:21 my_djangod----- 2022/2/15 10:15 Scripts-a---- 2022/2/12 15:16 40 .gitignore-a---- 2022/2/12 15:16 294 pyvenv.cfg(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env># 查看目录(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env> dir目录: D:\OtherProjects\other\python\python_env27\python27_envMode LastWriteTime Length Name---- ------------- ------ ----d----- 2022/2/12 15:16 Included----- 2022/2/12 15:31 Libd----- 2022/2/12 15:16 libsd----- 2022/2/15 10:21 my_djangod----- 2022/2/15 10:15 Scripts-a---- 2022/2/12 15:16 40 .gitignore-a---- 2022/2/12 15:16 294 pyvenv.cfg# 进入项目(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env> cd .\my_django\# 查看结构(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\my_django> tree /F文件夹 PATH 列表卷序列号为 34D6-1340D:.│ manage.py│└─my_djangosettings.pyurls.pywsgi.py__init__.py(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\my_django>
题外话 tree 命令不显示文件
# 查看 tree 的帮助,Windows command /?(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\my_django> tree /?以图形显示驱动器或路径的文件夹结构。TREE [drive:][path] [/F] [/A]/F 显示每个文件夹中文件的名称。/A 使用 ASCII 字符,而不使用扩展字符。# tree 加上参数,就可以显示文件了(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\my_django> tree /F /A文件夹 PATH 列表卷序列号为 34D6-1340D:.| db.sqlite3| manage.py|\---my_djangosettings.pysettings.pycurls.pyurls.pycwsgi.pywsgi.pyc__init__.py__init__.pyc(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\my_django>
运行项目 python .\manage.py runserver 8000
(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\my_django> python .\manage.py runserver 8000Performing system checks...System check identified no issues (0 silenced).You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.Run 'python manage.py migrate' to apply them.February 15, 2022 - 10:35:51Django version 1.11.29, using settings 'my_django.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CTRL-BREAK.
访问服务 http://localhost:8000
访问 http://localhost:8000/admin,或者 http://localhost:8000
创建应用 python manage.py startapp my_rest_framework
# 创建应用 python .\manage.py startapp my_rest_framework(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\my_django> python .\manage.py startapp my_rest_framework# 查看结构 tree /F(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\my_django> tree /F文件夹 PATH 列表卷序列号为 34D6-1340D:.│ db.sqlite3│ manage.py│├─my_django│ settings.py│ settings.pyc│ urls.py│ urls.pyc│ wsgi.py│ wsgi.pyc│ __init__.py│ __init__.pyc│└─my_rest_framework│ admin.py│ apps.py│ models.py│ tests.py│ views.py│ __init__.py│└─migrations__init__.py(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\my_django>
将创建的应用 my_rest_framework 添加到 settings.py
修改 settings.py 文件,为 INSTALLED_APPS 追加 my_rest_framework
INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',"my_rest_framework",]
my_rest_framework 目录下修改 views.py
# -*- coding: utf-8 -*-from __future__ import unicode_literalsfrom django.shortcuts import render# 导入 rest_framework 相关依赖from rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework.decorators import api_viewfrom django.http import JsonResponse, HttpResponseNotAllowed, HttpResponse# Create your views here.@api_view(['GET'])def hello(request):if request.method == 'GET':content = "hello world"return JsonResponse(data=content, safe=False)
my_rest_framework 目录下创建 urls.py
#!/usr/bin/python# coding=utf-8from django.contrib import adminfrom django.conf.urls import url, includefrom . import viewsurlpatterns = [url('hello/', views.hello)]
将应用 my_rest_framework 的 urls 添加入 项目的 urls.py 中
"""my_django URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see:https://docs.djangoproject.com/en/1.11/topics/http/urls/Examples:Function views1. Add an import: from my_app import views2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')Class-based views1. Add an import: from other_app.views import Home2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')Including another URLconf1. Import the include() function: from django.conf.urls import url, include2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))"""from django.conf.urls import url, includefrom django.contrib import adminurlpatterns = [url(r'^admin/', admin.site.urls),# 添加 my_rest_framework 的 urlsurl('', include("my_rest_framework.urls")),]
接着就是 python manage.py runserver 8000,然后 postman 访问 http://localhost:8000/hello/
其实存在三种方式实现 restful 接口
方式一:上例中的 api_view 注解
# -*- coding: utf-8 -*-from __future__ import unicode_literalsfrom django.shortcuts import render# 导入 rest_framework 相关依赖from rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework.decorators import api_viewfrom django.http import JsonResponse, HttpResponseNotAllowed, HttpResponse# Create your views here.@api_view(['GET'])def hello(request):if request.method == 'GET':content = "hello world"return JsonResponse(data=content, safe=False)
方式二:继承 APIView 方式
api_view.py
# -*- coding: UTF-8 -*-'''django rest framework 的 APIView 实现 restful api'''from django.shortcuts import renderfrom rest_framework.views import APIViewfrom rest_framework.response import Response# Create your views here.class MyApiView(APIView):'''使用 APIView 方式实现 restful 接口'''def get(self, request):a = request.GET['a']res = {'code': 100,'data': a,'msg': 'success, get',}return Response(res)def post(self, request):a = request.GET['a']res = {'code': 100,'data': a,'msg': 'success, post',}return Response(res)def delete(self, request):a = request.GET['a']res = {'code': 100,'data': a,'msg': 'success,delete',}return Response(res)def put(self, request):a = request.GET['a']res = {'code': 100,'data': a,'msg': 'success, put',}return Response(res)
修改应用的 urls.py
#!/usr/bin/python# coding=utf-8from django.contrib import adminfrom django.conf.urls import url, includefrom . import views, api_viewsurlpatterns = [# 普通 @api_view 方式url('hello/', views.hello),# PAIView 方式url('apiview/', api_views.MyApiView.as_view()),]
注意,访问时候需要加上末尾的 / , eg: http://localhost:8000/apiview/?a=1
方式三:viewsets,继承 viewsets.ModelViewSet
view_sets.py
#!/usr/bin/python# coding=utf-8from django.shortcuts import renderfrom rest_framework.response import Responsefrom rest_framework import viewsetsfrom rest_framework.decorators import list_routeimport jsonimport uuidclass DemoViewSets(viewsets.ModelViewSet):'''使用 viewsets 来做 restful'''@list_route(methods=['GET',],)def get(self, request):data = json.loads(request.body)print(data)res = {'code': '100','msg': 'success get','data': data,}return Response(data=res)@list_route(methods=['PUT',],)def get(self, request):data = json.loads(request.body)print(data)res = {'code': '100','msg': 'success put','data': data,}return Response(data=res)@list_route(methods=['POST',],)def get(self, request):data = json.loads(request.body)print(data)res = {'code': '100','msg': 'success post','data': data,}return Response(data=res)@list_route(methods=['DELETE',],)def get(self, request):data = json.loads(request.body)print(data)res = {'code': '100','msg': 'success delete','data': data,}return Response(data=res)
修改应用中的 urls.py
#!/usr/bin/python# coding=utf-8from django.contrib import adminfrom django.conf.urls import url, includefrom rest_framework.routers import DefaultRouterfrom . import views, api_views, view_setsrouter = DefaultRouter()router.register(prefix=r'', viewset=view_sets.DemoViewSets, base_name='view_sets_demo')urlpatterns = [# 普通 @api_view 方式url('hello/', views.hello),# PAIView 方式url('apiview/', api_views.MyApiView.as_view()),# viewsets 方式url('viewsets/', include(router.urls)),]
访问的路径是:http://localhost:8000/viewsets/get/?a=1
有点没搞懂 请求要加上方法名,可是改变请求方式,居然也能成功?难道说每个方法可以通用于任意的请求方式?
swagger 加入 drf_yasg
安装 drf-yasg
出错
(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\Scripts> pip install drf-yasgDEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip canbe found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality.Looking in indexes: https://mirrors.aliyun.com/pypi/simple/Collecting drf-yasgDownloading https://mirrors.aliyun.com/pypi/packages/18/de/729c403c2ccfef3680790c2cb5460b7bdf93457586f09d5c15a9e5da450f/drf_yasg-1.17.1-py2.py3-none-any.whl (1.1 MB)|████████████████████████████████| 1.1 MB 4.3 MB/sRequirement already satisfied: six>=1.10.0 in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from drf-yasg) (1.16.0)Requirement already satisfied: coreapi>=2.3.3 in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from drf-yasg) (2.3.3)Requirement already satisfied: Django>=1.11.7 in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from drf-yasg) (1.11.29)Collecting ruamel.yaml>=0.15.34Downloading https://mirrors.aliyun.com/pypi/packages/65/e9/494f4a4ae771028900ff085d41f39c7f117b9e839ad8c15c2101ca4e16f1/ruamel.yaml-0.17.1-py2.py3-none-any.whl (101 kB)|████████████████████████████████| 101 kB 2.8 MB/sRequirement already satisfied: uritemplate>=3.0.0 in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from drf-yasg) (4.1.0)Requirement already satisfied: djangorestframework>=3.8 in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from drf-yasg) (3.9.4)Requirement already satisfied: coreschema>=0.0.4 in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from drf-yasg) (0.0.4)Collecting inflection>=0.3.1Using cached https://mirrors.aliyun.com/pypi/packages/d5/35/a6eb45b4e2356fe688b21570864d4aa0d0a880ce387defe9c589112077f8/inflection-0.3.1.tar.gz (8.7 kB)Collecting packagingDownloading https://mirrors.aliyun.com/pypi/packages/3e/89/7ea760b4daa42653ece2380531c90f64788d979110a2ab51049d92f408af/packaging-20.9-py2.py3-none-any.whl (40 kB)|████████████████████████████████| 40 kB 3.7 MB/sRequirement already satisfied: requests in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from coreapi>=2.3.3->drf-yasg) (2.27.1)Requirement already satisfied: itypes in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from coreapi>=2.3.3->drf-yasg) (1.2.0)Requirement already satisfied: pytz in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from Django>=1.11.7->drf-yasg) (2021.3)Collecting ruamel.yaml.clib>=0.1.2; platform_python_implementation == "CPython" and python_version < "3.10"Using cached https://mirrors.aliyun.com/pypi/packages/b7/81/c04fb9be62657d4dce8aa2d99fde258a3af1cd77ec72af525593e9560127/ruamel.yaml.clib-0.2.4.tar.gz (180 kB)ERROR: Command errored out with exit status 1:command: 'D:\OtherProjects\other\python\python_env27\python27_env\Scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'c:\\users\\dell\\appdata\\local\\temp\\pip-install-hezagj\\ruamel-yaml-clib\\setup.py'"'"'; __file__='"'"'c:\\users\\dell\\appdata\\local\\temp\\pip-install-hezagj\\ruamel-yaml-clib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'c:\users\dell\appdata\local\temp\pip-pip-egg-info-ivur0p'cwd: c:\users\dell\appdata\local\temp\pip-install-hezagj\ruamel-yaml-clib\Complete output (1 lines):minimum python version(s): [(3, 5)]----------------------------------------ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\Scripts>
上述错误时 ruamel-yaml-clib 安装失败。只好晚上查询资料,ruamel-yaml-clib==0.2.0 的支持 python27 64bit的。那么手动安装一下吧 pip install ruamel-yaml-clib==0.2.0
安装 ruamel-yaml-clib==0.2.0
(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\Scripts> pip install ruamel-yaml-clib==0.2.0DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip canbe found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality.Looking in indexes: https://mirrors.aliyun.com/pypi/simple/Collecting ruamel-yaml-clib==0.2.0Downloading https://mirrors.aliyun.com/pypi/packages/97/f4/98dc93e36bfdaefa8edf5183fbf14a00439f48e5cd301e7c2954854b11c2/ruamel.yaml.clib-0.2.0-cp27-cp27m-win_amd64.whl (115 kB)|████████████████████████████████| 115 kB 3.1 MB/sInstalling collected packages: ruamel-yaml-clibSuccessfully installed ruamel-yaml-clib
再次安装 drf-yasg
(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\Scripts> pip install drf-yasgDEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip canbe found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality.Looking in indexes: https://mirrors.aliyun.com/pypi/simple/Collecting drf-yasgUsing cached https://mirrors.aliyun.com/pypi/packages/18/de/729c403c2ccfef3680790c2cb5460b7bdf93457586f09d5c15a9e5da450f/drf_yasg-1.17.1-py2.py3-none-any.whl (1.1 MB)Requirement already satisfied: six>=1.10.0 in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from drf-yasg) (1.16.0)Requirement already satisfied: coreapi>=2.3.3 in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from drf-yasg) (2.3.3)Requirement already satisfied: Django>=1.11.7 in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from drf-yasg) (1.11.29)Collecting ruamel.yaml>=0.15.34Using cached https://mirrors.aliyun.com/pypi/packages/65/e9/494f4a4ae771028900ff085d41f39c7f117b9e839ad8c15c2101ca4e16f1/ruamel.yaml-0.17.1-py2.py3-none-any.whl (101 kB)Requirement already satisfied: uritemplate>=3.0.0 in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from drf-yasg) (4.1.0)Requirement already satisfied: djangorestframework>=3.8 in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from drf-yasg) (3.9.4)Requirement already satisfied: coreschema>=0.0.4 in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from drf-yasg) (0.0.4)Collecting inflection>=0.3.1Using cached https://mirrors.aliyun.com/pypi/packages/d5/35/a6eb45b4e2356fe688b21570864d4aa0d0a880ce387defe9c589112077f8/inflection-0.3.1.tar.gz (8.7 kB)Collecting packagingUsing cached https://mirrors.aliyun.com/pypi/packages/3e/89/7ea760b4daa42653ece2380531c90f64788d979110a2ab51049d92f408af/packaging-20.9-py2.py3-none-any.whl (40 kB)Requirement already satisfied: requests in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from coreapi>=2.3.3->drf-yasg) (2.27.1)Requirement already satisfied: itypes in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from coreapi>=2.3.3->drf-yasg) (1.2.0)Requirement already satisfied: pytz in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from Django>=1.11.7->drf-yasg) (2021.3)Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == "CPython" and python_version < "3.10" in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from ruamel.yaml>=0.15.34->drf-yasg) (0.2.0)Requirement already satisfied: jinja2 in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from coreschema>=0.0.4->drf-yasg) (2.11.3)Collecting pyparsing>=2.0.2Downloading https://mirrors.aliyun.com/pypi/packages/8a/bb/488841f56197b13700afd5658fc279a2025a39e22449b7cf29864669b15d/pyparsing-2.4.7-py2.py3-none-any.whl (67 kB)|████████████████████████████████| 67 kB 3.3 MB/sRequirement already satisfied: chardet<5,>=3.0.2; python_version < "3" in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from requests->coreapi>=2.3.3->drf-yasg) (4.0.0)Requirement already satisfied: idna<3,>=2.5; python_version < "3" in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from requests->coreapi>=2.3.3->drf-yasg) (2.10)Requirement already satisfied: urllib3<1.27,>=1.21.1 in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from requests->coreapi>=2.3.3->drf-yasg) (1.26.8)Requirement already satisfied: certifi>=2017.4.17 in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from requests->coreapi>=2.3.3->drf-yasg) (2021.10.8)Requirement already satisfied: MarkupSafe>=0.23 in d:\otherprojects\other\python\python_env27\python27_env\lib\site-packages (from jinja2->coreschema>=0.0.4->drf-yasg) (1.1.1)Building wheels for collected packages: inflectionBuilding wheel for inflection (setup.py) ... doneCreated wheel for inflection: filename=inflection-0.3.1-py2-none-any.whl size=6095 sha256=19ee270a099848e8618da0194578c7ebc642d6fbbac392496f1c274550787b94Stored in directory: c:\users\dell\appdata\local\pip\cache\wheels\7c\49\a1\498800189565b8e8708fed7db2fbdacf3844a38396f10a39e3Successfully built inflectionInstalling collected packages: ruamel.yaml, inflection, pyparsing, packaging, drf-yasgSuccessfully installed drf-yasg-1.17.1 inflection-0.3.1 packaging-20.9 pyparsing-2.4.7 ruamel.yaml-0.17.1(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\Scripts>
查看安装的 package
(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\Scripts> pip listDEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip canbe found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality.Package Version------------------- ---------certifi 2021.10.8chardet 4.0.0coreapi 2.3.3coreschema 0.0.4Django 1.11.29djangorestframework 3.9.4drf-yasg 1.17.1idna 2.10inflection 0.3.1itypes 1.2.0Jinja2 2.11.3MarkupSafe 1.1.1minio 7.1.3packaging 20.9pip 20.3.4pyparsing 2.4.7pytz 2021.3requests 2.27.1ruamel.yaml 0.17.1ruamel.yaml.clib 0.2.0setuptools 44.1.1six 1.16.0uritemplate 4.1.0urllib3 1.26.8wheel 0.37.1(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\Scripts>
使用 drf-yasg
参考:https://github.com/axnsan12/drf-yasg
https://drf-yasg.readthedocs.io/en/stable/readme.html
修改 settings.py 加入 drf_yasg
# Application definitionINSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',"my_rest_framework","drf_yasg",]
修改项目的 urls.py
#!/usr/bin/python# coding=utf-8from unicodedata import namefrom django.contrib import adminfrom django.conf.urls import url, includefrom rest_framework import permissionsfrom drf_yasg.views import get_schema_viewfrom drf_yasg import openapifrom rest_framework.routers import DefaultRouterfrom . import views, api_views, view_setsschema_view = get_schema_view(info=openapi.Info(title="123",default_version='v1',description="def-yasg Test description",terms_of_service="https://www.google.com/policies/terms/",contact=openapi.Contact(email="xuxiaohuimail@163.com", name="123",),license=openapi.License(name="BSD License"),),public=True,permission_classes=[permissions.AllowAny,],)router = DefaultRouter()router.register(prefix=r'', viewset=view_sets.DemoViewSets, base_name='view_sets_demo')urlpatterns = [# swagger 相关的url# url(r'swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),# url (r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),# url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),# 普通 @api_view 方式url('hello/', views.hello),# PAIView 方式url('apiview/', api_views.MyApiView.as_view()),# viewsets 方式url('viewsets/', include(router.urls)),]
悲愤的事情发生了,启动报错:
(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\my_django> python .\manage.py runserver 8000Performing system checks...Unhandled exception in thread started by <function wrapper at 0x0000000004718A58>Traceback (most recent call last):File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\django\utils\autoreload.py", line 228, in wrapperfn(*args, **kwargs)File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_runself.check(display_num_errors=True)File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\django\core\management\base.py", line 359, in checkinclude_deployment_checks=include_deployment_checks,File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\django\core\management\base.py", line 346, in _run_checksreturn checks.run_checks(**kwargs)File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\django\core\checks\registry.py", line 81, in run_checksnew_errors = check(app_configs=app_configs)File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_configreturn check_resolver(resolver)File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolverreturn check_method()File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\django\urls\resolvers.py", line 256, in checkfor pattern in self.url_patterns:File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\django\utils\functional.py", line 35, in __get__res = instance.__dict__[self.name] = self.func(instance)File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\django\urls\resolvers.py", line 407, in url_patternspatterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\django\utils\functional.py", line 35, in __get__res = instance.__dict__[self.name] = self.func(instance)File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\django\urls\resolvers.py", line 400, in urlconf_modulereturn import_module(self.urlconf_name)File "D:\devTools\Python\Python27\lib\importlib\__init__.py", line 37, in import_module__import__(name)File "D:\OtherProjects\other\python\python_env27\python27_env\my_django\my_django\urls.py", line 21, in <module>url('', include("my_rest_framework.urls")),File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\django\conf\urls\__init__.py", line 50, in includeurlconf_module = import_module(urlconf_module)File "D:\devTools\Python\Python27\lib\importlib\__init__.py", line 37, in import_module__import__(name)File "D:\OtherProjects\other\python\python_env27\python27_env\my_django\my_rest_framework\urls.py", line 7, in <module>from rest_framework import permissionsFile "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\rest_framework\permissions.py", line 9, in <module>from rest_framework import exceptionsFile "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\rest_framework\exceptions.py", line 18, in <module>from rest_framework.compat import unicode_to_reprFile "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\rest_framework\compat.py", line 132, in <module>import coreapiFile "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\coreapi\__init__.py", line 2, in <module>from coreapi import auth, codecs, exceptions, transports, utilsFile "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\coreapi\transports\__init__.py", line 3, in <module>from coreapi.transports.http import HTTPTransportFile "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\coreapi\transports\http.py", line 13, in <module>import uritemplateFile "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\uritemplate\__init__.py", line 28, in <module>from uritemplate.api import (File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\uritemplate\api.py", line 19uri: str,^SyntaxError: invalid syntax
对于报错,万分无赖,只好查看自己成功的项目的依赖包
requirement.txt
astroid==1.6.6autopep8==1.6.0backports.functools-lru-cache==1.6.4certifi==2021.10.8chardet==4.0.0colorama==0.4.4configparser==4.0.2coreapi==2.3.3coreschema==0.0.4Django==1.11.29djangorestframework==3.9.4drf-yasg==1.17.1enum34==1.1.10futures==3.3.0idna==2.10inflection==0.3.1isort==4.3.21itypes==1.2.0Jinja2==2.11.3lazy-object-proxy==1.6.0MarkupSafe==1.1.1mccabe==0.6.1packaging==20.9pycodestyle==2.8.0pycparser==2.21pylint==1.9.5pyparsing==2.4.7pythonnet==2.5.2pytz==2021.3requests==2.27.1ruamel.ordereddict==0.4.15ruamel.yaml==0.16.13ruamel.yaml.clib==0.2.2singledispatch==3.7.0six==1.16.0toml==0.10.2uritemplate==3.0.1urllib3==1.26.8wrapt==1.13.3
使用 pip install -r requirement.txt 安装
然后再执行 python .\manage.py runserver 8000
神奇的事情出现,居然可以了。。。。定位了几个小时的事情,突然就好了
