Luke
Luke

Reputation: 375

flask db init leads to "KeyError: 'migrate'

I created already a database and added 2 tables (venue, artist).

This is a party from my app.py:

import json
import dateutil.parser
import babel
from flask import Flask, render_template, request, Response, flash, redirect, url_for
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
import logging
from logging import Formatter, FileHandler
from flask_wtf import Form
from forms import *
from flask_migrate import Migrate
#----------------------------------------------------------------------------#
# App Config.
#----------------------------------------------------------------------------#
app = Flask(__name__)
moment = Moment(app)
app.config.from_object('config')
db = SQLAlchemy(app)
# TODO: connect to a local postgresql database
##Done via the config file
#----------------------------------------------------------------------------#
# Models.
#----------------------------------------------------------------------------#
#Migrate
migrate =(app,db)
class Venue(db.Model):
    __tablename__ = 'venue'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    city = db.Column(db.String(120))
    state = db.Column(db.String(120))
    address = db.Column(db.String(120))
    phone = db.Column(db.String(120))
    image_link = db.Column(db.String(500))
    facebook_link = db.Column(db.String(120))
    # TODO: implement any missing fields, as a database migration using Flask-Migrate
class Artist(db.Model):
    __tablename__ = 'artist'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    city = db.Column(db.String(120))
    state = db.Column(db.String(120))
    phone = db.Column(db.String(120))
    genres = db.Column(db.String(120))
    image_link = db.Column(db.String(500))
    facebook_link = db.Column(db.String(120))

In my config file I create the connection.

If I try to run "flask db init" in the directory where also my app.py and all the other files are located I get the following error:

directory = current_app.extensions['migrate'].directory

KeyError: 'migrate'

I tried it for hours know but found no solution so far. What am I doing wrong? Please help me.

Upvotes: 7

Views: 13799

Answers (4)

Shamyrat Pashshyyev
Shamyrat Pashshyyev

Reputation: 304

Add Migrate(app,db) to your project and just run the flask db migrate command from outside the folder where your project is located and set the location of the flask app with:

On Windows-- set FLASK_APP=/absolute/path/to/flask/app
On Linux-- export FLASK_APP=/path/to/app/from/current/location
Then try flask db migrate and it should work just fine.

Upvotes: 0

Felix Orinda
Felix Orinda

Reputation: 743

You can have this setup

"""App factrory file"""
from flask import Flask
from flask_migrate import Migrate
from app.config.config import APP_CONFIG
from app.db.database import db

def create_app():
    """App factory"""
    app = Flask(__name__)
    app.config.from_object(APP_CONFIG["development"])
    db.init_app(app)
    Migrate(app,db)

    # Register blueprint apps
    app.register_blueprint(homeViews)

    return app

Flask migrate must have the app instance injected together with the Sqlachemy instance For environment variables you can have this in your .env

FLASK_APP=yourapp.py
FLASK_RUN_HOST="localhost"
FLASK_RUN_PORT=
FLASK_ENV=development
FLASK_DB_USER=
FLASK_DB_PASSWORD=
FLASK_APP_SECRET_KEY=

For your config.py

from os import environ
from dotenv import load_dotenv

# Load environment variables
load_dotenv()


class DevelopmentConfig(object):
    """
    Development configuration just for local development
    """
    SQLALCHEMY_DATABASE_URI = f"postgresql://{environ.get('FLASK_DB_USER')}:\
        {environ.get('FLASK_DB_PASSWORD')}@localhost/db_name"
    SQLALCHEMY_TRACK_MODIFICATIONS = False


class TestingConfig(object):
    """ Testing configuration just for local development"""
    ...


class ProductionConfig(object):
    """ Deployment configuration for production development"""
    ...


APP_CONFIG = {
    "development": DevelopmentConfig,
    "testing": TestingConfig,
    "production": ProductionConfig
}

Once you're done setting up you can running

>>> flask db init
>>> flask db migrate -m "Initial migrations"
>>> flask db upgrade

Upvotes: 3

Pulia Zlaya
Pulia Zlaya

Reputation: 51

Flask comand uses env variable FLASK_APP, to know where Flask app is located. For your application you will have to set FLASK_APP=microblog.py, as goes in chapter 1.

source - https://www.kickstarter.com/projects/1124925856/the-new-and-improved-flask-mega-tutorial)

RUS - Помните, что flask команда полагается на переменную среды FLASK_APP, чтобы знать, где расположено приложение Flask. Для этого приложения вы хотите установить FLASK_APP=microblog.py, как описано в главе 1.

Upvotes: 1

mustafasencer
mustafasencer

Reputation: 773

I think you should add the code below:

migrate = Migrate(app, db) # this

For further info you can check this link

Upvotes: 24

Related Questions