简体   繁体   English

浏览器显示 Python 代码而不是执行它

[英]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.我已经使用 python 构建了一个数独求解器,今天我设置了一个 web 页面,供用户将数字输入到看起来像数独的网格中,然后单击求解。 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.因为数独页面很长,而且问题不是特定于页面,所以我在下面放了一些简化的 html 表单代码作为测试。

<!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.提交表单后,应将其发送到 Test.py 以便进行操作。 On the web I have found examples using both CGI and Flask to do this, but both times I have encountered the same problem.在 web 上,我找到了使用 CGI 和 Flask 执行此操作的示例,但两次我都遇到了同样的问题。

Adapted CGI Code from Posting html form values to python script :改编自将 html 表单值发布到 python 脚本的 CGI 代码:

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

Adapted Flask Code from https://opentechschool.github.io/python-flask/core/form-submission.html : 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).当我单击提交时,浏览器将我重定向到显示原始 python 代码的页面,而不执行任何代码(或者看起来如此)。 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.我通过简单地将方法属性切换为“get”并检查我被重定向的页面的 url 来验证它正在输出数据。 So the problem must be in the browser, or maybe in the python code?所以问题一定出在浏览器上,或者可能出在 python 代码中? 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.我在 CGI 或 Flask 方面都不是很有经验,事实上我是一般编码的初学者,但考虑到互联网上用于将 html 表单数据发送到 Z23EEEB4347BDD26BFC6B7EE9A3B5 的类似解决方案的数量是一件很简单的事情。

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? 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.对于处理表单提交的代码,您可能希望创建一个单一视图 function,这取决于 HTTP 请求方法,要么呈现表单,要么返回结果。

app.py应用程序.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.如果此代码接收到 GET 请求(您在浏览器中点击/端点),则会呈现index.html模板。
  • 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 .如果此代码收到 POST 请求(表单已提交),则获取num_input变量,然后将其作为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.现在对于一个模板,根据是否将num参数传递给render_template将显示该数字,或显示 HTML 表单。

Be sure to put this in the templates/ subdirectory:请务必将其放在templates/子目录中:

templates/index.html模板/索引.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:在开发服务器中使用flask run运行此命令,您应该会看到开发服务器启动:

 * 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:在浏览器中打开 URL 应该会出现一个输入框,然后提交应该显示:

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.要扩展它,您可以向表单添加更多输入字段,只需确保每个字段都有唯一的name属性。

<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. @v25 这里是与我遇到的问题相关的屏幕截图。

1. Trying to run the app on flask 1.尝试在flask上运行应用程序

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

2. Running the app from the Test.html form 2. 从 Test.html 表单运行应用程序

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

3. Submitting the form 3. 提交表格

重定向到我的存档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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