English 中文(简体)
5. 建造一座桥梁
原标题:Python terminal not building database

我正在建造一个名叫Adhury的聊天信使。

当我通过<代码>db.create_all()自动创建数据库时,出现以下错误:

>>> db.create_all()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:UsersPraktikant2AppDataLocalProgramsPythonPython311Libsite-packagesflask_sqlalchemyextension.py", line 887, in create_all
    self._call_for_binds(bind_key, "create_all")
  File "C:UsersPraktikant2AppDataLocalProgramsPythonPython311Libsite-packagesflask_sqlalchemyextension.py", line 858, in _call_for_binds
    engine = self.engines[key]
             ^^^^^^^^^^^^
  File "C:UsersPraktikant2AppDataLocalProgramsPythonPython311Libsite-packagesflask_sqlalchemyextension.py", line 639, in engines
    app = current_app._get_current_object()  # type: ignore[attr-defined]
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:UsersPraktikant2AppDataLocalProgramsPythonPython311Libsite-packageswerkzeuglocal.py", line 508, 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.
>>>

I have following code:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)

app.config[ SQLALCHEMY_DATABASE_URI ] =  sqlite:///db.db 
app.config[ SQLALCHEMY_TRACK_MODIFICATIONS ] = False
db = SQLAlchemy(app)

class Message(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user = db.Column(db.String(200), nullable=True)
    content = db.Column(db.String(500), nullable=True)
    created_at = db.Column(db.DateTime(), default=datetime.utcnow)

with app.app_context():
    db.create_all()

@app.route("/")
def start_page():
    return "<h1>Hello World!</h1>"

if __name__ == "__main__":
    app.run(debug=True)

我做了什么错误,我如何纠正?

问题回答

你们都必须做的是:.force the context. 在经过周到和即时之后,添加以下一线:

app_context().push(

你的法典是:

app.config[ SQLALCHEMY_DATABASE_URI ] =  sqlite:///db.db 
app.config[ SQLALCHEMY_TRACK_MODIFICATIONS ] = False
db = SQLAlchemy(app)
app.app_context().push()

然后,在终点站:

1. Python (or Python3)
2. from app import app
3. from app import db
4. db.create_all()




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签