0

My __init__.py file

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import app_config


db = SQLAlchemy()

def create_app(config_name):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')

    db.init_app(app)

    @app.route('/')
    def index():
        return 'Hello, user'

    return app

I will find tutorial for flask build crud app flask

My config.py file:

import os

# Set path for our db
basedir = os.path.dirname(os.path.abspath(__file__))


class Config:
    DEBUG = True


class DevConfig(Config):
    DEBUG = True
    SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir,
                                                          'bookshell.db')
    SQLALCHEMY_ECHO = True
    SQLALCHEMY_TRACK_MODIFICATIONS = False


class ProdConfig(Config):
    DEBUG = False


class TestConfig(Config):
    DEBUG = True


app_config = {
    'development': DevConfig,
    'production': ProdConfig,
    'testing': TestConfig
}

run.py file

import os

# Import from app/__init__
from app import create_app


config_name = os.getenv('FLASK_CONFIG', 'development')
app = create_app(config_name)

if __name__ == '__main__':
    app.run()

So, I tried to configure my own config.py file, but I get an error

FileNotFoundError: [Errno 2] Unable to load configuration file (No such file or directory): '/Users/yevhensurzhenko/Desktop/Simple_login_form/instance/config.py'

But when I change some configuration, and when try to reload page it give me 405 error method not allowed or

app.config.from_object(app_config[config_name])
KeyError: <flask.cli.ScriptInfo object at 0x1038a5b70>

So, I made some changes, like

In config.py add

app_config = {
    ..
    'default': DevConfig
} 

In __init__.py create instance dir.

from instance import config

And now I get output from func that I create in __init__.py, in create__app()...

@app.route('/')
def index():
    return 'Hello, user'

But, FLASK_CONFIG not change, it work only production, wtf:(

  • Why do you use both `from_object` and `from_pyfile` at the same time? Only `from_object` should do the job. – bc291 Feb 20 '19 at 23:41
  • Also where do you set `FLASK_CONFIG` environment variable? I would recommend to set that variable in separate file with .env extensions. After that load it via `python-dotenv` library. – bc291 Feb 20 '19 at 23:48
  • Example: https://stackoverflow.com/a/52164534/8916412 – bc291 Feb 20 '19 at 23:54
  • Open again __init__.py in /app dir, it's already commit `#app.config.from_pyfile('config.py')` Thanks, for advise, – Yevhen Surzhenko Feb 21 '19 at 10:16

0 Answers0