英文:
How to create tables with Flask and sqlalchemy
问题
你好,以下是你要的翻译:
我正在尝试学习使用Flask和PostgreSQL构建应用程序,但无法正确使数据库工作。我正在按照以下教程进行操作:
from datetime import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password@localhost/ip_calc'
db = SQLAlchemy(app)
class Event(db.Model):
id = db.Column(db.Integer, primary_key=True)
description = db.Column(db.String(100), nullable=False)
created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
def __repr__(self):
return f"Event: {self.description}"
def __init__(self, description):
self.description = description
@app.route('/')
def hello():
return 'Hey!'
if __name__ == "__main__":
app.run()
然后教程说要转到终端,导航到正确的文件夹,并进入Python提示符,然后输入以下内容:
from app import db
db.create_all()
但我只收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/user/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 884, in create_all
self._call_for_binds(bind_key, "create_all")
File "/Users/robkinsey/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 855, in _call_for_binds
engine = self.engines[key]
^^^^^^^^^^^^
File "/Users/user/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 636, in engines
app = current_app._get_current_object() # type: ignore[attr-defined]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/user/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/werkzeug/local.py", line 508, in _get_current_object
raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.
如何使表格创建?我只是期望它能像教程中一样工作,而教程仅有一年的历史。
希望这能帮助你解决问题。
英文:
Hi I'm trying to learn to build an app in flask using postgresql, but I can't get the database working properly. The tutorial I'm following has the following:
from datetime import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password@localhost/ip_calc'
db = SQLAlchemy(app)
class Event(db.Model):
id = db.Column(db.Integer, primary_key=True)
description = db.Column(db.String(100), nullable=False)
created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
def __repr__(self):
return f"Event: {self.description}"
def __init__(self, description):
self.description = description
@app.route('/')
def hello():
return 'Hey!'
if __name__ == "__main__":
app.run()
The tutorial then says to go to the terminal navigate to the correct folder and go into a python prompt and type the following:
from app import db
db.create_all()
but I just get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/user/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 884, in create_all
self._call_for_binds(bind_key, "create_all")
File "/Users/robkinsey/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 855, in _call_for_binds
engine = self.engines[key]
^^^^^^^^^^^^
File "/Users/user/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 636, in engines
app = current_app._get_current_object() # type: ignore[attr-defined]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/user/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/werkzeug/local.py", line 508, in _get_current_object
raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.
How do I get the tables to create, I just expected it to work like it did in the tutorial it was only a year old.
答案1
得分: 1
尝试在错误的上下文中访问数据库(这是flask_sqlalchemy库所需的)。请尝试将以下内容添加到您的文件末尾。
if __name__ == "__main__":
with app.app_context():
db.create_all()
app.run()
否则,在运行app.run()
函数之前,在shell中运行with app.app_context():
(带有冒号)。
英文:
You are trying to access the database with the wrong context (which the flask_sqlalchemy library requires). Try adding this to the end of your file.
if __name__ == "__main__":
with app.app_context():
db.create_all()
app.run()
Otherwise, run the with app.app_context():
(with the colon) in the shell before running the app.run()
function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论