@Insssane

Ошибка: No application found. Either work inside a view function or push an application context., что это? и как исправить?

Такие варианты как: https://stackoverflow.com/questions/46540664/no-ap... и сделать как написано в документации уже пробовал

Traceback (most recent call last):
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\sqlalchemy\util\_collections.py", line 1008, in __call__
    return self.registry[key]
KeyError: <greenlet.greenlet object at 0x03AF9EF0 (otid=0x03139A00) current active started main>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\anton\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\anton\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\flask\__main__.py", line 3, in <module>
    main()
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\flask\cli.py", line 990, in main
    cli.main(args=sys.argv[1:])
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\flask\cli.py", line 596, in main
    return super().main(*args, **kwargs)
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\click\core.py", line 1062, in main
    rv = self.invoke(ctx)
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\click\core.py", line 1668, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\click\core.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\click\core.py", line 763, in invoke
    return __callback(*args, **kwargs)
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\click\decorators.py", line 84, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\click\core.py", line 763, in invoke
    return __callback(*args, **kwargs)
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\flask\cli.py", line 845, in run_command
    app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\flask\cli.py", line 321, in __init__
    self._load_unlocked()
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\flask\cli.py", line 346, in _load_unlocked
    self._app = rv = self.loader()
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\flask\cli.py", line 402, in load_app
    app = locate_app(self, import_name, name)
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\flask\cli.py", line 256, in locate_app
    __import__(module_name)
  File "C:\Users\anton\PycharmProjects\Site\main.py", line 1, in <module>
    from app import app
  File "C:\Users\anton\PycharmProjects\Site\app.py", line 59, in <module>
    user_datastore.create_user(email='admin4@local.com', password='admin')
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\flask_security\datastore.py", line 217, in create_user
    return self.put(user)
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\flask_security\datastore.py", line 34, in put
    self.db.session.add(model)
  File "<string>", line 2, in add
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\sqlalchemy\orm\scoping.py", line 105, in _proxied
    return self.registry()
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\sqlalchemy\util\_collections.py", line 1010, in __call__
    return self.registry.setdefault(key, self.createfunc())
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\sqlalchemy\orm\session.py", line 4065, in __call__
    return self.class_(**local_kw)
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 174, in __init__
    self.app = app = db.get_app()
  File "C:\Users\anton\PycharmProjects\Site\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 1042, in get_app
    raise RuntimeError(
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

Process finished with exit code 1


app.py
from flask import Flask, request, redirect, url_for
from config import Configuration

from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_admin import AdminIndexView


from flask_login import current_user

from flask_security import Security, SQLAlchemyUserDatastore

from models import *


app = Flask(__name__)
app.config.from_object(Configuration)


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

# ADMIN


class AdminView(ModelView):
    def is_accessible(self):
        return current_user.has_role('admin')

    def inaccessible_callback(self, name, **kwargs):
        return redirect(url_for('security.login', next=request.url))


class HomeAdminView(AdminIndexView):
    def is_accessible(self):
        return current_user.has_role('admin')

    def inaccessible_callback(self, name, **kwargs):
        return redirect(url_for('security.login', next=request.url))


# flask-security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)

# admin user
user_datastore.create_user(email='admin4@local.com', password='admin')
user = User.query.first()

user_datastore.create_role(name='admin', description='administrator')


role = Role.query.first()
user_datastore.add_role_to_user(user, role)


admin = Admin(app, 'FlaskApp', url='/admin', index_view=HomeAdminView(name='Home'))
admin.add_view(AdminView(Author, db.session))
admin.add_view(AdminView(Book, db.session))
admin.add_view(AdminView(User, db.session))
admin.add_view(AdminView(Role, db.session))


app.run()


models.py
from flask_security import UserMixin, RoleMixin

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()


class Author(db.Model):
    __tablename__ = 'author'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    birthday = db.Column(db.Date)
    name = db.Column(db.String(32), unique=True)

    def __init__(self, id, birthday, name):
        self.id = id
        self.name = name
        self.birthday = birthday

    def __repr__(self, *args, **kwargs):
        return f'{self.id}.{self.name}'


class Book(db.Model):
    __tablename__ = 'book'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(64))
    published = db.Column(db.Float)
    is_published = db.Column(db.Boolean, default=True)

    def __init__(self, id, title, published, is_published):
        self.id = id
        self.title = title
        self.published = published
        self.is_published = is_published

    def __repr__(self, *args, **kwargs):
        return f'{self.id}.{self.title}'

    book_name = db.Column(db.String(32), db.ForeignKey('author.name'))
    name = db.relationship('Author', backref=db.backref('book', lazy=True))


roles_users = db.Table('roles_users',
                       db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
                       db.Column('role_id', db.Integer, db.ForeignKey('role.id')))


class User(db.Model, UserMixin):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(100), unique=True)
    password = db.Column(db.String(255))
    active = db.Column(db.Boolean)
    confirmed_at = db.Column(db.DateTime)
    roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'))


class Role(db.Model, RoleMixin):
    __tablename__ = 'role'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(40))
    description = db.Column(db.String(255))


create_aadmin.py
from app import db
from app import user_datastore

from models import User, Role


if __name__ == '__main__':
    email = 'admin@admin.ru'
    password = 'admin'

    user_datastore.create_user(email=email, password=password)
    db.session.commit()

    user_datastore.create_role(name='admin', description='administrator')
    db.session.commit()

    admin_user = User.query.filter_by(email=email).first()
    admin_role = Role.query.filter_by(name='admin').first()

    user_datastore.add_role_to_user(admin_user, admin_role)
    db.session.commit()

    print('Admin user created.\nE-mail: {}\nPassword: {}'.format(email, password))


config.py
class Configuration(object):
    SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://userr:password@localhost/flaskdata'
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    FLASK_APP = "webapp"
    DEBUG = True

# Flask-Security
    SECRET_KEY = 'mysecret'
    SECURITY_PASSWORD_SALT = 'mysecretsalt'


main.py
from app import app

if __name__ == '__main__':
    app.run()
  • Вопрос задан
  • 38 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы