实现通过网页运行本地脚本,同时将结果反馈到网页上,保存到数据库内.
项目结构:
整体的思路是:表单提交信息,action内填写要转到的网页链接name(在urls.py内设置的):
然后它会执行与之对应的views.py内的函数:
1:再testscript.html写下表单,类型选择post,action内填写想要转到的链接名称.
<form method="post" action="{% url 'polls:scriptresult' %}">
{% csrf_token %}
<input type="text" name="script_name" placeholder="script_test">
<input type="text" name="parameter">
<input type="submit" value="提交">
</form>
2:在views.py内写处理表单传递过来的数据的函数,同时在models.py内创建用来存储相关数据的表格.
models.py内:
class ScriptResult(models.Model):
script_name = models.CharField(max_length=100)
script_result = models.CharField(max_length=200)
script_runtime = models.DateTimeField('run time', auto_now=True)
def __str__(self):
return self.script_name
这里假设脚本存放在同一路径D:\WebScript\目录下,且启动文件为main.py,目前这个目录下只有一个用来测试的脚本script_test,可以将两个字符串合并,当参数不符合条件时,输出info incorrect
views.py内的函数:
script_list = ['script_test']
def script_result(request):
# 获取表单传递过来的脚本名称和相关参数
script_name = request.POST.get('script_name')
parameter = request.POST.get('parameter')
# 如果脚本列表中有这个脚本,就开始处理,使用subprocess模块执行脚本,同时接受此命令的输出,将其存储进入数据库
if script_name in script_list:
do_something = subprocess.Popen(rf'python D:\WebScript\{script_name}\main.py {parameter}', stdout=subprocess.PIPE, shell=True)
script_re = do_something.stdout.read().decode().strip()
script_mysql = ScriptResult(script_name=script_name, script_result=script_re)
script_mysql.save()
curr_re = ScriptResult.objects.all()
return render(request, 'polls/script_result.html', {'path': script_name, 'result': script_re,
'mysql_script_result': curr_re})
else:
return HttpResponse('脚本名称错误,暂时没有这个脚本')
3:在urls.py内创建链接:
path('scirptresult/', views.script_result, name='scriptresult')
第一部分为浏览器搜索栏内显示的链接,这是在polls文件内,所以链接应该为:ip/polls/scriptresult/
第二个是引用的函数,第三个是html文件中填写的名字.
界面如下:
正确执行如下:
脚本不存在:
数据库数据:
Original: https://blog.csdn.net/Sodnrn/article/details/121853952
Author: Sodnrn
Title: Django笔记(3)
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/734909/
转载文章受原作者版权保护。转载请注明原作者出处!