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 djangorestframework
DEPRECATION: 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 Python
2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Collecting djangorestframework
Downloading https://files.pythonhosted.org/packages/1b/fe/fcebec2a98fbd1548da1c12ce8d7f634a02a9cce350833fa227a625ec624/djangorestframework-3.9.4-py2.py3-none-any.whl (911kB)
|████████████████████████████████| 921kB 19kB/s
Installing collected packages: djangorestframework
Successfully installed djangorestframework-3.9.4
WARNING: 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 list
DEPRECATION: 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 Python
2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Package Version
----------------------------- -------
astroid 1.6.6
autopep8 1.6.0
backports.functools-lru-cache 1.6.4
colorama 0.4.4
configparser 4.0.2
Django 1.11.29
djangorestframework 3.9.4
enum34 1.1.10
futures 3.3.0
isort 4.3.21
lazy-object-proxy 1.6.0
mccabe 0.6.1
pip 19.2.3
pycodestyle 2.8.0
pycparser 2.21
pylint 1.9.5
pythonnet 2.5.2
pytz 2021.3
setuptools 41.2.0
singledispatch 3.7.0
six 1.16.0
toml 0.10.2
wrapt 1.13.3
WARNING: 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.18
PS 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 list
DEPRECATION: 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.8
minio 7.1.3
pip 20.3.4
setuptools 44.1.1
urllib3 1.26.8
wheel 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 djangorestframework
DEPRECATION: 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.
Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
Collecting django
Downloading 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/s
Collecting djangorestframework
Downloading 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/s
Collecting pytz
Downloading https://mirrors.aliyun.com/pypi/packages/d3/e3/d9f046b5d1c94a3aeab15f1f867aa414f8ee9d196fae6865f1d6a0ee1a0b/pytz-2021.3-py2.py3-none-any.whl (503 kB)
|████████████████████████████████| 503 kB 5.4 MB/s
Installing collected packages: pytz, django, djangorestframework
Successfully 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 list
DEPRECATION: 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.8
Django 1.11.29
djangorestframework 3.9.4
minio 7.1.3
pip 20.3.4
pytz 2021.3
setuptools 44.1.1
urllib3 1.26.8
wheel 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_env
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2022/2/12 15:16 Include
d----- 2022/2/12 15:31 Lib
d----- 2022/2/12 15:16 libs
d----- 2022/2/15 10:21 my_django
d----- 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_env
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2022/2/12 15:16 Include
d----- 2022/2/12 15:31 Lib
d----- 2022/2/12 15:16 libs
d----- 2022/2/15 10:21 my_django
d----- 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-1340
D:.
│ manage.py
│
└─my_django
settings.py
urls.py
wsgi.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-1340
D:.
| db.sqlite3
| manage.py
|
\---my_django
settings.py
settings.pyc
urls.py
urls.pyc
wsgi.py
wsgi.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 8000
Performing 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:51
Django 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-1340
D:.
│ 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_literals
from django.shortcuts import render
# 导入 rest_framework 相关依赖
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import api_view
from 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-8
from django.contrib import admin
from django.conf.urls import url, include
from . import views
urlpatterns = [
url('hello/', views.hello)
]
将应用 my_rest_framework 的 urls 添加入 项目的 urls.py 中
"""my_django URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
# 添加 my_rest_framework 的 urls
url('', 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_literals
from django.shortcuts import render
# 导入 rest_framework 相关依赖
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import api_view
from 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 render
from rest_framework.views import APIView
from 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-8
from django.contrib import admin
from django.conf.urls import url, include
from . import views, api_views
urlpatterns = [
# 普通 @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-8
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework.decorators import list_route
import json
import uuid
class 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-8
from django.contrib import admin
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from . import views, api_views, view_sets
router = 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-yasg
DEPRECATION: 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.
Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
Collecting drf-yasg
Downloading 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/s
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.34
Downloading 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/s
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.1
Using cached https://mirrors.aliyun.com/pypi/packages/d5/35/a6eb45b4e2356fe688b21570864d4aa0d0a880ce387defe9c589112077f8/inflection-0.3.1.tar.gz (8.7 kB)
Collecting packaging
Downloading https://mirrors.aliyun.com/pypi/packages/3e/89/7ea760b4daa42653ece2380531c90f64788d979110a2ab51049d92f408af/packaging-20.9-py2.py3-none-any.whl (40 kB)
|████████████████████████████████| 40 kB 3.7 MB/s
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)
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.0
DEPRECATION: 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.
Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
Collecting ruamel-yaml-clib==0.2.0
Downloading 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/s
Installing collected packages: ruamel-yaml-clib
Successfully installed ruamel-yaml-clib
再次安装 drf-yasg
(python27_env) PS D:\OtherProjects\other\python\python_env27\python27_env\Scripts> pip install drf-yasg
DEPRECATION: 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.
Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
Collecting drf-yasg
Using 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.34
Using 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.1
Using cached https://mirrors.aliyun.com/pypi/packages/d5/35/a6eb45b4e2356fe688b21570864d4aa0d0a880ce387defe9c589112077f8/inflection-0.3.1.tar.gz (8.7 kB)
Collecting packaging
Using 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.2
Downloading 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/s
Requirement 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: inflection
Building wheel for inflection (setup.py) ... done
Created wheel for inflection: filename=inflection-0.3.1-py2-none-any.whl size=6095 sha256=19ee270a099848e8618da0194578c7ebc642d6fbbac392496f1c274550787b94
Stored in directory: c:\users\dell\appdata\local\pip\cache\wheels\7c\49\a1\498800189565b8e8708fed7db2fbdacf3844a38396f10a39e3
Successfully built inflection
Installing collected packages: ruamel.yaml, inflection, pyparsing, packaging, drf-yasg
Successfully 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 list
DEPRECATION: 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.8
chardet 4.0.0
coreapi 2.3.3
coreschema 0.0.4
Django 1.11.29
djangorestframework 3.9.4
drf-yasg 1.17.1
idna 2.10
inflection 0.3.1
itypes 1.2.0
Jinja2 2.11.3
MarkupSafe 1.1.1
minio 7.1.3
packaging 20.9
pip 20.3.4
pyparsing 2.4.7
pytz 2021.3
requests 2.27.1
ruamel.yaml 0.17.1
ruamel.yaml.clib 0.2.0
setuptools 44.1.1
six 1.16.0
uritemplate 4.1.0
urllib3 1.26.8
wheel 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 definition
INSTALLED_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-8
from unicodedata import name
from django.contrib import admin
from django.conf.urls import url, include
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from rest_framework.routers import DefaultRouter
from . import views, api_views, view_sets
schema_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 8000
Performing 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 wrapper
fn(*args, **kwargs)
File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run
self.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 check
include_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_checks
return 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_checks
new_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_config
return check_resolver(resolver)
File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver
return check_method()
File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\django\urls\resolvers.py", line 256, in check
for 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_patterns
patterns = 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_module
return 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 include
urlconf_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 permissions
File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\rest_framework\permissions.py", line 9, in <module>
from rest_framework import exceptions
File "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_repr
File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\rest_framework\compat.py", line 132, in <module>
import coreapi
File "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, utils
File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\coreapi\transports\__init__.py", line 3, in <module>
from coreapi.transports.http import HTTPTransport
File "D:\OtherProjects\other\python\python_env27\python27_env\lib\site-packages\coreapi\transports\http.py", line 13, in <module>
import uritemplate
File "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 19
uri: str,
^
SyntaxError: invalid syntax
对于报错,万分无赖,只好查看自己成功的项目的依赖包
requirement.txt
astroid==1.6.6
autopep8==1.6.0
backports.functools-lru-cache==1.6.4
certifi==2021.10.8
chardet==4.0.0
colorama==0.4.4
configparser==4.0.2
coreapi==2.3.3
coreschema==0.0.4
Django==1.11.29
djangorestframework==3.9.4
drf-yasg==1.17.1
enum34==1.1.10
futures==3.3.0
idna==2.10
inflection==0.3.1
isort==4.3.21
itypes==1.2.0
Jinja2==2.11.3
lazy-object-proxy==1.6.0
MarkupSafe==1.1.1
mccabe==0.6.1
packaging==20.9
pycodestyle==2.8.0
pycparser==2.21
pylint==1.9.5
pyparsing==2.4.7
pythonnet==2.5.2
pytz==2021.3
requests==2.27.1
ruamel.ordereddict==0.4.15
ruamel.yaml==0.16.13
ruamel.yaml.clib==0.2.2
singledispatch==3.7.0
six==1.16.0
toml==0.10.2
uritemplate==3.0.1
urllib3==1.26.8
wrapt==1.13.3
使用 pip install -r requirement.txt 安装
然后再执行 python .\manage.py runserver 8000
神奇的事情出现,居然可以了。。。。定位了几个小时的事情,突然就好了