1

I have built a sudoku solver using python and today I set up a web page for the user to input numbers into a sudoku-looking grid and then click solve. This was done with a form and "solve" is the submit button. Because the sudoku page is long and the problem isn't specific to the page, I put some simplified html form code below as a test.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Test</title>
  </head>
  <body>
    <form id="sudoku" action="Test.py" method="post">
      <label for="num-input"> Enter a Number: </label>
        <input type="number" name="num-input">
      <label for="num-input"> Enter another Number: </label>
        <input type="number" name="num-input">
      <label for="num-input"> Enter a third Number: </label>
        <input type="number" name="num-input">
      <button type="submit" name="submit" form="sudoku"> Submit </button>
    </form>
  </body>
</html>

When the form is submitted it should be sent to Test.py in order to be manipulated. On the web I have found examples using both CGI and Flask to do this, but both times I have encountered the same problem.

Adapted CGI Code from Posting html form values to python script:

import cgi
form = cgi.FieldStorage()
numbers =  form.getvalue('num-input')

Adapted Flask Code from https://opentechschool.github.io/python-flask/core/form-submission.html:

from flask import request, redirect 

@app.route('/Test.py', methods = ['POST'])
    def signup():
        nums = request.form['num-input']
        print(nums)
        return redirect('/index.html')

I have tried both solutions and many others on my test form and I keep having one recurring issue. When I click submit, the browser redirects me to a page where is displays the raw python code without executing any of it (or so it seems). The form shouldn't be the problem; I verified it was outputting data by briefly switching the method attribute to "get" and checking the url of the page where I was redirected. So the problem must be in the browser, or maybe in the python code? I am not very experienced in either CGI or Flask and as a matter of fact I am a beginner at coding in general, but given the amount of similar solutions on the internet for sending html form data to python files I am assuming this is meant to be quite a straightforward matter.

As an added on question, where is the output of the python code meant to go if I didn't yet place it in another html page?

Thanks in advance for any help.

  • How are you running this app? It's rare to see raw python code rendered in the browser; this suggests you're serving the `.py` file with a conventional webserver. You need to have python installed, then install the flask library with a package manager like `pip`, allowing you to then launch the dev server with `flask run`... – v25 May 01 '20 at 22:02
  • I am running the app on chrome from a local host. I am simply opening the html test form and moving on from there. The page wasn't created with python through Flask, it is plain html (CSS and JavaScript in the actual sudoku app). I have python installed, it runs fine on terminal and so does flask. – Giacomo Saracchi May 01 '20 at 22:45
  • @v25 more details on my problems in the answer below. – Giacomo Saracchi May 03 '20 at 09:01

2 Answers2

0

I really want to help you out and you seem to have made some beginner mistakes so hopefully this answer is of some use:

For the code to handle a form submission, you probably want to create a single view function, which depending on the HTTP request method, either renders the form, or returns the result.

app.py

from flask import Flask, request, render_template 
app = Flask(__name__)

@app.route('/', methods = ['GET','POST'])
def index():
    if request.method == 'POST':
        num_input = request.form['num-input']
        return render_template('index.html', num = num_input)

    elif request.method == 'GET':
        return render_template('index.html')
  • If this code receives a GET request (you hit the / endpoint in the browser) then the index.html template is rendered.
  • If this code receives a POST request (the form was submitted) then the num_input variable is obtained and then passed back to the template as num.

Now for a template which, depending on whether or not the num argument was passed to render_template will either display that number, or display the HTML form.

Be sure to put this in the templates/ subdirectory:

templates/index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Test</title>
  </head>
  <body>
  {% if num %}
    The number you entered was: {{num}}
  {% else %}
    <form action="/" method="POST">
      <label for="num-input"> Enter a Number: </label>
        <input type="number" name="num-input" />
      <input type="submit" value="Submit"> 
    </form>
  {% endif %}
  </body>
</html>

Run this in the dev server with flask run, and you should see the dev server start:

 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Opening that URL in your browser should present you with a input box, and submitting should then display:

The number you entered was: 42 

To expand this you can add more input fields to the form, just ensure each has a unique name attribute.

<label for="num-input-two"> Enter another Number: </label>
<input type="number" name="num-input-two">
v25
  • 7,096
  • 2
  • 20
  • 36
  • thanks for your answer. I am having a couple of issues with it. I tired to run the app on flask after copying the bits of code above and it redirects me to "/" without executing any of the python. Moreover, it does not execute the if statement in the html but rather prints it on the screen as if it were text. – Giacomo Saracchi May 02 '20 at 09:47
  • @GiacomoSaracchi Can you post a screencap of this? – v25 May 02 '20 at 12:39
0

@v25 here are the screenshots related to the issues I am having.

1. Trying to run the app on flask

Flask error --> Internal Server Error. The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

2. Running the app from the Test.html form

HTML if statement displayed. Form code is executed

3. Submitting the form

Redirection to my archive

  • Hi. Can you also show what you see in the server console, when you get that "Internal Server Error" on the first screencap. There should be some debug output. If you launch the flask server in development mode: `FLASK_ENV=development flask run` this should also put that debug output in the browser, rather than just throwing an internal server error. As for the second screencap it would be helpful to know what's in the address bar on this one. It definately does not look like flask is serving this correctly. Perhaps also update this with your full code. – v25 May 03 '20 at 19:51
  • @v25 Update. Running the app with FLASK_ENV=development flask run I found the cause of the error. Flask doesn't recognise the HTML test file as a template. The error is: jinja2.exceptions.TemplateNotFound: /Users/user/Documents/Coding/Penguin Project/Templates/test1.html. I did put the HTML file in a templates folder, but I think it is not recognising it as a templates folder because I am running the file on my own machine, not on a web server that has a predefined templates folder. The full code really isn't relevant here, I am just trying to run a simple test to then expand my understanding. – Giacomo Saracchi May 03 '20 at 20:53
  • That error looks like you need to verify you can infact `cat /Users/user/Documents/Coding/Penguin Project/Templates/test1.html`. By default, unless you've specified otherwise, flask will look for templates in a `templates` subdirectory of your project (relevant to `app.py`). The webserver is irrelevant. If you run it locally with the dev server it should work fully. – v25 May 03 '20 at 21:02
  • So how do I tell flask that my templates are in that folder? Why would concatenating through terminal (cat /Users/user/Documents/Coding/Penguin Project/Templates/test1.html) help? – Giacomo Saracchi May 04 '20 at 08:51
  • The `TemplateNotFound` exception indicates that's the path it's looking for the template. `cat` that file to ensure it exists and has the correct contents. Flask looks in the `templates` folder (lowercase `t`) by default. The exception looks like it's going for `Templates` which suggested you'd overidden that. Don't tweak the default at the moment though: Just ensure there's a template where its looking was my point. – v25 May 04 '20 at 09:27
  • This is really basic stuff. As you're struggling, it's maybe worth a try with an existing basic template [something like this](https://gist.github.com/vulcan25/0e242c63afb9539e98869ad0f77974ab) then build on that? Feel free to comment against that gist, as this is getting a bit long for SO. – v25 May 04 '20 at 09:30