python - 方法不允许 flask 错误 405

标签 python forms flask

我正在开发一个 flask 注册表,我收到一个错误:

error 405 method not found.

代码:

import os
# Flask
from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash, Markup, send_from_directory, escape
from werkzeug import secure_filename

from cultura import app

# My app
from include import User

@app.route('/')
def index():
    return render_template('hello.html')

@app.route('/registrazione', methods=['POST']) 
def registration():
    if request.method == 'POST':
        username= request.form.username.data
        return render_template('registration.html', username=username)
    else :
        return render_template('registration.html')

registration.html:

<html>
<head> <title>Form di registrazione </title>
 </head> 

    <body>
    {{ username }}
    <form id='registration' action='/registrazione' method='post'>
    <fieldset >
    <legend>Registrazione utente</legend>
    <input type='hidden' name='submitted' id='submitted' value='1'/>
    <label for='name' >Nome: </label> 
    <input type='text' name='name' id='name' maxlength="50" /> <br>
    <label for='email' >Indirizzo mail:</label>
    <input type='text' name='email' id='email' maxlength="50" />
     <br>
    <label for='username' >UserName*:</label>
    <input type='text' name='username' id='username' maxlength="50" />
     <br>
    <label for='password' >Password*:</label>
    <input type='password' name='password' id='password' maxlength="50" />
    <br>
    <input type='submit' name='Submit' value='Submit' />

    </fieldset>
    </form>
    </body>
    </html>

当我访问 localhost:5000/registrazione 时,我收到错误消息。我做错了什么?

最佳答案

这是因为您在定义路由时只允许 POST 请求。

当您在浏览器中访问 /registrazione 时,它会首先执行 GET 请求。只有在您提交表单后,您的浏览器才会进行 POST。因此,对于像您这样的自提交表单,您需要同时处理这两个问题。

使用

@app.route('/registrazione', methods=['GET', 'POST']) 

应该可以。

关于python - 方法不允许 flask 错误 405,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21689364/

相关文章:

python - ORA-01036 : illegal variable name/number (cx_Oracle)

python - 我需要在 python 中编写代码以使用指纹技术比较两个文档的文本

javascript - jQuery 验证 : display the focused field error message

python - Flask 教程 : Stylesheet does not work

heroku - 在 Heroku 上使用 Redis 的服务器端 Flask session

python - 如何在行值而不是列值中绘制箱线图

python - 使用可读和可调试的代码从python 3.6+中的模块化模板创建函数

html - 可以从 html 表单发出 XML-RPC 请求吗?

javascript - 如何使用 JavaScript 动态创建表单?

Python Flask 强制重新加载缓存的 JS 文件