Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up Python server side with javascript client side

So there is already a Python program set up that runs on the console that I must build upon. I will be building a web GUI interface for the application using Javascript. How would I:

a. Go about handling the input/output of this Python program without touching the original code.

b. Go about sending console-line inputs to the Python program via Javascript calls. I've looked into raw HTTP requests/AJAX, but I'm not sure how exactly I would go about sending that as input to the Python program.

like image 552
Nikhil Unni Avatar asked Jul 30 '12 18:07

Nikhil Unni


People also ask

Can you mix Python and JavaScript together?

In this way, we can take into account the advantages of JavaScript and Python in the process of web development, and maximize the value of different programming languages. You can combine JavaScript and Python without using a database or developing a cumbersome API structure to improve development efficiency.

Can client side scripting use Python?

Besides, running Python scripts on the client-side has several benefits. We can get the full potential of Python without having to convert it into JS as we do in Tensorflow.

Can you use JavaScript for server-side?

Server-Side JavaScript is the use of the JavaScript language on servers. You know, those computers that are always on (and maybe online) running stuff, doing all kinds of work. Nowadays many of them have software, web servers, command-line applications, and other services that are written in JavaScript.

Is JavaScript server-side or client-side?

JavaScript is an important client-side scripting language and widely used in dynamic websites. The script can be embedded within the HTML or stored in an external file.


1 Answers

a. To handle input/output of the program: Pexpect. It's fairly easy to use, and reading some of the examples distributed with it should teach you enough to get the basics down.

b. Javascript interface:

Well, I use gevent and it's built-in WSGI server. (look up what a WSGI server (another) is). I should note that this program will keep a state, so you can manage your open sessions by returning a session ID to your javascript client and storing your pexpect session in a global variable or some other container so that you can complete the program's input and output across multiple independent AJAX requests. I leave that up to you, however, as that is not as simple.

All my example will do is put the POST request in some after clicking something of your choice. (it won't actually work because some of the variables are not set. Set them.)

Heres the relevant parts:

<!-- JavaScript -->
<script src="jquery.js"></script>
<script type="text/javascript">
function toPython(usrdata){
    $.ajax({
        url: "http://yoursite.com:8080",
        type: "POST",
        data: { information : "You have a very nice website, sir." , userdata : usrdata },
        dataType: "json",
        success: function(data) {
            <!-- do something here -->
            $('#somediv').html(data);
        }});
$("#someButton").bind('click', toPython(something));
</script>

Then the server:

# Python and Gevent
from gevent.pywsgi import WSGIServer
from gevent import monkey
monkey.patch_all() # makes many blocking calls asynchronous

def application(environ, start_response):
    if environ["REQUEST_METHOD"]!="POST": # your JS uses post, so if it isn't post, it isn't you
        start_response("403 Forbidden", [("Content-Type", "text/html; charset=utf-8")])
        return "403 Forbidden"
    start_response("200 OK", [("Content-Type", "text/html; charset=utf-8")])
    r = environ["wsgi.input"].read() # get the post data
    return r

address = "youraddresshere", 8080
server = WSGIServer(address, application)
server.backlog = 256
server.serve_forever()

If your program is Object Oriented, it'd be fairly easy to integrate this. EDIT: Doesn't need to be object oriented. and I have now included some Pexpect code

global d
d = someClass()
def application(environ, start_response):
    # get the instruction
    password = somethingfromwsgi # read the tutorials on WSGI to get the post stuff
    # figure out WHAT to do
    global d
    success = d.doSomething()
    # or success = funccall()
    prog = pexpect.spawn('python someprogram.py')
    prog.expect("Password: ")
    prog.sendline(password)
    i = prog.expect(["OK","not OK", "error"])
    if i==0:
        start_response("200 OK", [("Content-Type", "text/html; charset=utf-8")])
        return "Success"
    elif i==1:
        start_response("500 Internal Server Error", [("Content-Type", "text/html; charset=utf-8")])
        return "Failure"
    elif i==2:
        start_response("500 Internal Server Error", [("Content-Type", "text/html; charset=utf-8")])
        return "Error"

Another option I suggest is Nginx + uWSGI. If you would prefer that, I can give you some examples of that as well. It gives you the benefit of incorporating the webserver into the setup.

like image 55
Logan Avatar answered Sep 18 '22 11:09

Logan