2

I'm trying to replicate this https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xxiii-application-programming-interfaces-apis focus only in the API and security (tokens) part.

I'm having problems when I'm executing the example to manage the database

>>> u = User(username='susan', email='susan@example.com')
>>> db.session.add(u)
>>> db.session.commit()

I get this error:

RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

The main idea here is to validate if the db is working properly

This is the code in my main app/init.py file:

from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import Config

db = SQLAlchemy()
migrate = Migrate()

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    migrate.init_app(app, db)

    from app.main import bp as main_bp
    app.register_blueprint(main_bp)

    from app.api import bp as api_bp
    app.register_blueprint(api_bp, url_prefix='/api')

    return app

from app import models

This is my app/models.py file:

from flask import current_app, url_for
from werkzeug.security import generate_password_hash, check_password_hash
from app import db#, login

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    token = db.Column(db.String(32), index=True, unique=True)
    token_expiration = db.Column(db.DateTime)

    def __repr__(self):
        return '<User {}>'.format(self.username)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)


    def from_dict(self, data, new_user=False):
        for field in ['username', 'email']:
            if field in data:
                setattr(self, field, data[field])
        if new_user and 'password' in data:
            self.set_password(data['password'])


    @staticmethod
    def check_token(token):
        user = User.query.filter_by(token=token).first()
        if user is None or user.token_expiration < datetime.utcnow():
            return None
        return user
Rednaxel
  • 938
  • 2
  • 16
  • 33
  • Do you provide `app.config['SQLALCHEMY_DATABASE_URI']` in your config class? – bc291 Aug 21 '18 at 20:48
  • I will suggest you to move `db = SQLAlchemy()` object instantiation to `__init__.py` in root module where you declare your models. Then try to import it in app, next do `db.init_app(app)` in `init.py`. Finally import db from `__init__.py` to your `models.py` – bc291 Aug 21 '18 at 20:53
  • 1
    Also putting `db.app = app` right before `db.init_app(app)` does the job sometimes. So I may suggest you to do it first. – bc291 Aug 21 '18 at 20:57
  • 2
    If none of this works try `app.app_context().push()` before `db.init_app(app)` – bc291 Aug 21 '18 at 21:01
  • I just validated and the api is working with the db correctly. But haven't figure out how to execute the lines I sent above. – Rednaxel Aug 21 '18 at 22:26
  • 1
    What kind of error do you get? Paste full stack trace. – bc291 Aug 21 '18 at 23:03
  • 1
    Possible duplicate of ['No application found. Either work inside a view function or push an application context.'](https://stackoverflow.com/questions/46540664/no-application-found-either-work-inside-a-view-function-or-push-an-application) – Danila Ganchar Oct 04 '18 at 14:17

0 Answers0