How can I run my python script from within a web browser and process the results?

20,709

Solution 1

First off, is your heart really set on it being Django? If not I'd advise that Django, whilst an awesome framework, is a bit much for your needs. You don't really need full stack.

You might want to look at Flask instead, which is a Python micro-framework (and dead easy to use)

However, since you asked about Django...

You can create a custom Django command (docs here) that calls your script, that can be called from a view as described in this question.

This has the added benefit of allowing you to run your script via the Django management.py script too. Which means you can keep any future scripts related to this project nice and uniform.

For getting the results of your script running, you can get them from the same bit of code that calls the command (the part described in the last link), or you can write large result sets to a file and process that file. Which you choose would really depend on the size of your result set and if you want to do anything else with it afterwards.

Solution 2

What nobody told me here, since I asked about Django:

What I really needed was a simple solution called WSGI. In order to make your python script accessible from the webbrowser you don't need Django, nor Flask. Much easier is a solution like Werkzeug or CherryPy.

Solution 3

After following the django tutorial, as suggested in a comment above, you'll want to create a view that has a text field and a submit button. On submission of the form, your view can run the script that you wrote (either imported from another file or copy and pasted; importing is probably preferable if it's complicated, but yours sounds like it's just a few lines), then return the number that you calculated. If you want to get really fancy, you could do this with some javascript and an ajax request, but if you're just starting, you should do it with a simple form first.

Share:
20,709
Sadık
Author by

Sadık

CV

Updated on January 25, 2020

Comments

  • Sadık
    Sadık over 4 years

    I have a written a short python script which takes a text and does a few things with it. For example it has a function which counts the words in the text and returns the number.

    How can I run this script within django? I want to take that text from the view (textfield or something) and return a result back to the view.

    I want to use django only to give the script a webinterface. And it is only for me, maybe for a few people, not for a big audience. No deployment.

    Edit: When I first thought the solution would be "Django", I asked for it explicitly. That was of course a mistake because of my ignorance of WSGI. Unfortunately nobody advised me of this mistake.