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

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

How to create tables with Flask and sqlalchemy

问题

你好,以下是你要的翻译:

我正在尝试学习使用Flask和PostgreSQL构建应用程序,但无法正确使数据库工作。我正在按照以下教程进行操作:

  1. from datetime import datetime
  2. from flask import Flask
  3. from flask_sqlalchemy import SQLAlchemy
  4. app = Flask(__name__)
  5. app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password@localhost/ip_calc'
  6. db = SQLAlchemy(app)
  7. class Event(db.Model):
  8. id = db.Column(db.Integer, primary_key=True)
  9. description = db.Column(db.String(100), nullable=False)
  10. created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
  11. def __repr__(self):
  12. return f"Event: {self.description}"
  13. def __init__(self, description):
  14. self.description = description
  15. @app.route('/')
  16. def hello():
  17. return 'Hey!'
  18. if __name__ == "__main__":
  19. app.run()

然后教程说要转到终端,导航到正确的文件夹,并进入Python提示符,然后输入以下内容:

  1. from app import db
  2. db.create_all()

但我只收到以下错误:

  1. Traceback (most recent call last):
  2. File "<stdin>", line 1, in <module>
  3. File "/Users/user/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 884, in create_all
  4. self._call_for_binds(bind_key, "create_all")
  5. File "/Users/robkinsey/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 855, in _call_for_binds
  6. engine = self.engines[key]
  7. ^^^^^^^^^^^^
  8. File "/Users/user/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 636, in engines
  9. app = current_app._get_current_object() # type: ignore[attr-defined]
  10. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  11. File "/Users/user/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/werkzeug/local.py", line 508, in _get_current_object
  12. raise RuntimeError(unbound_message) from None
  13. RuntimeError: Working outside of application context.
  14. 如何使表格创建?我只是期望它能像教程中一样工作,而教程仅有一年的历史。

希望这能帮助你解决问题。

英文:

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:

  1. from datetime import datetime
  2. from flask import Flask
  3. from flask_sqlalchemy import SQLAlchemy
  4. app = Flask(__name__)
  5. app.config[&#39;SQLALCHEMY_DATABASE_URI&#39;] = &#39;postgresql://postgres:password@localhost/ip_calc&#39;
  6. db = SQLAlchemy(app)
  7. class Event(db.Model):
  8. id = db.Column(db.Integer, primary_key=True)
  9. description = db.Column(db.String(100), nullable=False)
  10. created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
  11. def __repr__(self):
  12. return f&quot;Event: {self.description}&quot;
  13. def __init__(self, description):
  14. self.description = description
  15. @app.route(&#39;/&#39;)
  16. def hello():
  17. return &#39;Hey!&#39;
  18. if __name__ == &quot;__main__&quot;:
  19. 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:

  1. from app import db
  2. db.create_all()

but I just get the following error:

  1. Traceback (most recent call last):
  2. File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
  3. File &quot;/Users/user/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/flask_sqlalchemy/extension.py&quot;, line 884, in create_all
  4. self._call_for_binds(bind_key, &quot;create_all&quot;)
  5. 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
  6. engine = self.engines[key]
  7. ^^^^^^^^^^^^
  8. File &quot;/Users/user/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/flask_sqlalchemy/extension.py&quot;, line 636, in engines
  9. app = current_app._get_current_object() # type: ignore[attr-defined]
  10. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  11. File &quot;/Users/user/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/werkzeug/local.py&quot;, line 508, in _get_current_object
  12. raise RuntimeError(unbound_message) from None
  13. 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库所需的)。请尝试将以下内容添加到您的文件末尾。

  1. if __name__ == "__main__":
  2. with app.app_context():
  3. db.create_all()
  4. 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.

  1. if __name__ == &quot;__main__&quot;:
  2. with app.app_context():
  3. db.create_all()
  4. 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:

确定