flask-sqlalchemy cross database with "dynamic" schema

  • Last Update :
  • Techknowledgy :

Never tried this myself, but you can probably force __table_args__ to have lazy evaluation by making it a declared_attr.

from sqlalchemy.ext.declarative
import declared_attr

class MyModel(MySQLSettings, MyOtherMixin, Base):
   __tablename__ = 'my_model'

@declared_attr
def __table_args__(cls):
   return {
      'schema': current_app.config['OTHER_DB_NAME']
   }

Suggestion : 2

Never tried this myself, but you can probably force __table_args__ to have lazy evaluation by making it a declared_attr.

Never tried this myself, but you can probably force __table_args__ to have lazy evaluation by making it a declared_attr.

from sqlalchemy.ext.declarative
import declared_attrclass MyModel(MySQLSettings, MyOtherMixin, Base): __tablename__ = 'my_model'
@declared_attr def __table_args__(cls): return {
   'schema': current_app.config['OTHER_DB_NAME']
}

Suggestion : 3

I'm attempting to use the "application factory" pattern from flask, but I seem to have a chicken-and-egg problem with my models. http://flask.pocoo.org/docs/patterns/appfactories/,Answer link : https://codehunter.cc/a/flask/flask-sqlalchemy-cross-database-with-dynamic-schema,(Side note - an easy fix for this is to configure Sqlalchemy to always output the schema name in the query, no matter what - but I can't seem to find a setting for this.),So, now I have models being defined that require the schema name from the config, but with no schema from the config to put in the class definition. I also may simply be missing something in flask I wasn't aware of.

However, in this case, I have two sets of models, one from the default database, and another set on another db connection - and I'd like to cross-db join. I know that the usual method is to add

__table_args__ = {
   'schema': 'other\_db\_name'
}

Suggestion : 4

Last Updated : 28 Dec, 2021,GATE CS 2021 Syllabus

In any directory where you feel comfortable create a folder and open the command line in the directory. Create a python virtual environment using the command below.

python -m venv <name>

Once the command is done running activate the virtual environment using the command below.

<name>\scripts\activate

Now, install Flask using pip(package installer for python). Simply run the command below.

pip install Flask

In the command line which is navigated to the project directory and virtual environment running, we need to run the following commands. 

python

The above command will initiate a python bash in your command line where you can use further lines of code to create your data table according to your model class in your database. 

from app
import db
db.create_all()

Suggestion : 5

marshmallow can be used to validate configuration according to a schema. Below is a schema that could be used to validate package.json files. This example demonstrates the following features:,Examples Validating package.json Text Analysis API (Bottle + TextBlob) Quotes API (Flask + SQLAlchemy) ToDo API (Flask + Peewee) Inflection (Camel-casing Keys) ,But if we pass an invalid package.json file…,After registering a user and creating some todo items in the database, here is an example response.

import sys
import json
from packaging
import version
from pprint
import pprint

from marshmallow
import Schema, fields, INCLUDE, ValidationError

class Version(fields.Field):
   ""
"Version field that deserializes to a Version object."
""

def _deserialize(self, value, * args, ** kwargs):
   try:
   return version.Version(value)
except version.InvalidVersion as e:
   raise ValidationError("Not a valid version.") from e

def _serialize(self, value, * args, ** kwargs):
   return str(value)

class PackageSchema(Schema):
   name = fields.Str(required = True)
version = Version(required = True)
description = fields.Str(required = True)
main = fields.Str(required = False)
homepage = fields.URL(required = False)
scripts = fields.Dict(keys = fields.Str(), values = fields.Str())
license = fields.Str(required = True)
dependencies = fields.Dict(keys = fields.Str(), values = fields.Str(), required = False)
dev_dependencies = fields.Dict(
   keys = fields.Str(),
   values = fields.Str(),
   required = False,
   data_key = "devDependencies",
)

class Meta:
   # Include unknown fields in the deserialized output
unknown = INCLUDE

if __name__ == "__main__":
   pkg = json.load(sys.stdin)
try:
pprint(PackageSchema().load(pkg))
except ValidationError as error:
   print("ERROR: package.json is invalid")
pprint(error.messages)
sys.exit(1)
{
   "name": "dunderscore",
   "version": "1.2.3",
   "description": "The Pythonic JavaScript toolkit",
   "devDependencies": {
      "pest": "^23.4.1"
   },
   "main": "index.js",
   "scripts": {
      "test": "pest"
   },
   "license": "MIT"
}
$ python examples/package_json_example.py < package.json
{'description': 'The Pythonic JavaScript toolkit',
'dev_dependencies': {'pest': '^23.4.1'},
'license': 'MIT',
'main': 'index.js',
'name': 'dunderscore',
'scripts': {'test': 'pest'},
'version': <Version('1.2.3')>}
{
   "name": "dunderscore",
   "version": "INVALID",
   "homepage": "INVALID",
   "description": "The Pythonic JavaScript toolkit",
   "license": "MIT"
}
$ python examples / package_json_example.py < invalid_package.json
ERROR: package.json is invalid {
   'homepage': ['Not a valid URL.'],
   'version': ['Not a valid version.']
}
from bottle
import route, request, run
from textblob
import TextBlob
from marshmallow
import Schema, fields

class BlobSchema(Schema):
   polarity = fields.Float()
subjectivity = fields.Float()
chunks = fields.List(fields.String, attribute = "noun_phrases")
tags = fields.Raw()
discrete_sentiment = fields.Method("get_discrete_sentiment")
word_count = fields.Function(lambda obj: len(obj.words))

def get_discrete_sentiment(self, obj):
   if obj.polarity > 0.1:
   return "positive"
elif obj.polarity < -0.1:
   return "negative"
else:
   return "neutral"

blob_schema = BlobSchema()

@route("/api/v1/analyze", method = "POST")
def analyze():
   blob = TextBlob(request.json["text"])
return blob_schema.dump(blob)

run(reloader = True, port = 5000)

Suggestion : 6

SQLAlchemy is a popular SQL toolkit and Object Relational Mapper. It is written in Python and gives full power and flexibility of SQL to an application developer. It is an open source and cross-platform software released under MIT license.,SQLAlchemy lets you just use strings, for those cases when the SQL is already known and there isn’t a strong need for the statement to support dynamic features. The text() construct is used to compose a textual statement that is passed to the database mostly unchanged.,Using the above command, we can download the latest released version of SQLAlchemy from python.org and install it to your system.,For bulk updates, we shall use update() method of the Query object. Let us try and give a prefix, ‘Mr.’ to name in each row (except ID = 2). The corresponding update() statement is as follows −

Any version of Python higher than 2.7 is necessary to install SQLAlchemy. The easiest way to install is by using Python Package Manager, pip. This utility is bundled with standard distribution of Python.

pip install sqlalchemy

In case of anaconda distribution of Python, SQLAlchemy can be installed from conda terminal using the below command −

conda install - c anaconda sqlalchemy

It is also possible to install SQLAlchemy from below source code −

python setup.py install

The create_engine() function takes the database as one argument. The database is not needed to be defined anywhere. The standard calling form has to send the URL as the first positional argument, usually a string that indicates database dialect and connection arguments. Using the code given below, we can create a database.

>>> from sqlalchemy
import create_engine
   >>>
   engine = create_engine('sqlite:///college.db', echo = True)

For a MySQL database, use the below command −

engine = create_engine("mysql://user:pwd@localhost/college", echo = True)