使用Flask-SQLAlchemy创建数据库时候报错
此电脑上有MySQL8.0,用户名root,密码eastchinasea,有数据库flask_demo.db
代码:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import pymysql
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = (
'mysql+pymysql://root:eastchinasea@localhost/flask_demo'
)
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, autoincrement = True, primary_key = True)
username = db.Column(db.String(80), unique = True, nullable = False)
email = db.Column(db.String(120), unique = True, nullable = False)
def __repr__(self):
return '<User %r>' % self.username
if __name__ == '__main__':
db.create_all()
运行结果及详细报错内容:
Traceback (most recent call last):
File "D:\Program\Python\Python Web\Flask_\SQLflask\manage.py", line 23, in <module>
db.create_all()
File "D:\Program\Python\venv\Lib\site-packages\flask_sqlalchemy\extension.py", line 884, in create_all
self._call_for_binds(bind_key, "create_all")
File "D:\Program\Python\venv\Lib\site-packages\flask_sqlalchemy\extension.py", line 855, in _call_for_binds
engine = self.engines[key]
^^^^^^^^^^^^
File "D:\Program\Python\venv\Lib\site-packages\flask_sqlalchemy\extension.py", line 636, in engines
app = current_app._get_current_object() # type: ignore[attr-defined]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Program\Python\venv\Lib\site-packages\werkzeug\local.py", line 513, in _get_current_object
raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.
我尝试过的方法:
我把这个
app.config['SQLALCHEMY_DATABASE_URI'] = (
'mysql+pymysql://root:eastchinasea@localhost/flask_demo'
)
里面的
mysql+pymysql://root:eastchinasea@localhost/flask_demo
修改了很多次,还是有错误,如:
mysql+pymysql://root:eastchinasea@127.0.0.1/flask_demo
mysql+pymysql://root:eastchinasea@localhost/flask_demo.db
改了很多次还是有错误.