简体   繁体   中英

Internal server error 500 after launching flask python

I am following the tutorial: https://pythonhosted.org/Flask-SQLAlchemy/quickstart.html but something I am missing. I am using Pycharm 4.0.6 as interpreter. Almost everything is working but when I add db.session.commit() it saying me: Internal Server Error 500

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email
    def __repr__(self):
        return '<User %r>' % self.username

@app.route('/')
def hello_world():
    db.create_all()
    admin = User('admin', 'admin@example.com')
    guest = User('guest', 'guest@example.com')
    db.session.add(admin)
    db.session.add(guest)
    db.session.commit()
    return 'Hello World'



if __name__ == '__main__':
    app.run()

You've set the username and email fields to be unique. The first time you visit / , two users are created. The second time you visit, the view attempts to create and insert the same two users again. However, the usernames and emails already exist in the database, so it fails.

Creating an instance of a model with the same values is not the same as selecting it from the database. Instead, you should try to select the existing instances first, and only create new ones if the query did not return anything.

admin = User.query.filter(
    User.username == 'admin' | User.email == 'admin@example.com'
).first()

if admin is None:
    admin = User('admin', 'admin@example.com')
    db.session.add(admin)
    db.session.commit()

For a more in depth look, see the Unique recipe in the SQLAlchemy wiki.

It's better to set "app.debug = True" to get an error message that can help you troubleshoot, I believe @davidism already beat me to the answer, but just to add, you should catch SQlAlchemy errors as follows:

from sqlalchemy.exc import SQLAlchemyError

try:
    db.session.commit()
except SQLAlchemyError as e:
     reason=str(e)
     flash(reason)

This way your application will continue to run and the error message will be flashed on the screen, making it easier for you and the end user to correct the mistake.

In my case, I was using an index.html template outside the templates folder. When I moved the index.html file under templates folder the issue got resolved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM