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
classTest_python_view(APIView):#運(yùn)行python代碼defpost(self,request):#post請求serializer = PythonSeriaklizers(data=request.data)if serializer.is_valid():# 表單驗(yàn)證通過執(zhí)行下面代碼with transaction.atomic():# 創(chuàng)建事物,保證py文件運(yùn)行成功和py文件運(yùn)行和刪除成功,否則就回滾save_is = transaction.savepoint()all_obj,file_name="",""try:token1 = request.data.get("token")if token1 == settings.SECRET_KEY:#驗(yàn)證傳上來的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循環(huán)把讀取的數(shù)據(jù),把讀取的數(shù)據(jù)寫到創(chuàng)建的py文件for i in'{}'.format(str(http_file_py_name)):f.write(i.encode())f.close()#讀取完成關(guān)閉文件obj = subprocess.Popen('python {}'.format(file_name), shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)#這里是運(yùn)行py文件的代碼,stdout是獲取運(yùn)行該命令的正確信息,stderr是獲取錯(cuò)誤信息try:all_obj += obj.stdout.read().decode('gbk')+"\r\n"+ obj.stderr.read().decode('gbk')#把獲取的正確和錯(cuò)誤信息進(jìn)行組合except Exception as e:return Response({"all_result":str(e),"message":"成功","code":"200"})#這里如果出現(xiàn)異常進(jìn)行返回結(jié)果os.remove(file_name)#刪除該py文件這樣防止產(chǎn)生垃圾文件return Response({"all_result": all_obj,"message":"成功","code":"200"})else:#如果token校驗(yàn)錯(cuò)誤就打印下面代碼return Response(data={"message":"token參數(shù)錯(cuò)誤或?yàn)榭?#xff01;","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#導(dǎo)入這個(gè)模塊app_name="Use_cases"
urlpatterns=[path("Test_python_view/",Test_python_view.as_view()),#python代碼測試]
項(xiàng)目里的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")),]