简体   繁体   English

启动flask python后内部服务器错误500

[英]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.我正在关注教程: https : //pythonhosted.org/Flask-SQLAlchemy/quickstart.html但我缺少一些东西。 I am using Pycharm 4.0.6 as interpreter.我使用 Pycharm 4.0.6 作为解释器。 Almost everything is working but when I add db.session.commit() it saying me: Internal Server Error 500几乎一切正常,但是当我添加 db.session.commit() 它说我:内部服务器错误 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.您已将usernameemail字段设置为唯一。 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.如需更深入的了解,请参阅 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:最好设置“app.debug = True”以获取可以帮助您进行故障排除的错误消息,我相信@davidism 已经击败了我的答案,但只是补充一下,您应该按如下方式捕获 SQlAlchemy 错误:

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.就我而言,我使用的是模板文件夹外的 index.html 模板。 When I moved the index.html file under templates folder the issue got resolved.当我移动模板文件夹下的 index.html 文件时,问题得到了解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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