问题
I'm new to Flask, and having some issues setting up a very basic Flask app. Right now, I'm trying to get the user to submit a form on the homepage and then save that form to a SQL database.
However, when the user submits the form, I get the following error
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: contact [SQL: 'INSERT INTO contact (name, email) VALUES (?, ?)'] [parameters: ('aaa', 'aaa')] (Background on this error at: http://sqlalche.me/e/e3q8)
Relevant code is below:
app/models.py
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired
class ContactForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
email = PasswordField('Email', validators=[DataRequired()])
submit = SubmitField('submit')
app/__init__
.py
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
from app import routes, models
app/config.py
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'some-secret-key'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
enter code here
Where could I be going wrong here? Do I have to call db.create_all() somewhere? If so, where?
Thanks!
Edit: I've also run
flask db init
flask db migrate
flask db upgrade
回答1:
Create a model in models.py:
from __init__.py import db
class ContactModel(db.Model):
__tablename__ = 'contact'
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(120))
email = db.Column(db.String(120))
def save_to_db(self):
db.session.add(self)
db.session.commit()
Then in init.py:
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
#create all db tables
@app.before_first_request
def create_tables():
from models import ContactModel
db.create_all()
from app import routes, models
回答2:
If you are using flask-migrate library, you should run commands below to create and apply migrations. Database and tables will be created.
flask db migrate
flask db upgrade
Before running this commands you should create models. Models objects represent tables on a database. In your case, it may look like this
class Contact(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
回答3:
I had the same issue. In my case I was querying the database in a forms.py
and this was imported to routes.py
.
So the problem was basically that the database was queried in the code before it could be created, as classes are loaded before the server starts and an eventual init happens.
The accepted answer didn't work for me. Unfortunately, I haven't found a clean solution for this. So I ended up with a workaround for this.
In my case I wanted to show files in a dropdown list, so I initialized them empty the first time:
try:
profile_files = [ (file.path, file.filename[:-4])
for file in File.query.filter_by(type=2).order_by(File.created.desc()).all()]
except sqlalchemy.exc.OperationalError as e:
profile_files = []
So the general workaround would be:
try:
# Your DB query
except sqlalchemy.exc.OperationalError as e:
# create placeholder until your DB is ready
Now I can use all the terminal commands again:
flask db init
flask db migrate
flask db upgrade
Hope this is helpful to someone!
来源:https://stackoverflow.com/questions/50892823/flask-sqlalchemy-exc-operationalerror-operationalerror-no-such-table-when-try