简体   繁体   中英

Browser displaying Python code rather than executing it

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.

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 here are the screenshots related to the issues I am having.

1. Trying to run the app on flask

烧瓶错误 --> 内部服务器错误。服务器遇到内部错误,无法完成您的请求。服务器过载或应用程序出错。

2. Running the app from the Test.html form

显示 HTML if 语句。执行表单代码

3. Submitting the form

重定向到我的存档

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM