"Directory migrations already exists" during init on Heroku - python

I ran the command heroku run init and got this error. How can I fix it?
manager.run()
File "/app/.heroku/python/lib/python2.7/site-packages/flask_script/__init__.py", line 412, in run
result = self.handle(sys.argv[0], sys.argv[1:])
File "/app/.heroku/python/lib/python2.7/site-packages/flask_script/__init__.py", line 383, in handle
res = handle(*args, **config)
File "/app/.heroku/python/lib/python2.7/site-packages/flask_script/commands.py", line 216, in __call__
return self.run(*args, **kwargs)
File "/app/.heroku/python/lib/python2.7/site-packages/flask_migrate/__init__.py", line 61, in init
command.init(config, directory, 'flask')
File "/app/.heroku/python/lib/python2.7/site-packages/alembic/command.py", line 28, in init
raise util.CommandError("Directory %s already exists" % directory)
alembic.util.CommandError: Directory migrations already exists
manage.py:
app = create_app(os.environ.get('FLASK_CONFIG', 'default'))
magrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
#manager.command
def init_db():
db.drop_all()
db.create_all()
config.py:
class Config(object):
DEBUG = False
SECRET_KEY = 'Thisismysecretkey'
SQLALCHEMY_DATABASE_URI = os.environ.get(
'DATABASE_URL',
'postgresql+psycopg2://peg:1234#localhost/app')
print SQLALCHEMY_DATABASE_URI
class HerokuConfig(ProductionConfig):
def init_app(cls, app):
ProductionConfig.init_app(app)
import logging
from logging import StreamHandler
file_handler = StreamHandler()
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'heroku': HerokuConfig,
'default': DevelopmentConfig
}

You appear to be trying to run manage.py db init again. Don't do that, the migration directory and migrations already exist in the application you've already built. Instead, run manage.py db upgrade.

Related

Python/Docker - Unknown server host 'db' when migrating

I am trying to migrate a program using python manage.py db migrate in my Visual Studio terminal but when I run it I am getting an error named (2005, "Unknown server host 'db' (11001)"). I am also using the SQLAlchemy library as well to use it alongside flask to create my app. I have found some solutions on StackOverflow and GitHub like trying to recreate my network https://github.com/docker-library/mysql/issues/644 and trying to import MySQLdb and using MySQLdb.connect() "Unknown MySQL server host" when using Flask in Python, but when I try both of these solutions on my program using Visual Studio they don't work.
Here is the error that I am getting in it's full form:
Traceback (most recent call last):
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\engine\base.py", line 2336, in _wrap_pool_connect
return fn()
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 304, in unique_connection
return _ConnectionFairy._checkout(self)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 778, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 495, in checkout
rec = pool._do_get()
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\impl.py", line 241, in _do_get
return self._create_connection()
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 309, in _create_connection
return _ConnectionRecord(self)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 440, in __init__
self.__connect(first_connect_check=True)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 661, in __connect
pool.logger.debug("Error on connect(): %s", e)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\util\langhelpers.py", line 68, in __exit__
compat.raise_(
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\util\compat.py", line 182, in raise_
raise exception
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 656, in __connect
connection = pool._invoke_creator(self)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\engine\strategies.py", line 114, in connect
return dialect.connect(*cargs, **cparams)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\engine\default.py", line 493, in connect
return self.dbapi.connect(*cargs, **cparams)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\__init__.py", line 123, in Connect
return Connection(*args, **kwargs)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\connections.py", line 185, in __init__
super().__init__(*args, **kwargs2)
MySQLdb._exceptions.OperationalError: (2005, "Unknown server host 'db' (11001)")
Here are my required files respectivly:
Dockerfile:
FROM python:3.9
ENV PYTHONUNBUFFERED 1
WORKDIR /app
COPY requirements.txt /app/requirements.txt
RUN pip install -r requirements.txt
COPY . /app
CMD python main.py
requirements.txt:
Flask==1.1.2
Flask-SQLAlchemy==2.4.4
SQLAlchemy==1.3.20
Flask-Migrate==2.6.0
Flask-Script==2.0.6
Flask-Cors==3.0.9
requests==2.25.0
werkzeug==1.0.1
mysqlclient==2.1.0
pika==1.1.0
itsdangerous==2.0.1
wolframalpha==5.0.0
docker-compose.yml:
version: '3.8'
services:
backend:
build:
context: .
dockerfile: Dockerfile
command: 'python main.py'
ports:
- 8001:5000
volumes:
- .:/app
depends_on:
- db
queue:
build:
context: .
dockerfile: Dockerfile
command: 'python -u consumer.py'
depends_on:
- db
db:
image: mysql:5.7.22
restart: always
environment:
MYSQL_DATABASE: veganetworkscript
MYSQL_USER: root
MYSQL_PASSWORD: root
MYSQL_ROOT_PASSWORD: root
volumes:
- .dbdata:/var/lib/mysql
ports:
- 33068:3306
And finally my manage.py file:
from main import app, db
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
main.py:
from flask_cors import CORS
from sqlalchemy import UniqueConstraint
from vegaaimain.vegamain import main
from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy
from dataclasses import dataclass
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql://root:root#db/veganetworkscript'
CORS(app)
db = SQLAlchemy(app)
class Product(db.Model):
id: int
title: str
image: str
id = db.Column(db.Integer, primary_key=True, autoincrement=False)
title = db.Column(db.String(200))
image = db.Column(db.String(200))
class VegaScriptRun(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=False)
title = db.Column(db.String(200))
description = db.Column(db.String(400))
image = db.Column(db.String(200))
main()
class ProductUser(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer)
product_id = db.Column(db.Integer)
UniqueConstraint('product_id', 'user_id', name='user_product_unique')
#app.route('/api/products')
def index():
return jsonify(Product.query.all())
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
What exactly am I missing or potentially doing wrong here, thank you!
Make changes as follow and it should work:
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql://root:root#127.0.0.1:33068/veganetworkscript'
But this will only work for migration when your docker container is not running. You can reach the host machine within the container on ip address 172.17.0.1. So your database URI should be
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql://root:root#172.17.0.1:33068/veganetworkscript'
Also checkout this link
https://www.digitalocean.com/community/tutorials/how-to-use-flask-sqlalchemy-to-interact-with-databases-in-a-flask-application

Correct way to use Flask configuration from_object

I'm trying to use debug mode in Flask, but it's crashing every time. Ny config.py file looks like this:
class Config(object):
DEBUG = False
DEVELOPMENT = False
SECRET_KEY = 'do-i-really-need-this'
FLASK_SECRET = SECRET_KEY
SQLALCHEMY_DATABASE_URI = 'host'
class DevConfig(Config):
DEVELOPMENT = True
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'host2'
Then, init.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app():
"""Construct the core application."""
app = Flask(__name__, instance_relative_config=False)
app.config.from_object('config.DevConfig')
db.init_app(app)
with app.app_context():
# Imports
from . import routes
# Create tables for our models
db.create_all()
return app
And finally, the run file:
from application import create_app
app = create_app()
if __name__ == "__main__":
app.run(host='0.0.0.0')
When I try to run it, following error appears:
* Serving Flask app "application" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
INFO:werkzeug: * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
INFO:werkzeug: * Restarting with stat
Traceback (most recent call last):
File "<ipython-input-1-aaa9539d5209>", line 1, in <module>
runfile('/home/vladimir.balayan/Desktop/scipts/UX/flasksqlalchemy-tutorial-master/wsgi.py', wdir='/home/vladimir.balayan/Desktop/scipts/UX/flasksqlalchemy-tutorial-master')
File "/home/vladimir.balayan/anaconda3/envs/wbe-testing/lib/python3.7/site-packages/spyder_kernels/customize/spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "/home/vladimir.balayan/anaconda3/envs/wbe-testing/lib/python3.7/site-packages/spyder_kernels/customize/spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/home/vladimir.balayan/Desktop/scipts/UX/flasksqlalchemy-tutorial-master/wsgi.py", line 11, in <module>
app.run(host='0.0.0.0')
File "/home/vladimir.balayan/anaconda3/envs/wbe-testing/lib/python3.7/site-packages/flask/app.py", line 990, in run
run_simple(host, port, self, **options)
File "/home/vladimir.balayan/anaconda3/envs/wbe-testing/lib/python3.7/site-packages/werkzeug/serving.py", line 1007, in run_simple
run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
File "/home/vladimir.balayan/anaconda3/envs/wbe-testing/lib/python3.7/site-packages/werkzeug/_reloader.py", line 332, in run_with_reloader
sys.exit(reloader.restart_with_reloader())
File "/home/vladimir.balayan/anaconda3/envs/wbe-testing/lib/python3.7/site-packages/werkzeug/_reloader.py", line 159, in restart_with_reloader
args = _get_args_for_reloading()
File "/home/vladimir.balayan/anaconda3/envs/wbe-testing/lib/python3.7/site-packages/werkzeug/_reloader.py", line 76, in _get_args_for_reloading
if __main__.__package__ is None:
AttributeError: module '__main__' has no attribute '__package__'
I already installed python-dotenv module and made .env file with FLASK_ENV=development, but the error is the same.
I'm using Spyder IDE for debugging and this tutorial
If your application structure is the same as shown in the tutorial you are following, try changing your config.py to this
from os import environ, path
basedir = path.abspath(path.dirname(__file__))
class Config(object):
DEBUG = False
DEVELOPMENT = False
SECRET_KEY = environ.get('SECRET_KEY') or \
'\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'
FLASK_SECRET = SECRET_KEY
class DevConfig(Config):
DEVELOPMENT = True
DEBUG = True
SQLALCHEMY_DATABASE_URI = environ.get('SQLALCHEMY_DATABASE_URI') or \
'sqlite:///' + os.path.join(basedir, 'db.sqlite')
class ProdConfig(Config):
DEVELOPMENT = True
DEBUG = True
SQLALCHEMY_DATABASE_URI = environ.get('SQLALCHEMY_DATABASE_URI') or \
'sqlite:///' + os.path.join(basedir, 'db.sqlite')
config = {
'dev': DevConfig,
'prod': ProdConfig,
'default': DevConfig,
}
And then your __init__.py to this
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import config
db = SQLAlchemy()
def create_app(config_name):
"""Construct the core application."""
app = Flask(__name__)
app.config.from_object(config.get(config_name or 'default'))
db.init_app(app)
with app.app_context():
# Imports
from . import routes
# Create tables for our models
db.create_all()
return app
Then in your run.py or whatever file you are using to launch the application you could do this
from os import environ
from application import create_app
app = create_app(environ.get('FLASK_CONFIG'))
if __name__ == "__main__":
app.run(host='0.0.0.0')
Hope this helps.

Celery Worker not Inheriting Settings from Django App

I am developing a django app that has to process large spreadsheets that users upload - so naturally I turned to celery and rabbitmq. I successfully setup the environment and the task completes in the background successfully except for one issue: I use several environment variables (defined in my apache vhost file and passed to django by mod_wsgi) in a db router class to determine which database to use (i.e. production vs staging vs dev):
class DbRouter(object):
def db_for_read(self, model, **hints):
if model._meta.app_label == 'auth':
return 'auth'
elif model._meta.app_label == 'admin':
return 'auth'
elif model._meta.app_label == 'contenttypes':
return 'auth'
else:
environment = environment = os.environ['BH_ENVIRONMENT_NAME']
if environment == "staging":
return 'staging'
if environment == "production":
return 'production'
def db_for_write(self, model, **hints):
if model._meta.app_label == 'auth':
return 'auth'
elif model._meta.app_label == 'admin':
return 'auth'
elif model._meta.app_label == 'contenttypes':
return 'auth'
else:
###########################################
#This is where django raises the exception#
###########################################
environment = os.environ['BH_ENVIRONMENT_NAME']
if environment == "staging":
return 'staging'
if environment == "production":
return 'production'
def allow_migrate(self, db, app_label, model_name, **hints):
return True
which works just fine in the regular django thread; however, when the background task attempts to use the db router I get the following key error (which seems to imply that os.environ dictionary is not available to the worker thread?):
[2018-02-16 14:23:01,516: ERROR/ForkPoolWorker-2] Task
exposures.tasks.process_exposure_file[27d7e651-e73e-49f1-bd20-8ab80b90d13a]
raised unexpected: KeyError('BH_ENVIRONMENT_NAME',)
Traceback (most recent call last):
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/celery/app/trace.py", line 374, in trace_task
R = retval = fun(*args, **kwargs)
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/celery/app/trace.py", line 629, in __protected_call__
return self.run(*args, **kwargs)
File "/home/bryan/PycharmProjects/BeachHouse/exposures/tasks.py", line 10,
in process_exposure_file
exposure = Exposure.objects.get(pk=exposure_id)
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/django/db/models/query.py", line 397, in get
num = len(clone)
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/django/db/models/query.py", line 254, in __len__
self._fetch_all()
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/django/db/models/query.py", line 1179, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/django/db/models/query.py", line 50, in __iter__
db = queryset.db
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/django/db/models/query.py", line 1109, in db
return self._db or router.db_for_read(self.model, **self._hints)
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/django/db/utils.py", line 258, in _route_db
chosen_db = method(model, **hints)
File "/home/bryan/PycharmProjects/BeachHouse/BeachHouse/db_routers.py", line
16, in db_for_read
environment = os.environ['BH_ENVIRONMENT_NAME']
File "/var/www/BeachHouse/bhvenv/lib/python3.6/os.py", line 669, in
__getitem__
raise KeyError(key) from None
KeyError: 'BH_ENVIRONMENT_NAME'
I attempted to fix this by adding the following to my settings.py file:
ENVIRONMENT_NAME = os.environ.get('BH_ENVIRONMENT_NAME')
and updating the db router to use settings.ENVIRONMENT_NAME - however, when I print this out in the celery worker terminal it's blank. My celery.py file is as follows (not sure if that's relevant or not?):
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ['DJANGO_SETTINGS_MODULE'] = 'BeachHouse.settings'
app = Celery('BeachHouse')
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object('BeachHouse.settings', namespace='CELERY')
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
so the question is: how do I pass the apache vhost variables to the celery workers - or alternatively, how do I get my django settings to this worker thread (that successfully load the apache variables)? I would like to stick with using the apache virtual host approach to define the variables if possible as there are many settings getting pulled from there.

How to use celery to run SQL and get returned result from DB?

I am using Flask, Celery, Redis and Mysql to build website. Now I am facing one problem. I want to send every SQL query to celery and once job is done I then get query result from celery.result.
Here is part of my code:
Manage.py
import os
from app import create_app, db
from app.models import Users, Items
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
app.app_context().push()
manager = Manager(app)
migrate = Migrate(app, db)
def make_shell_context():
return dict(app=app, db=db, Users=Users, Items=Items)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
query.py
from .models import Items, Users
from sqlalchemy import desc
from app import create_celery_app
celery = create_celery_app()
#celery.task
def user_query(id):
return Users.query.filter_by(id = id).first()
view.py
from ..query import user_query
...
userresult = user_query.delay(1)
main.py
from flask import Blueprint
main = Blueprint('main', __name__)
from . import views, errors
app.py
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from config import config, Config
from celery import Celery
from flask.ext.sqlalchemy import SQLAlchemy
import os
bootstrap = Bootstrap()
moment = Moment()
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
moment.init_app(app)
db.init_app(app)
from main import main as main_blueprint
app.register_blueprint(main_blueprint)
return app
def create_celery_app(app=None):
app = app or create_app(os.getenv('FLASK_CONFIG') or 'default')
celery = Celery(__name__, broker=app.config['CELERY_BROKER_URL'], include=['app.query'])
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
return celery
When I run celery worker I get error:
File "/home/yx/Documents/flasky/venv/bin/celery", line 11, in <module>
sys.exit(main())
File "/home/yx/Documents/flasky/venv/local/lib/python2.7/site-packages/celery/__main__.py", line 30, in main
main()
File "/home/yx/Documents/flasky/venv/local/lib/python2.7/site-packages/celery/bin/celery.py", line 81, in main
cmd.execute_from_commandline(argv)
File "/home/yx/Documents/flasky/venv/local/lib/python2.7/site-packages/celery/bin/celery.py", line 770, in execute_from_commandline
super(CeleryCommand, self).execute_from_commandline(argv)))
File "/home/yx/Documents/flasky/venv/local/lib/python2.7/site-packages/celery/bin/base.py", line 309, in execute_from_commandline
argv = self.setup_app_from_commandline(argv)
File "/home/yx/Documents/flasky/venv/local/lib/python2.7/site-packages/celery/bin/base.py", line 469, in setup_app_from_commandline
self.app = self.find_app(app)
File "/home/yx/Documents/flasky/venv/local/lib/python2.7/site-packages/celery/bin/base.py", line 489, in find_app
return find_app(app, symbol_by_name=self.symbol_by_name)
File "/home/yx/Documents/flasky/venv/local/lib/python2.7/site-packages/celery/app/utils.py", line 229, in find_app
sym = symbol_by_name(app, imp=imp)
File "/home/yx/Documents/flasky/venv/local/lib/python2.7/site-packages/celery/bin/base.py", line 492, in symbol_by_name
return symbol_by_name(name, imp=imp)
File "/home/yx/Documents/flasky/venv/local/lib/python2.7/site-packages/kombu/utils/__init__.py", line 96, in symbol_by_name
module = imp(module_name, package=package, **kwargs)
File "/home/yx/Documents/flasky/venv/local/lib/python2.7/site-packages/celery/utils/imports.py", line 101, in import_from_cwd
return imp(module, package=package)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/yx/Documents/flasky/app/query.py", line 6, in <module>
celery = create_celery_app()
File "/home/yx/Documents/flasky/app/__init__.py", line 29, in create_celery_app
app = app or create_app(os.getenv('FLASK_CONFIG') or 'default')
File "/home/yx/Documents/flasky/app/__init__.py", line 24, in create_app
from main import main as main_blueprint
File "/home/yx/Documents/flasky/app/main/__init__.py", line 5, in <module>
from . import views, errors
File "/home/yx/Documents/flasky/app/main/views.py", line 7, in <module>
from ..query import user_query
ImportError: cannot import name user_query
But user_query is from query.py, so does anyone know if I miss something?
Thank you.

Flask-Migrate Error: 'ConfigParser.NoSectionError: No section: 'alembic''

For the last few weeks I've been building a website mostly based on Miguel Grinberg's book 'Flask Web Development'. This is my 'manage.py' file for reference:
import os
from app import create_app, db
from app.models import User, Role, Permission, Post
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
def make_shell_context():
return dict(app=app, db=db, User=User, Follow=Follow, Role=Role,
Permission=Permission, Post=Post)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
And this is my app/__init.py file:
from flask import Flask #session, flash, url_for
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from config import config
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
mail = Mail()
moment = Moment()
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
login_manager.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
from main import main as main_blueprint
from .auth import auth as auth_blueprint
app.register_blueprint(main_blueprint)
app.register_blueprint(auth_blueprint, url_prefix = '/auth')
return app
As you can see it's a relatively bare-bones project, but it was going well until a few days ago when I accidentally deleted my migrations folder, which up until that point was working without perfectly fine. When I attempted to set up the migrations folder again, I got this error:
(website1)joshua#joshua-ThinkPad-Edge-E430 ~/website/website1 $ python manage.py db migrate
Traceback (most recent call last):
File "manage.py", line 29, in <module>
manager.run()
File "/home/joshua/.virtualenvs/website1/lib/python2.7/site-packages/flask_script/__init__.py", line 412, in run
result = self.handle(sys.argv[0], sys.argv[1:])
File "/home/joshua/.virtualenvs/website1/lib/python2.7/site-packages/flask_script/__init__.py", line 383, in handle
res = handle(*args, **config)
File "/home/joshua/.virtualenvs/website1/lib/python2.7/site-packages/flask_script/commands.py", line 216, in __call__
return self.run(*args, **kwargs)
File "/home/joshua/.virtualenvs/website1/lib/python2.7/site-packages/flask_migrate/__init__.py", line 153, in migrate
config = _get_config(directory, opts=['autogenerate'])
File "/home/joshua/.virtualenvs/website1/lib/python2.7/site-packages/flask_migrate/__init__.py", line 51, in _get_config
config.set_main_option('script_location', directory)
File "/home/joshua/.virtualenvs/website1/lib/python2.7/site-packages/alembic/config.py", line 201, in set_main_option
self.file_config.set(self.config_ini_section, name, value)
File "/home/joshua/anaconda/lib/python2.7/ConfigParser.py", line 753, in set
ConfigParser.set(self, section, option, value)
File "/home/joshua/anaconda/lib/python2.7/ConfigParser.py", line 396, in set
raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'alembic'
I'm not really sure what to do about this, I've tried dropping then re-creating my database and running db migrate again but I got the same error as before. I also tried uninstalling and reinstalling alembic but with no luck.
I'm not really sure what do do at this point, up until now whenever I've had an issue with the tutorial I took the time to figure it out on my own since I want to understand how everything works, but I'm totally stumped on this one.
Courtesy Dauros: I neglected to run python manage.py db init.

Categories