2

I am working on flask app and trying to create user input form through which user can connect to their database.I just want to provide functionally to the users so that they can make a connection from flask application to the database using user interface instead of providing all configuration values in config.py file.

I have written view functions to render flask wtform and accepting input from form and creating sqlalchemy database uri indside a view function.I am not able create sqlalchemy database uri as a globally so that it can be pass to flask application object.

__ init__.py

from flask import Flask,render_template,request
from flask_bootstrap import Bootstrap
from app.forms import ConnectDB  

def create_app():
   app = Flask(__name__)
   Bootstrap(app)
   app.config['SECRET_KEY'] = "123456789"

@app.route('/')
def index():
    form = ConnectDB()
    return render_template('index.html', form=form )
@app.route('/connect/' , methods=['GET','POST'])

def connect():
    form = ConnectDB()
    if request.method == 'POST' and form.validate():
        database = form.database.data
        username = form.username.data
        password = form.password.data
        host = form.host.data 
        port = form.port.data
        database_name = form.database_name.data

        uri = "{DATABASE_DIALECT}://{DB_USER}:{DB_PASSSWORD}@{DB_ADDRESS}:
               {DB_PORT}/{DATABASE_NAME}".format(DATABASE_DIALECT =database,
                DB_USER = username,DB_PASSSWORD = password,DB_ADDRESS =host,
                DB_PORT = port,DATABASE_NAME = database_name)

      config['SQLALCHEMY_DATABASE_URI'] = uri

from app.models import db
db.init_app(app)

# Blueprints   
from app.views import geoit
app.register_blueprint(geoit)

return app

I know SQLALCHEMY_DATABASE_URI became local to connect view function and can not access outside of view.

But I don't know other possible way so that i can load database configurations in the flask app using user input.

Please help out for this problem.

Mayank Soni
  • 93
  • 12
  • https://stackoverflow.com/questions/1857465/with-sqlalchemy-how-to-dynamically-bind-to-database-engine-on-a-per-request-basi – abigperson Nov 22 '17 at 12:43
  • Possible duplicate of [With sqlalchemy how to dynamically bind to database engine on a per-request basis](https://stackoverflow.com/questions/1857465/with-sqlalchemy-how-to-dynamically-bind-to-database-engine-on-a-per-request-basi) – Luis Orduz Nov 22 '17 at 15:41
  • Thanks for the reply...but this is not desired solution for my qustion. – Mayank Soni Nov 23 '17 at 05:28
  • @MayankSoni have you found a solution for this? – scientific_explorer Dec 06 '18 at 14:01

0 Answers0