Django 自动生成api接口文档教程
作者:Op小剑 时间:2022-09-11 06:40:26
最近在写测试平台,需要实现一个节点服务器的api,正好在用django,准备使用djangorestframework插件实现。
需求
实现一个接口,在调用时,通过传递的参数,直接运行对应项目的自动化测试
环境
Python3.6 ,PyCharm,W7
项目结构
功能实现
流程
我们要做的就是实现以上流程
安装
pip install djangorestframework
pip install markdown
pip install django-filter # Filtering support
配置
INSTALLED_APPS = (
...
'rest_framework',
)
编写代码(本次代码不涉及数据库操作,只简单的写一个api)
①:打开AutoApi/Api/views.py 编写如下代码
from django.http import JsonResponse, HttpResponseNotAllowed, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from rest_framework import status
@csrf_exempt
def run_job(request):
# 判断请求头是否为json
if request.content_type != 'application/json':
# 如果不是的话,返回405
return HttpResponse('only support json data', status=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE)
# 判断是否为post 请求
if request.method == 'POST':
try:
# 解析请求的json格式入参
data = JSONParser().parse(request)
except Exception as why:
print(why.args)
else:
content = {'msg': 'SUCCESS'}
print(data)
# 返回自定义请求内容content,200状态码
return JsonResponse(data=content, status=status.HTTP_200_OK)
# 如果不是post 请求返回不支持的请求方法
return HttpResponseNotAllowed(permitted_methods=['POST'])
②:打开AutoApi/Api/urls.py 编写如下代码
from django.conf.urls import url
from Api import views
urlpatterns = [
url(r'^runJob/$',views.run_job),
]
③:打开AutoApi/AutoApi/urls.py 修改如下代码
ALLOWED_HOSTS = '*' # 修改为* 代码允许任意host
from django.conf.urls import url,include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^',include('Api.urls')),# 新增
]
④:启动服务
python manage.py runserver 0.0.0.0:8080
⑤:我们请求试试看
来源:https://blog.csdn.net/xie_0723/article/details/78219007
标签:Django,生成,api文档
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
sql server 2000阻塞和死锁问题的查看与解决方法
2024-01-20 01:46:45
MySQL如何通过Navicat实现远程连接
2024-01-13 23:07:07
![](https://img.aspxhome.com/file/2023/8/80018_0s.png)
Javascript查看大图功能代码实现
2024-04-22 13:03:46
JavaScript:ES2019 的新特性(译)
2024-04-10 16:16:57
python中星号变量的几种特殊用法
2021-03-20 10:57:50
使用Python AIML搭建聊天机器人的方法示例
2022-01-04 10:14:28
echarts图表设置宽度100%结果为100px的解决办法
2024-04-18 09:50:19
![](https://img.aspxhome.com/file/2023/0/136200_0s.png)
Python中利用sorted()函数排序的简单教程
2022-09-13 20:26:36
免费手机号码归属地API查询接口和PHP使用实例分享
2023-10-31 08:06:37
kali-linux 202202 安装w3af命令行版的详细过程
2023-07-14 01:34:01
如何使用VUE+faceApi.js实现摄像头拍摄人脸识别
2023-07-02 16:32:04
![](https://img.aspxhome.com/file/2023/8/139698_0s.png)
JavaScript输入邮箱自动提示实例代码
2024-02-27 03:01:43
详解MySQL中ALTER命令的使用
2024-01-26 12:27:25
numpy创建单位矩阵和对角矩阵的实例
2023-08-05 10:25:44
3段Python图像处理的实用代码的分享
2021-10-19 08:06:58
![](https://img.aspxhome.com/file/2023/7/75927_0s.png)
MySQL简单了解“order by”是怎么工作的
2024-01-16 10:52:41
![](https://img.aspxhome.com/file/2023/5/127565_0s.png)
ADO.NET 连接数据库字符串小结(Oracle、SqlServer、Access、ODBC)
2024-01-22 07:43:47
Python中range、np.arange和np.linspace的区别
2023-10-17 14:45:14
![](https://img.aspxhome.com/file/2023/5/64265_0s.png)
Python2随机数列生成器简单实例
2021-11-18 08:12:37
python中pip的使用和修改下载源的方法
2023-08-04 21:33:41