环境准备
1.首先安装python,python安装详情这个可以查看官网的教程进行安装
2.安装python后,再通过命令pip install django
安装django,django安装完再进行创建项目(官网可查看安装和创建app步骤,这里不细说),然后再cmd里再输入命令:pip install djangorestframework
安装djangorestframework
这里介绍项目的路径
如下图(我们先在项目里创建一个Use_cases的app,然后创建一个urls.py
的文件和serializers.py文件,然后我们在views.py文件里编写我们的后端代码,serializers.py编写表单验证逻辑,models定义模块):
- models.py的代码如下:
from django.db import models
from django.core import validators#验证器
#Create your models here.
class UseTestOrm(models.Model):#签名加密配置
class Meta:
db_table = 'usertestorm'
ordering = ["-data_time"]
judge_edit = models.CharField(max_length=10, null=True) # 判断是否编辑的用例
http_file_py_name = models.TextField(null=True, default="") # py代码
- serializers.py文件代码如下
import re
from apps.HttprunerMan.Use_cases.models import UseTestOrm#导入环境orm
class PythonSeriaklizers(serializers.ModelSerializer):#python文件运行序列化
http_file_py_name = serializers.CharField(error_messages={"required": "代码不能为空!", "blank": "代码不能为空!"})
judge_edit = serializers.CharField(required=False, allow_blank=True, max_length=10,error_messages={"max_length": "judge_edit参数不能超过10个字符串!"}, default="yes")
class Meta:
model = UseTestOrm
fields=('http_file_py_name','judge_edit')
def validate_http_file_py_name(self,value):#对用例id表单验证
os_list="import(\s+)os"
#sys_list="import(\s+)sys"
subprocess_list = "import(\s+)subprocess"
true_list = "while(\s+)True"
#or(re.findall(true_list,value)!=[])
#or(re.findall(sys_list,value)!=[])
if (re.findall(os_list,value)!=[])or(re.findall(subprocess_list,value)!=[])or("exec" in value)or("pickle" in value):
raise ValidationError("代码上存在非法模块,请去掉os、exec、pickle、subprocess模块和while True方法")
return value
- views.py代码如下:
import subprocess#终端打印
import time
from django.conf import settings
from apps.HttprunerMan.Use_cases.serializers import PythonSeriaklizers
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class Test_python_view(APIView):#运行python代码
def post(self,request):#post请求
serializer = PythonSeriaklizers(data=request.data)
if serializer.is_valid(): # 表单验证通过执行下面代码
with transaction.atomic(): # 创建事物,保证py文件运行成功和py文件运行和删除成功,否则就回滚
save_is = transaction.savepoint()
all_obj,file_name="",""
try:
token1 = request.data.get("token")
if token1 == settings.SECRET_KEY:#验证传上来的token是否与django的密钥一直,这样保证安全问题
http_file_py_name= serializer.data.get("http_file_py_name")#获取代码
file_name = settings.MEDIA_ROOT + '\\' + str(int(time.time()))+".py"#生成py文件
f = open(file_name, "bw")#打开生成的py文件
#下面for循环把读取的数据,把读取的数据写到创建的py文件
for i in '{}'.format(str(http_file_py_name)):
f.write(i.encode())
f.close()#读取完成关闭文件
obj = subprocess.Popen('python {}'.format(file_name), shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)#这里是运行py文件的代码,stdout是获取运行该命令的正确信息,stderr是获取错误信息
try:
all_obj += obj.stdout.read().decode('gbk') + "\r\n" + obj.stderr.read().decode('gbk')#把获取的正确和错误信息进行组合
except Exception as e:
return Response({"all_result": str(e), "message": "成功", "code": "200"})#这里如果出现异常进行返回结果
os.remove(file_name)#删除该py文件这样防止产生垃圾文件
return Response({"all_result": all_obj, "message": "成功", "code": "200"})
else:#如果token校验错误就打印下面代码
return Response(data={"message": "token参数错误或为空!", "code": 400},status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
os.remove(file_name)
transaction.savepoint_rollback(save_is)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
- urls.py文件如下定义
from django.urls import path,re_path
from apps.HttprunerMan.Use_cases.views import Test_python_view,
from rest_framework.routers import DefaultRouter#导入这个模块
app_name="Use_cases"
urlpatterns=[
path("Test_python_view/",Test_python_view.as_view()),#python代码测试
]
- 项目里的urls.py文件代码:
from django.contrib import admin
from django.urls import path,include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('usetest/',include("apps.HttprunerMan.Use_cases.urls")),
]
-
settings.py文件需要在INSTALLED_APPS里添加app路径如下
-
最终使用p
ython manage.py runserver
命令启动项目,项目效果图如下