2

Here's the Flask app:

from flask import Flask, request, render_template, redirect, url_for, flash
app = Flask(__name__)

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

@app.route('/contact', methods = ['POST'])
def contact():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        message = request.form['message']

        flash(name)
        flash(email)
        flash(message)

    return redirect(url_for('index'))

if __name__ == '__main__':
    app.debug = True
    app.secret_key='a;sldfjka;oeiga;lbneas; biaweag'
    app.run()

Here's the template I'm using:

<!DOCTYPE html>
<html>
    <head>
    </head>

    <body> 
        <form action="/contact" method="post">
            <input type="text" name="name" />
            <input type="text" name="email" />
            <textarea name="message"> </textarea>
            <input type="submit" />
        </form> 
        <ul>
        {% for message in get_flashed_messages() %}
            <li><h3> {{ message }} </h3></li>
        {% endfor %}
        </ul>
    </body>
</html>

And here's the gunicorn command line I use to serve it:

gunicorn --error-logfile err.log --access-logfile access.log \
--log-level debug -b 127.0.0.1:5000 --debug -w 4 wsgi:app

It serves the GET request for the template just fine. However, when I actually POST the form, it 500's out. Here's the response headers:

HTTP/1.1 500 INTERNAL SERVER ERROR
Server: gunicorn/0.17.2
Date: Thu, 21 Mar 2013 21:57:25 GMT
Connection: close
Content-Type: text/html
Content-Length: 291

Here's what shows up in the gunicorn logs:

==> err.log <==
2013-03-21 17:12:38 [10092] [DEBUG] POST /contact

==> access.log <==
"127.0.0.1 - - [21/Mar/2013:17:12:38] "POST /contact HTTP/1.1" 500 291 \
"http://localhost:5000/" "Mozilla/5.0 (X11; Linux x86_64; rv:19.0) \
Gecko/20100101 Firefox/19.0"

Works fine when I serve it using Flask's built in dev server.

Mah brain tells me that this is something reeeeally simple that I'm just missing. Guh.

1 Answer 1

5

I defined the secret_key in the name == main block. Gunicorn was choking because the app didn't have said key, which it needs to handle form submissions.

if __name__ == '__main__':
    app.secret_key = #...

That line needs to be... anywhere else, so long as it gets evaluated when the script is run by gunicorn.

app = Flask(__name__)
app.secret_key = #...

I think it's worth pointing out that if I had any kind of decent logging set up, I would have caught this little screw up right away.

1
  • 3
    Thanks for bothering to post the resolution, I had exactly the same issue and this resolved it instantly. Probably saved me hours.
    – Matt
    Jul 16, 2014 at 20:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.