How to select config in `flask db migrate` - flask-migrate

I have both development db and production db connection strings in my .env.
LOCAL_DB_STRING="local_db"
DB_STRING="production_db"
LOCAL_APP_STATE="development"
When running app, the correct one is loaded using config.py:
class Config(object):
SQLALCHEMY_DATABASE_URI = os.environ.get("DB_STRING")
APP_STATE = os.environ.get("APP_STATE")
class DevConfig(Config):
SQLALCHEMY_DATABASE_URI = os.environ.get("LOCAL_DB_STRING")
APP_STATE = os.environ.get("LOCAL_APP_STATE")
and then in __init__.py create_app()
application.config.from_object(configs[config_name])
How can I use flask-migrate similar way - choosing which db (dev/prod) it uses for its commands?
Thanks for help!
SOLVED: I found out it was my mistake - I was getting APP_STATE from APP_STATE variable, but in my .env file there was LOCAL_APP_STATE. So flask db didn't get right environment.

There was mistake in my .env file - using LOCAL_APP_STATE instead of APP_STATE, which made flask db run default config.

Related

Why Flask does not traceback when it recognizes bad DB connection?

Could not find any answer to this, I try to create two separated objects for different configurations to separate development environment from production.
So I came up with this config.py file
class BaseConfig:
SECRET_KEY = 'MYSECRET'
class DevConfig(BaseConfig):
SQLALCHEMY_DATABASE_URI = 'sqlite:///market.db'
DEBUG = True
class ProdConfig(BaseConfig):
DEBUG = False
pg_user = 'admin'
pg_password = 'admin'
pg_db = 'mytable'
pg_host = 'localhost'
pg_port = '5432'
SQLALCHEMY_DATABASE_URI = f"postgresql://{pg_user}:{pg_password}#{pg_host}:{pg_port}/{pg_db}"
Now I have this config file, I want to test out and see failure by purpose when I create a Flask instance and read from ProdConfig object (Note: I still don't have Postgres instance running on localhost), but I expect for a connection failure when I start my app. But why it lets me to even run the application?
Project has one package, so here is __init__.py of one of my packages:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from market.config import DevConfig, ProdConfig
app = Flask(__name__)
app.config.from_object(ProdConfig) # Note this one!
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = "login_page"
login_manager.login_message_category = "info"
And I have a run.py outside of the package that imports this package, so:
from market import app
#Checks if the run.py file has executed directly and not imported
if __name__ == '__main__':
app.run()
I would expect Flask to fail immediately when the connection could not be established against the DB.

Debugging connection PostgreSQL Loopback 4

Im on a mac(OS 10.14) using nodejs 14 and PostgresSQL 12.
I just installed Loopback4 and after following this tutorial Im not able to use any of the enpoints that use Models, ie that connect to Postgres, I constantly get a timeout.
It seems like its not even reaching the Postgres Server, but the error gives no information, just that the request times out.
There are no issues with the Postgres server since I can connect and request information with other nodejs applications to the same database.
I also tried to set this as the host host: '/var/run/postgresql/', same result.
I now tried the approach with a Docker container, setting the datasource files as follows:
import {inject, lifeCycleObserver, LifeCycleObserver} from '#loopback/core';
import {juggler} from '#loopback/repository';
const config = {
name: 'mydb',
connector: 'postgresql',
url: 'postgres://postgres:mysecretpassword#localhost:5434/test',
ssl: false,
};
// Observe application's life cycle to disconnect the datasource when
// application is stopped. This allows the application to be shut down
// gracefully. The `stop()` method is inherited from `juggler.DataSource`.
// Learn more at https://loopback.io/doc/en/lb4/Life-cycle.html
#lifeCycleObserver('datasource')
export class PostgresSqlDataSource extends juggler.DataSource
implements LifeCycleObserver {
static dataSourceName = 'PostgresSQL';
static readonly defaultConfig = config;
constructor(
#inject('datasources.config.PostgresSQL', {optional: true})
dsConfig: object = config,
) {
super(dsConfig);
}
}
With that same url I can log on my command line from my mac.
Is there a way to add logging and print any connection error? Other ways to debug it?
[UPDATE]
As of today Loopback4 Postgres connector does not work properly with Nodejs 14.
When starting the application, instead of running
npm start, you can set the debug string by running:
DEBUG=loopback:connector:postgresql npm start
If you want it to be more generic, you can use:
DEBUG=loopback:* npm start

Meteor deploying on Modulus

Modulus deployments is perfect without any problems, but is not working. I have created a database on Modulus with the same name on the Meteor app.
http://wikimicroscope-13216.onmodulus.net/
Console log in Modulus:
Error: URL must be in the format mongodb://user:pass#host:port/dbname
at Error (<anonymous>)
at exports.parse (/mnt/data/2/node_modules/mongodb/lib/mongodb/connection/url_parser.js:15:11)
at Function.MongoClient.connect (/mnt/data/2/node_modules/mongodb/lib/mongodb/mongo_client.js:164:16)
at Function.Db.connect (/mnt/data/2/node_modules/mongodb/lib/mongodb/db.js:2035:23)
at new MongoConnection (packages/mongo-livedata/mongo_driver.js:151)
at new MongoInternals.RemoteCollectionDriver (packages/mongo-livedata/remote_collection_driver.js:4)
at Object.<anonymous> (packages/mongo-livedata/remote_collection_driver.js:44)
at Object.defaultRemoteCollectionDriver (packages/underscore/underscore.js:750)
at new Meteor.Collection (packages/mongo-livedata/collection.js:72)
at packages/accounts-base/accounts_common.js:122
[2014-05-23T16:02:46.435Z] Application CRASH detected. Exit code 8.
[2014-05-23T16:02:47.472Z] Application restarted.
I have set mongo_url and root_url before. Here are my environment variables:
CONNECTION STRINGS
MONGO URI
mongodb://<user>:<pass>#novus.modulusmongo.net:27017/iZ3anope
MONGO CONSOLE
mongo novus.modulusmongo.net:27017/iZ3anope -u <user> -p <pass>
I have deployed with different node versions like v0.10.25, v0.10.28. It is not working.
Beside on the browser there is the messages:
!Unable to connect to any application instances.!
and in the console inspector in Chrome / local store I find a message like this:
BiDefender_BLock {"verdict":"TRACKER","hitList":""}
Thanks!
You need to fill in <user>:<pass> with the username and password you set for the database.
I had this error and solve it by executing:
modulus env set MONGO_URL "mongodb://myUser:myPass#proximus.modulusmongo.net:27017/6sd54f5f?autoReconnect=true&connectTimeoutMS=60000"
instead of:
modulus env set MONGO_URL "mongodb://myUser:myPass#proximus.modulusmongo.net:27017/6sd54f5f ?autoReconnect=true&connectTimeoutMS=60000"
If you see, I added an extra space before the '?'
When I look at logs in modulus web interface, it told me database name cannot contains character ' ' (space)
I also just had this problem and fixed it by restarting my app

How to use inmemory data base for Junits in Play 2.2

I am working on play 2.2 for my application. In my application.conf, I have specified the connection properties as below.
db.testdb.driver=org.h2.Driver
db.testdb.url="jdbc:h2:mem:play"
db.testdb.user=xxxxx
db.testdb.password=xxxx
And When I try to access the h2 db in my Jnuit , I am getting connection "testdb" undefined error.
Junit:
FakeApplication app = Helpers.fakeApplication(Helpers.inMemoryDatabase("testdb"));
Helpers.start(app);
Please help me to connect h2 db from my Junit.
Thanks in adv.
Try to use default setting for h2 db:
db.default.driver=org.h2.Driver#
db.default.url="jdbc:h2:mem:play#"
db.default.user=sa
db.default.password=""

problems using Zend_Db when running php as cli script

I am trying to add some administration scripts to a Zend Framework project, that will end up being run nightly via cron.
However I've hit my first problem with the script when trying to use Zend_Db. I am currently doing a very simple SQL call to get some results and just display them using var_dump() however I get the following error message:
SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
The script so far looks like this:
<?php
chdir(dirname(__FILE__));
error_reporting(E_ALL|E_STRICT);
ini_set('display_errors', 1);
date_default_timezone_set('Europe/London');
//directory setup and class loading
set_include_path('.' . PATH_SEPARATOR . '../library/' . PATH_SEPARATOR . '../application/models/'
. PATH_SEPARATOR . '../library/MyApp/'
. PATH_SEPARATOR . get_include_path());
include "Zend/Loader/Autoloader.php";
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->setFallbackAutoloader(true);
//start sessions
Zend_Session::start();
//read configuration data
$config = new Zend_Config_Xml('../application/config/config.xml', 'app');
//we create an ability to capture errors and write them to an error log if there are problems.
$log = new Zend_Log();
$writer = new Zend_Log_Writer_Stream($config->log->logfile);
$log->addWriter($writer);
$filter = new Zend_Log_Filter_Priority((int)$config->log->level);
$log->addFilter($filter);
//we now need to get the list of graduates that need to have their CV's removed from the search engine
$date = new Zend_Date();
$date->sub(3, Zend_Date::MONTH);
echo $date->get(Zend_Date::ISO_8601);
$sql = "SELECT userid, guid FROM users WHERE lastlogin = ? AND active = 1";
$db = Zend_Db::factory($config->database);
try{
$results = $db->fetchAll($sql, $date->get(Zend_Date::ISO_8601));
var_dump($results);
}catch(Zend_Db_Exception $dbe){
$log->debug($dbe->getMessage()."\n".$dbe->getTraceAsString());
}
//close database.
if($db->isConnected()){
$db->closeConnection();
}
What am I missing? I know that the database connection settings in the Zend_Config object works and the web application is running fine with no issues.
I am running this using Zend Framework v1.7.6 at present.
Also are there any generic tips for using the Zend Framework in a cli script?
Many thanks.
PHP will try to connect to mysql via tcp/ip, unless the mysql server is on the same machine as the script and "localhost" is used as the db host. Then it will use a filesystem socket.
It could be that mysql cannot create /tmp/mysql.sock due to permissions, or that it's not configured to do so. The Mysql manual should have more on that.
A quick way to get around this for now should be to change the db host in your Zend_Db settings to an actual ip mysql listens on, not "localhost" or "127.0.0.1".
also check your php.ini and look for the mysql_sock
this is often a trap for Mac users with Mamp installed: Snow Leopard comes with a php configured which is separate to the ph included with Mamp