integrating python scripts with django

2019-05-23 02:19发布

问题:

I have written some test scripts in python which call some apis for a paritcular application and output the results to a database so I can use jasper to report on the results. Currently the scripts are run using a python interpreter, ie double click on the python file that has some parameters and variables modifed within the script that then initiates the tests. I would like to move towards a more user friendly interface so other people can use these test scripts without having to modify the python code. So I am thinking about using django and creating a web page that has check boxes, and if the check box is ticked, then it will execute that particular python test script or a text box that will pass the values to a given variable, for example. I have a few questions around how this might be achieved.

1 - would I need to implement the python code in to the django source code or can I call the python script from the web page served up by django?

2 - If I were to run this from a web page, how could I ensure that if the web page was closed, that the test would continue in the background.

3 - Is there a way to output the status of the test case to a web page and if the web page was closed, for the status to be availble if the web page was reopened?

Many thanks - oli

回答1:

If you have a python function you can call from a Django django view maybe with a form as parameter input. If you have long running processes you might want to consider a tip from here: How to start a long-running process from a Django view?

from mytests import testfunc

def test_parameter_view(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ParameterForm(request.POST)
        if form.is_valid():
            testfunc(form.cleaned_data['parameter'])   # <-- Here the actual testing happens
            return HttpResponseRedirect(reverse(test_result)) # Redirect after POST
    else:
        form = ParameterForm()

    return render_to_response('test.html', {
        'form': form,
    })

In your test_result view you can access the test result values from the database.

If the user closes the browser or not doesn't affect server processes that already have been started. And since you write your results to the database they are persistent and can be accessed any time after the test has finished.



回答2:

If you don't want to port over your scripts into django views, there is another way:

1 - Set up a form with all the options that you want passed to the script

2 - GET or POST the form params and save them to variables using var1 = request.POST['param1'], etc

3 - Use a module called subprocess to execute your script. http://docs.python.org/library/subprocess.html