Natalie
Natalie

Reputation: 447

Handle POST request from Python index.html file

I am trying to create a webform from which I am doing some data processing from a Python script and writing it to an HTML file. I am using SimpleHTTPServer and discovered that it can't handle POST requests. I have been googling for hours and haven't been able to figure this out. Here is the relevant part of my code:

index = open("index.html", "w")
form_string = '''<form action="" method="post">
                  <center><input type="radio" name="radio" value="left">
                  <input type="radio" name="radio" value="middle">
                  <input type="radio" name="radio" value="right"></center>
                  <center><p><input type="submit" name="submit" value="Submit Decision"/></p></center>
                  </form>'''
index.write(form_string)

I tried using the following php snippet as a test to see if its working but I got an error saying that my SimpleHTTPServer can't handle POST requests.

php_string = '''<?php
                    echo .$_POST['radio'];
                 ?>
                 '''

index.write(php_string)

My overall goal is to simply store which button was clicked by the user in some sort of external file, and I figured the POST request would be the best way. Does anyone know how I could do this?

Upvotes: 0

Views: 942

Answers (1)

DDGG
DDGG

Reputation: 1241

I am not familar with the builtin SimpleHTTPServer, but it's for teaching purposes.

I'd recommand you use the well known micro-framework named Flask, maybe this is what you want:

from flask import Flask, request

app = Flask(__name__)


@app.route('/')
def index():
    return '''<form action="" method="post">
              <center><input type="radio" name="radio" value="left">
              <input type="radio" name="radio" value="middle">
              <input type="radio" name="radio" value="right"></center>
              <center><p><input type="submit" name="submit" value="Submit Decision"/></p></center>
              </form>'''


@app.route('/', methods=['POST'])
def post_abc():
    return 'radio: "%s", submit: "%s"' % (request.form['radio'], request.form['submit'])


if __name__ == '__main__':
    app.run(debug=True)

Visit http://localhost:5000 with your browser to test it.

You can install Flask via pip install flask.

Upvotes: 1

Related Questions