python - Flask 未激活功能

标签 python testing flask html

我一直在使用 python flask 和 html,为了创建一个小网站,(只是作为我放学后的爱好),我在 html 中创建了一个表单,并将其保存在模板文件夹中的项目。然后我还在 python 脚本中添加了一个函数,所以当点击网页的按钮时,它会将用户重定向回主页(index.html),但是当我测试了网页并点击了按钮时网页( flask 服务器正在运行)显示“400 错误请求”页面

Python 代码:

#Python code behind the website
import datetime
from flask import Flask, session, redirect, url_for, escape, request,    render_template
print ("started")
def Log(prefix, LogMessage):
    timeOfLog = datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S" + " : ")
    logFile = open("Log.log", 'a')
    logFile.write("[" + timeOfLog + "][" + prefix + "][" + LogMessage + "] \n")
    logFile.close()

app = Flask(__name__)

@app.route('/')
def my_form():
    print ("Acessed index")
    return render_template("index.html")

@app.route('/', methods=['POST'])
def my_form_post():
    text = request.form['text']#requests text from the text form
    processed_text = text #does nothing 
    user = "" #use poss in future to determin user
    logFile = open("MessageLog.msglog", 'a')#opens the message log file in append mode
    logFile.write(text + "\n")#stores the inputted message in the message log file
    logFile.close()
    #print (text)
    Log("User Message", (user + text))#uses the main log file to store messages aswell as errors
    print ("Accessing index")
    return render_template("test.html")

@app.route('/test', methods=['POST'])
def test():
    #text = request.form['text']
    print ("Test page function")
    #return "hello"
    return render_template("index.html") 

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

HTML代码: -->

<body>
<h1>Test Page</h1>
<form method="POST">
    <input type="submit" name="my-form" value="Send">
</form>

</body>

堆栈轨迹: stack trace

最佳答案

您需要将表单发布到正确的 URL:

<body>
<h1>Test Page</h1>
<form method="POST" action='/test'>
    <input type="submit" name="my-form" value="Send">
</form>
</body>

默认情况下,如果您不向 HTML 表单添加 action 属性,它只会对您当前所在的 URL 执行它定义的方法。您可以添加 action 属性来更改该行为。

您也可以使用 url_for() 函数来完成此操作。这更安全一些,因为 URL 往往比您的 View 方法名称更改得更频繁:

<body>
<h1>Test Page</h1>
<form method="POST" action="{{ url_for('test') }}">
    <input type="submit" name="my-form" value="Send">
</form>
</body>

您将 View 方法的名称(不是它的 URL)作为字符串传递给函数。小心使用正确的引号。

请注意,同一 URL 有 2 个 View 会让人有些困惑。通常像这样的事情是通过 YMMV 完成的,但请考虑将其用于您的应用程序:

@app.route('/someurl')
def some_view():
    if request.method == "POST":
        # handle POST
    else:
        # handle GET

关于python - Flask 未激活功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31455365/

相关文章:

python - 按列而不是按行替换列表中的字符

python - 如何使用 setup.py 安装先决条件

testing - 为什么smallCheck的 `Series`类在构造函数中有两个类型?

python - 如何刷新解释器列表缓存?

python - 如何在 Mac OSX 上确定文件的扩展属性和资源分支及其大小?

angularjs - 在使用 karma 进行测试时,**phantom js** 比 **chrome** 有什么用?

django - 在 Django 测试运行期间避免 404 警告?

python - 如何渲染和返回图以在 flask 中查看?

python - Elastic Beanstalk 无法识别文件的绝对路径,返回 FileNotFoundError

python - 带有 WTforms 的 RECaptcha 不会呈现