Wednesday, June 14, 2017

Dynamic database connection Flask-SQLAlchemy

Leave a Comment

i need to connect two database. the default database is fixed but the other one is dynamic, its based on URL.

for example if url is : yourapp.myweb.com then second database name will be yourapp

i try connect database into init.py but its show me following error

builtins.AssertionError AssertionError: A setup function was called after the first request was handled.  This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late. To fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests. 

here is my init.py

from flask import Flask,session from flask_sqlalchemy import SQLAlchemy import os app = Flask(__name__,static_url_path='/static')  #  Database Connection database = request.url.split("/")[2].split(".")[0] app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root:root@localhost/main_database" app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['SQLALCHEMY_BINDS'] = {     'user_db': 'mysql+pymysql://root:root@localhost/database_'+str(database), #dynamic Connection } db = SQLAlchemy(app) db.create_all() db.create_all(bind=['user_db']) # db.init_app(app)  from . import views 

here is the viwe.py

@app.route('/login', methods = ['GET']) def index():     try:         from .model import Users         # Some Code     except Exception as e:         raise e         # return "Failed to login ! Please try again." 

here is the model.py

from application import db class Users(db.Model):     __bind_key__ = 'user_db'     __tablename__ = 'users'     id = db.Column(db.Integer, primary_key = True)     email = db.Column(db.String(50))     name = db.Column(db.String(50))     password = db.Column(db.String())      def __repr__(self):         return '<User %r>' % self.name 

1 Answers

Answers 1

As I said in one of my comments, this might be a problem with the database connection. Here's what I'd check for:

  1. First of all, make sure you have the right engine installed in your virtual environment (you can check easily by running pip list; just in case, let me insist that libraries need to be installed in a virtual environment). Make sure you have not pymysql, but the port to Python3, called mysqlclient. pymysql only works with Python2. In order to install this library, you need to install first the Python and MySQL development headers. For example, in Debian/Ubuntu:

    sudo apt-get install python-dev libmysqlclient-dev 

    Then you can install the library with the following command:

    pip install mysqlclient 
  2. If this is installed, make sure you can actually connect to the database using the library. Open a Python shell within the virtual environment and type the following (from the example in github):

    import pymysql.cursors  connection = pymysql.connect(host='<you_host>',                              user='<user>',                              password='<password>',                              db='<database_name>',                              charset='utf8mb4',                              cursorclass=pymysql.cursors.DictCursor)  try:     with connection.cursor() as cursor:         do_something() except:     pass 
  3. If this works, make sure you're running the most recent version of Flask (0.12 at the moment; this again you can check by running pip list), as there are several bugs related to running Flask in DEBUG mode that have been fixed over time.

  4. It's surely not the case here, but another sanity check is verifying that no other process is running on the port that you want to use for Flask.

If all of the above is working fine, I'd need to see a bit of the stack trace to figure out what is actually going on.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment