Reputation: 269
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', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
return 'Hello World'
if __name__ == '__main__':
app.run()
Upvotes: 0
Views: 10859
Reputation: 382
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.
Upvotes: 0
Reputation: 723
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.
Upvotes: 0
Reputation: 127410
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 == '[email protected]'
).first()
if admin is None:
admin = User('admin', '[email protected]')
db.session.add(admin)
db.session.commit()
For a more in depth look, see the Unique recipe in the SQLAlchemy wiki.
Upvotes: 1