I'm trying to get used to the Flask API and I'm creating a simple page with 1 form which uses POST method.
Instead when I look at the Flask output I can see that any time I try to open the /configure view Flask receives a GET method instead and returns Method not allowed on the view.
test.py -
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash
import dude
app = Flask(__name__)
@app.route('/')
def hello():
output = None
if retval:
output = "True"
elif retval == False:
output = "False" + error
return render_template('index.html', output=output)
@app.route('/configure', methods=['POST'])
def configure():
hostname = request.form['hostname']
if hostname in ip_dict:
_info.append(hostname)
flash('good job')
else:
flash('Host name not in the DNS system')
return render_template('configure.html')
if __name__== "__main__":
WB = dude.Dude()
retval, error, ip_dict = WB.get_ips()
app.run(debug=True)
index.html
<!doctype html>
<title>configurator</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
<div class=page>
<h1>Configurator</h1>
<div class=metanav>
<p>{{ output }}</p>
<a href="{{ url_for('configure') }}">Configure</a>
</div>
{% for message in get_flashed_messages() %}
<div class=flash>{{ message }}</div>
{% endfor %}
{% block body %}{% endblock %}
</div>
configure.html
{% extends "index.html" %}
{% block body %}
<h1>Configure</h1>
<form action="{{ url_for('configure') }}" method=post class=hostname>
<d1>
<dt>Host name:
<dd><input type=text name=hostname size=15>
<dd><input type=submit value=Submit>
</d1>
</form>
{% for message in get_flashed_messages() %}
<div class=flash>{{ message }}</div>
{% endfor %}
</div>
{% endblock %}
and the console output from Flask
127.0.0.1 - - [04/Apr/2016 19:24:25] "GET /configure HTTP/1.1" 405 -
UPDATE
I found my mistake. I am rendering template index.html in a place where I should be instead rendering configure.html. After this in configure() I am rendering a template where instead I should redirect.
This is how the new methods look like.
@app.route('/')
def hello():
output = None
if retval:
output = "True"
elif retval == False:
output = "False" + error
return render_template('configure.html', output=output)
@app.route('/comeon', methods=['POST'])
def configure():
hostname = request.form['hostname']
if hostname in ip_dict:
_info.append(hostname)
flash('good job')
else:
flash('Host name not in the DNS system')
return redirect(url_for('hello'))
答案 0 :(得分:2)
Then you are trying to open /configure
in browser it by defaults uses GET
method.
Since you've specified only POST
for that url you are getting error.
And you have some problems with your forms.
render_template('configure.html')
You should pass some arguments such as hostname
since you are trying to use it in template <dd><input type=text name=hostname size=15>
.
And this is incorrect syntax. It should be instead:
<dd><input type=text name={{ hostname }} size=15>
And so on.