user3946530
user3946530

Reputation:

how to call python command from html page?

I want to call python command from my html page .

Code is :

<form class="form" action="" method="post" name="new-service" enctype=multipart/form-data>
      <div class="control-group">

          <div class="controls">
               <input id="Search" name="Search" type="text" placeholder="Search.. eg: moto g" class="form-control input-xlarge search-query center-display" required="">
   <!--  here i want to call python command  or function  -->

          </div>
     </div>

      </form>

and my python command is :

$ python main.py -s=bow    

here bow is get from input box .

Upvotes: 0

Views: 1816

Answers (2)

Dalen
Dalen

Reputation: 4236

Use jQuery to send a request to your python script on server that will be handled as a CGI/Fast CGI script or through WSGI (mod_wsgi for Apache) or mod_python (for Apache too).

Your Python script will receive input using query strings.

Client side example:

<html><head><title>TEST</title>
<script type="text/javascript" src="jquery.js"></script>
<script>

pyurl = "/cgi-bin/main.py"; // Just for example. It can be anything. Doesn't need to be Python at all
function callpy (argdict) {
    $.post(pyurl, argdict, function (data) {    
    // Here comes whatever you'll do with the Python's output.
    // For example:
    document.write(data);
    });
}
</script>
</head><body>
<!-- Now use it: -->
<a href="#" onclick='javascript:callpy({"s": "bow", "someother": "argument"});'>CLICK HERE FOR TEST!!!</a>
</body></html>

On server side (CGI just for example):

#! /usr/bin/env python
import cgi, cgitb
cgitb.enable()

print "Content-Type: text/html\n"
i = cgi.FieldStorage()
if i.has_key("s"):
    if i["s"].value=="bow": print "Yeeeeey!!!! I got 'bow'!!!<br>"
    else: print "Woops! I got", i["s"].value, "instead of 'bow'<br>"
else: print "Argument 's' not present!<br>"
print "All received arguments:"
for x in i.keys(): print x, "<br>"

Upvotes: 1

chaos
chaos

Reputation: 490

Directly from the UI you cannot call a command. That is backend specific. However, in the view that handles your form you can do something like:

from django.core.management import call_command
call_command('your_command_name', args, kwargs)

Check the documents page here for reference: https://docs.djangoproject.com/en/1.8/ref/django-admin/#call-command

Upvotes: 2

Related Questions