AssertionError: DatabaseBackend is not running - sqlalchemy

In FastAPI, I need to dynamically connect to a database after a POST request, i.e, in the POST request body, I receive database_name on which I need to connect.
So I have tried this:
import databases
#app.post("/computers/", response_model=Computer)
async def create_computer(computer: ComputerIn):
DATABASE_URL = "postgresql://username:password#localhost/"+computer.database_name
database = databases.Database(DATABASE_URL)
database.connect()
...
But I get the following error:
File
"/home/.local/lib/python3.8/site-packages/databases/backends/postgres.py",
line 169, in acquire
assert self._database._pool is not None, "DatabaseBackend is not running" AssertionError: DatabaseBackend is not running
Any idea why this might not work ?
Thanks

Two things:
You forgot the await keyword. Here's an example taken from the github's page https://github.com/encode/databases
# Create a database instance, and connect to it.
from databases import Database
database = Database('sqlite+aiosqlite:///example.db')
await database.connect()
# Create a table.
query = """CREATE TABLE HighScores (id INTEGER PRIMARY KEY, name VARCHAR(100), score INTEGER)"""
await database.execute(query=query)
It is not good practice to connect to a database on every request. It is better to connect at runtime and then share the connection pool, so that at every request a new connection is not create. Instead, the currently active connection pool is used, wasting fewer resource.
See https://fastapi.tiangolo.com/advanced/events/ for further information

Related

completion of jmeter execution generate the csv file ,how read the csv file in groovy and how to automaticaly pass those values in query ?, ?,? places [duplicate]

Please give step by step process
How to connect MySQL db and excute queries and stored those results in db table by using jsr223 sampler? Please give sample code this topic
Download MySQL JDBC Driver and drop it to "lib" folder of your JMeter installation (or other folder in JMeter Classpath)
Restart JMeter to pick up the .jar
Add Thread Group to your Test Plan
Add JSR223 Sampler to your Thread Group
Put the following code into "Script" area:
import groovy.sql.Sql
def url = 'jdbc:mysql://your-database-host:your-database-port/your-database-name'
def user = 'your-username'
def password = 'your-password'
def driver = 'com.mysql.cj.jdbc.Driver'
def sql = Sql.newInstance(url, user, password, driver)
def query= 'INSERT INTO your-table-name (your-first-column, your-second-column) VALUES (?,?)'
def params = ['your-first-value', 'your-second-value']
sql.executeInsert query, params
sql.close()
Change your-database-host, your-database-port, etc. to real IP address, port, credentials, table name, column name, etc.
Enjoy.
More information:
Apache Groovy - Working with a relational database
Apache Groovy - Why and How You Should Use It
P.S. I believe using JDBC Request sampler would be way faster and easier

SQLAlchemy core -How do I access an existing Postgresql database?

I have created the below class
This seems to give me access to the schema of the table but not to the table itself. Most of the examples I am seeing, including the one in the manual follow the code that was used to create the tables
class DataBase:
def __init__(self,user, password, db, host='localhost', port=5432):
'''Initializes the connection and a metadata objects'''
# We connect with the help of the PostgreSQL URL
# postgresql://federer:grandestslam#localhost:5432/tennis
url = 'postgresql://{}:{}#{}:{}/{}'
url = url.format(user, password, host, port, db)
# The return value of create_engine() is our connection object
self.engine = sqlalchemy.create_engine(url, client_encoding='utf8', echo=False) #echo=True enable logging (This is Python loggin module)
self.conn=self.engine.connect()
# We then bind the connection to MetaData()
self.meta = sqlalchemy.MetaData(bind=self.con, reflect=True)
And then I use
if __name__ == '__main__':
db=DataBase('nme','nme','nme')
db.meta.tables['tablename']
But this is giving me access to the schema of the table
I want to insert a record in this table after the table was created
Edit: this worked, thank you
known_devices=Table('known_devices',self.meta,autoload=True)
ins=known_devices.insert().values(
....
)
result=self.conn.execute(ins)
Looking at
https://docs.sqlalchemy.org/en/latest/core/reflection.html and
https://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.Insert.values
it should be something along the lines of
yourtable=Table('tablename', meta, autoload=True)
conn.execute(yourtable.insert(), field="content")

In Shiny app, how to refresh data from MySQL db every 10 minutes if any change occured

I've made dashboard using shiny, shinydashboard and RMySQL package.
Following is what I wrote in order to refresh data every 10 minutes if any change occured.
In global.R
con = dbConnect(MySQL(), host, user, pass, db)
check_func <- function() {dbGetQuery(con, check_query}
get_func <- function() {dbGetQuery(con, get_query}
In server.R
function(input, output, session) {
# check every 10 minutes for any change
data <- reactivePoll(10*60*1000, session, checkFunc = check_func, valueFunc = get_func)
session$onSessionEnded(function() {dbDisconnect(con)})
However, above code infrequently generates corrupt connection handle error from check_func.
Warning: Error in .local: internal error in RS_DBI_getConnection: corrupt connection handle
Should I put dbConnect code inside server function?
Any better ideas?
link: using session$onsessionend to disconnect rshiny app from the mysql server
"pool" package is the answer: http://shiny.rstudio.com/articles/pool-basics.html
This adds a new level of abstraction when connecting to a database: instead of directly fetching a connection from the database, you will create an object (called a pool) with a reference to that database. The pool holds a number of connections to the database. ... Each time you make a query, you are querying the pool, rather than the database. ... You never have to create or close connections directly: the pool knows when it should grow, shrink or keep steady.
I've got answer from here. -> https://stackoverflow.com/a/39661853/4672289

INSERT throw errors

I'm developing an API with Nodejs and I have a create project endpoint and a create patient endpoint. Both of them work if I create the database tables with mySql.
But I need to run first create project which creates some tables to be used by create user endpoint. The problem comes when I call user endpoint and throws this:
** Connection to project psapp_demo successfully.
*** Error: ER_NO_SUCH_TABLE: Table 'psapp_demo_proposa58_pr.displayer_patient' doesn't exist
But database psapp_demo_proposa58_pr and table displayer_patient exist and are accessible throw PHPmyadmin.
Code for creating a new patient is based on a promise which is catching the error:
Services.user.create(connection,req,userId,req.body,clinicId)
.then((userId) => { req.userId = userId; next() })
.fail((err) => next(err))
Anyway, database created with a project endpoint also does not work with phpmyadmin so problem seems to realy on the database, not the code. This is the error where you can see I can even navigate with phpmyadmin throw that databases but are not located when I try to insert something:
A SELECT operation throws empty which is right. With a SELECT, there is not error.
Do you know why could it be happening? Thanks

Saved GORM domain object not showing up in mysql

I have a Message object that has log entries that are added as the message is processed.
Domain class Message has:
SortedSet messageLogEntries
static hasMany = [messageLogEntries: MessageLogEntry]
void addLogEntry(String entry) {
def mle = new MessageLogEntry(logEntry: entry)
this.addToMessageLogEntries(mle)
this.save(failOnError: true, flush: true)
log.debug(entry)
}
I can step through the code the entry is created and saved and allocated an id but when I query the database in MySql the entry is not there.
This was working but is not since I converted from mysql 5.5 to 5.6.10
Please help.
If this code is being executed inside a Hibernate transaction, you will not see it in the DB until the transaction is committed. Are you running this code inside an integration test or from a transactional execution stream (e.g. a service)?