如何使用Flask和SQLAlchemy创建表格。

huangapple go评论63阅读模式
英文:

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[&#39;SQLALCHEMY_DATABASE_URI&#39;] = &#39;postgresql://postgres:password@localhost/ip_calc&#39;

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&quot;Event: {self.description}&quot;

    def __init__(self, description):
        self.description = description

@app.route(&#39;/&#39;)
def hello():
    return &#39;Hey!&#39;

if __name__ == &quot;__main__&quot;:
    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 &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
  File &quot;/Users/user/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/flask_sqlalchemy/extension.py&quot;, line 884, in     create_all
    self._call_for_binds(bind_key, &quot;create_all&quot;)
  File &quot;/Users/robkinsey/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/flask_sqlalchemy/extension.py&quot;, line 855, in _call_for_binds
    engine = self.engines[key]
         ^^^^^^^^^^^^
  File &quot;/Users/user/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/flask_sqlalchemy/extension.py&quot;, line 636, in engines
    app = current_app._get_current_object()  # type: ignore[attr-defined]
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   File &quot;/Users/user/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/werkzeug/local.py&quot;, 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__ == &quot;__main__&quot;:
  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.

huangapple
  • 本文由 发表于 2023年5月20日 22:52:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76295826.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定