Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to input data from a web page to Python script most efficiently

How can I most easily input data from a web page and pass it to a Python script?

I've been reading here and on other forums a lot about Python in connection with php or cgi, or even Tornado, Django, etc but I am quite puzzled what is the best solution for me.

I have a Python script that grabs data from the web, generates .html pages etc - when being run there is just one

userIn=str(raw_input())

which makes the script gather data based on the input in the terminal. I now only want this input to be coming from some sort of

<html>
<body>

<form action="test.php" method="get">
Name <input type="text" name="name" />
<input type="submit" />
</form>

</body>
</html> 

In the file test.php I have tried passing the value in any kind (proc_open, exec...) but I do not seem to get the connection between python and this form, on top of that I am not sure what's the best idea to pass python's output (some debugging-errors etc) back to the web-interface?!

Thanks a lot!

like image 786
birgit Avatar asked Aug 11 '26 18:08

birgit


2 Answers

I now managed it with the exec() command.

<html>
<body>

<form action="test.php" method="get">
<input type="text" name="name" />
<input type="submit" />
</form>

</body>
</html> 

test.php:

<?php
exec("python mypythonscript.py ".$name, $output);
?>
like image 180
birgit Avatar answered Aug 14 '26 10:08

birgit


To get a value from the form you could change action="test.php" to action="/where_you_hooked_your_webapp".

The code of the application could be:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def handle_input():
    userIn = request.args.get('name', 'default name goes here')
    # grab data from the web, prepare data for html template, etc
    return render_template('user.html', user=userIn, data=data)

To find out how you can deploy it see Flask Quickstart e.g., Apache with mod_wsgi.

like image 25
jfs Avatar answered Aug 14 '26 10:08

jfs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!