单击“ subimit”按钮后,我遇到了标题中的问题,当我将路由从应用程序分离到视图时,当我进入localhost:5000 / register /时,问题开始显示,但是当我填写表格并单击Submit然后我有问题405
app.py
from flask import Flask,render_template,request,redirect,abort
app = Flask(__name__)
import views
app.add_url_rule('/', view_func=views.index)
app.add_url_rule('/login/', view_func=views.login)
app.add_url_rule('/register/', view_func=views.register)
if __name__ == '__main__':
app.run(debug=True)
views.py
from flask import Flask,render_template,request,redirect,abort
app = Flask(__name__)
@app.route('/register/', methods=["GET","POST"])
def register():
if request.method == "POST":
req = request.form
email = req.get("email")
password = req["password"]
phonenumber = request.form["phonenumber"]
if email == "" or password == "" or phonenumber=="":
feedback="Please fill the form"
alert = "fail"
else:
feedback="Account created!"
alert = "good"
return render_template('register.html',feedback=feedback,alert=alert)
return render_template('register.html')
@app.route('/')
def index():
print("CIAO")
return render_template('base.html')
和表格
<form class="" method="POST" action="{{ url_for('register') }}">
<input type="email" name="email" placeholder="Email">
<input type="password" name="password" placeholder="password" minlength="8">
<input type="tel" name="phonenumber" placeholder="Numer Telefonu" minlength="8" maxlength="9">
<input type="submit" name="submit">
</form>
答案 0 :(得分:1)
Flask找不到/register/
端点的POST方法处理程序。您正在混合add_url_rule
和@route
。如果想要可插入的视图,则只需要前者即可。
我建议在这里使用MethodView方法。每个模板都有一个单独的类,并在其中定义get()
和post()
方法。
app.py:
from flask import Flask
from views import Register, Login, Index
app = Flask(__name__)
app.add_url_rule('/', view_func=Index.as_view("index"))
app.add_url_rule('/login/', view_func=Login.as_view("login"))
app.add_url_rule('/register/', view_func=Register.as_view("register"))
if __name__ == '__main__':
app.run(debug=True)
views.py:
from flask import Flask,render_template,request,redirect,abort
from flask.views import MethodView
class Register(MethodView):
def get(self):
return render_template('register.html')
def post(self):
req = request.form
email = req.get("email")
password = req["password"]
phonenumber = request.form["phonenumber"]
if email == "" or password == "" or phonenumber == "":
feedback = "Please fill the form"
alert = "fail"
else:
feedback = "Account created!"
alert = "good"
return render_template('register.html', feedback=feedback, alert=alert)
class Index(MethodView):
def get(self):
print("CIAO")
return render_template('index.html')
class Login(MethodView):
def get(self):
return render_template('login.html')