ввожу в терминал команду db.create_all() выдаёт ошибку

Рейтинг: 1Ответов: 2Опубликовано: 19.02.2023

занимаюсь питоном очень мало и программу писал по гайду, уже день маюсь с проблемой помогите режить

from flask import Flask, render_template, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URL'] = 'sqlite://blog.db'
db = SQLAlchemy(app)


class Article(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    intro = db.Column(db.String(300), nullable=False)
    text = db.Column(db.Text, nullable=False)
    date = db.Column(db.DateTime, default=datetime.utcnow)

    def __repr__(self):
        return '<Article %r>' % self.id


@app.route('/')
@app.route('/home')
def index():
    return render_template("index.html")


@app.route('/about')
def about():
    return render_template("about.html")


@app.route('/user/<string:name>/<int:id>')
def user(name, id):
    return "User page" + name + " _ " + str(id)


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




ошибка:
Traceback (most recent call last):                                                                                                           
  File "<stdin>", line 1, in <module>                                                                                                        
  File "C:\Users\Артём\AppData\Local\Programs\Python\Python310\lib\site-packages\flask_sqlalchemy\extension.py", line 884, in create_all     
    self._call_for_binds(bind_key, "create_all")                                                                                             
  File "C:\Users\Артём\AppData\Local\Programs\Python\Python310\lib\site-packages\flask_sqlalchemy\extension.py", line 855, in _call_for_binds
    engine = self.engines[key]                                                                                                               
  File "C:\Users\Артём\AppData\Local\Programs\Python\Python310\lib\site-packages\flask_sqlalchemy\extension.py", line 636, in engines        
    app = current_app._get_current_object()  # type: ignore[attr-defined]                                                                    
  File "C:\Users\Артём\AppData\Local\Programs\Python\Python310\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.

Ответы

▲ 1

Проблема в строке app.config['SQLALCHEMY_DATABASE_URL'] = 'sqlite://blog.db'. У вас опечатка, должно быть SQLALCHEMY_DATABASE_URI вместо SQLALCHEMY_DATABASE_URL. Что-то вроде такого

from flask import Flask, render_template, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'
app.config['SECRET_KEY'] = 'your_secret_key_here'
db = SQLAlchemy(app)


class Article(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    intro = db.Column(db.String(300), nullable=False)
    text = db.Column(db.Text, nullable=False)
    date = db.Column(db.DateTime, default=datetime.utcnow)

    def __repr__(self):
        return '<Article %r>' % self.id


@app.route('/')
@app.route('/home')
def index():
    return render_template("index.html")


@app.route('/about')
def about():
    return render_template("about.html")


@app.route('/user/<string:name>/<int:id>')
def user(name, id):
    return "User page" + name + " _ " + str(id)


if __name__ == "__main__":
    with app.app_context():
        db.create_all()
    app.run(debug=True)
▲ 0
>>> from app import app, db
>>> app.app_context().push()
>>> db.create_all()