Python三期爬虫作业python学习专题

Python django框架-代码测试助手

2017-11-02  本文已影响35人  chengcxy

一.需求

工作中除了写代码,最大的兴趣就是看开源代码了,好的简洁的代码拿过来首先得自己跑一遍,原来要么在终端vim编辑个脚本,要么在pycharm中在一个空文件里跑一下,联想到原来学Python时候,廖雪峰老师那里有一个代码助手,输入代码执行后会显示代码运行结果,就是这么一个功能.昨天去看怎么实现时候却发现如下面图1无法连接,经过看他代码,用的wsgi模块在本地39093端口开启web服务,调用解释器执行代码.


图1 无法连接

二.python代码测试助手 环境3.6.1 原理

前端两个文本域,一个按钮,按钮点击后 前端ajax请求后台接口,将输入的代码post提交给后台,由于我对wsgi不熟悉,采用的方式是文件读写的方式.代码后台拿到后,在static文件夹下生成一个index.py文件,将代码写入到这个脚本,然后调用系统命令将代码执行结果写入到指定结果文本文件,再去读取结果文件将结果传到视图函数里面渲染到前端,读取后删除结果文件,保留index.py 便于后续的点击下载脚本功能实现.
2.1 逻辑处理主代码

import os
from os import path
from maoyan.settings import BASE_DIR

class CodeTest(object):
    #传入参数 前端发送的代码
    def check_code_run(self,input_code):
        par_path = path.join(BASE_DIR,'static')
        os.chdir(par_path)
        pyfile = path.join(par_path,'index.py')
        relust_file =  path.join(par_path,'code_result.txt')
        #生成index.py
        with open(pyfile,'w',encoding='utf8') as fw:
            fw.write(input_code)
        with open(pyfile,'r',encoding='utf8') as py:
            pycode=py.read()
        # 交互模式执行 生成结果文件
        execute_code = 'python {} 2>&1 |tee code_result.txt'.format(pyfile)
        os.system(execute_code)
        #读取结果文件
        with open(relust_file,'r',encoding='utf8') as fr:
            contents = fr.readlines()
            code_run_result = '\n'.join(contents).replace('/Users/chengxinyao/django_project/maoyan/static/','')
        os.remove(relust_file)
        #返回代码路径,前端提交的代码(这一个可不返回)代码运行结果
        return pyfile,pycode,code_run_result

2.2 views视图

from django.shortcuts import render
from .code_test import CodeTest
from django.http import JsonResponse
# Create your views here.

def input_code(request):
    input_code = '''
y,m,d = map(str,'2017-10-09'.split('-'))
print(y,m,d)
'''
    return render(request, 'codetest/codetest.html', {'input_code': input_code})

def run(request):
    ct = CodeTest()
    item = {}
    input_code = request.POST['input_code']
    pyfile,py_code, code_run_result = ct.check_code_run(input_code)
    item['pyfile'] = pyfile
    item['input_code'] = py_code
    item['code_run_result'] = code_run_result
    return JsonResponse(item)

python代码测试助手
上一篇下一篇

猜你喜欢

热点阅读