You can make a custom builder for the session that will re-create the engine and scoped session when your rules dictate it. Something like
class SessionManager(object):
def __init__(self):
self.session = None
def get_session(self):
#
return existing session or make a new engine and scoped_session
To make this class transparent, use Werkzeug's LocalProxy. The code that uses the sessions won't have to change at all.
session_manager = SessionManager() db_session = LocalProxy(session_manager.get_session)
These method above are in addition to anycodings_flask-sqlalchemy your main SQLALCHEMY_DATABASE_URI that anycodings_flask-sqlalchemy you should set. While you can anycodings_flask-sqlalchemy dynamically bind the other database on anycodings_flask-sqlalchemy user logins method.,You will need to use SQLALCHEMY_BINDS anycodings_flask-sqlalchemy method to bind to mult[le client anycodings_flask-sqlalchemy database.,The only problem is, the anycodings_flask-sqlalchemy SQLALCHEMY_DATABASE_URI configuration is anycodings_flask-sqlalchemy done statically. I may need to switch anycodings_flask-sqlalchemy between anycodings_flask-sqlalchemy mysql://username:password@Y.Y.Y.Y/db1 and anycodings_flask-sqlalchemy mysql://username:password@Z.Z.Z.Z/db1 (or anycodings_flask-sqlalchemy any other arbitrary MySQL URI), depending on anycodings_flask-sqlalchemy which client is making the request.,I've found some similar questions (see anycodings_flask-sqlalchemy below), but I have yet to figure out a clean anycodings_flask-sqlalchemy way to do it when using the Flask-SQLAlchemy anycodings_flask-sqlalchemy extension specifically.
On the Flask-SQLAlchemy site, a simple anycodings_flask-sqlalchemy example is shown along the lines of:
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@Y.Y.Y.Y/db1' db = SQLAlchemy(app) class User(db.Model): # Etc.
If you're using flask-sqlalchemy 0.12 or anycodings_flask-sqlalchemy later, this feature is supported with anycodings_flask-sqlalchemy BINDS.
SQLALCHEMY_DATABASE_URI = 'postgres://localhost/main'
SQLALCHEMY_BINDS = {
'users': 'mysqldb://localhost/users',
'appmeta': 'sqlite:////path/to/appmeta.db'
}
And you can specify connection database anycodings_flask-sqlalchemy in the model definition.
class User(db.Model):
__bind_key__ = 'users'
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(80), unique = True)
You could do something like this. FYI anycodings_flask-sqlalchemy this is pure SQLAlchemy, not with anycodings_flask-sqlalchemy Flask-SQLAlchemy. Hopefully you need anycodings_flask-sqlalchemy this for read-only stuff. You can figure anycodings_flask-sqlalchemy out some other stuff to have to write anycodings_flask-sqlalchemy stuff, like even listeners on your anycodings_flask-sqlalchemy session/models
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base # an Engine, which the Session will use for connection # resources some_engine_1 = create_engine('postgresql://scott:tiger@localhost/') some_engine_2 = create_engine('postgresql://adriel:velazquez@localhost/') # create a configured "Session" class Session_1 = sessionmaker(bind = some_engine_1) Session_2 = sessionmaker(bind = some_engine_2) # create a Session session_1 = Session_1() session_2 = Session_2() Base = declarative_base() class ModelBase(Base): #different custom queries for each database master_query = session_1.query_property() client_1_query = session_2.query_property() class User(ModelBase): pass #ETC # #Accessing the different databases: User.master_query.filter(User.id == 1).all() User.client_1_query.filter(User.id == 1).all()
You will need to use SQLALCHEMY_BINDS anycodings_flask-sqlalchemy method to bind to mult[le client anycodings_flask-sqlalchemy database.
app.config['SQLALCHEMY_BINDS'] = {
'user1': mysql database ', user2: mysqal2database'
}
You will also need to refer to the anycodings_flask-sqlalchemy bind_key name such as "user1" in the anycodings_flask-sqlalchemy model for example:
class users(db.Model):
__bind_key__
id = db.Column(Integer, primary_key = True)
name = db.Column(String)
Last Updated : 15 Oct, 2021,GATE CS 2021 Syllabus
Example:
@app.route('allow/<variable name>')
OR
@app.route('allow/<converter: variable name>')
Let’s allow the user with having an ID of less than 25 to visit the page. The modified code with dynamic URL binding is given below. The function uses the <variable name> passed in route() decorator as an argument.
@app.route('/allow/<int:Number>')
def allow(Number):
if Number < 25:
return f'You have been allowed to enter because\
your number is {str(Number)}'
else:
return f'You are not allowed'
A dictionary that maps bind keys to SQLAlchemy connection URIs. For more information about binds see Multiple Databases with Binds.,Certain database backends may impose different inactive connection timeouts, which interferes with Flask-SQLAlchemy’s connection pooling.,For a complete list of connection URIs head over to the SQLAlchemy documentation under (Supported Databases). This here shows some common connection strings.,Number of seconds after which a connection is automatically recycled. This is required for MySQL, which removes connections after 8 hours idle by default. Note that Flask-SQLAlchemy automatically sets this to 2 hours if MySQL is used. Some backends may use a different default timeout value. For more information about timeouts see Timeouts.
dialect + driver: //username:password@host:port/database
postgresql: //scott:tiger@localhost/mydatabase
mysql: //scott:tiger@localhost/mydatabase
oracle: //scott:tiger@127.0.0.1:1521/sidname
#Unix / Mac(note the four leading slashes)
sqlite: ////absolute/path/to/foo.db
#Windows(note 3 leading forward slashes and backslash escapes)
sqlite: ///C:\\absolute\\path\\to\\foo.db
#Windows(alternative using raw string)
r 'sqlite:///C:\absolute\path\to\foo.db'
from sqlalchemy
import MetaData
from flask
import Flask
from flask_sqlalchemy
import SQLAlchemy
convention = {
"ix": 'ix_%(column_0_label)s',
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s"
}
metadata = MetaData(naming_convention = convention)
db = SQLAlchemy(app, metadata = metadata)
SQLite connects to file-based databases, using the Python built-in module sqlite3 by default.,As SQLite connects to local files, the URL format is slightly different. The “file” portion of the URL is the filename of the database. For a relative file path, this requires three slashes:,The standard calling form is to send the URL as the first positional argument, usually a string that indicates database dialect and connection arguments:,QueuePool is not used by default for SQLite engines. See SQLite for details on SQLite connection pool usage.
from sqlalchemy
import create_engine
engine = create_engine('postgresql://scott:tiger@localhost:5432/mydatabase')
dialect + driver: //username:password@host:port/database
postgresql + pg8000: //dbuser:kx%40jj5%2Fg@pghost10/appdb
>>>
import urllib.parse >>>
urllib.parse.quote_plus("kx@jj5/g")
'kx%40jj5%2Fg'
# default engine = create_engine('postgresql://scott:tiger@localhost/mydatabase') # psycopg2 engine = create_engine('postgresql+psycopg2://scott:tiger@localhost/mydatabase') # pg8000 engine = create_engine('postgresql+pg8000://scott:tiger@localhost/mydatabase')
# default engine = create_engine('mysql://scott:tiger@localhost/foo') # mysqlclient(a maintained fork of MySQL - Python) engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo') # PyMySQL engine = create_engine('mysql+pymysql://scott:tiger@localhost/foo')