Airflow Scheduler with SQL Server backend and pyodbc - sql-server

I have setup Airflow a SQL Server as backend (SQL Azure). Init DB is successful. I am trying to run a simple dag every 2 minutes.
The dag has 2 tasks:
print date
sleep
When it start the airflow scheduler, it creates tasks instances for both the tasks, the first one succeeds & the second one seems to be stuck in "running" state.
Looking at scheduler logs, I see the following error repeatedly.
[2019-01-04 11:38:48,253] {jobs.py:397} ERROR - Got an exception! Propagating...
Traceback (most recent call last):
File "/home/sshuser/.local/lib/python2.7/site-packages/airflow/jobs.py", line 389, in helper
pickle_dags)
File "/home/sshuser/.local/lib/python2.7/site-packages/airflow/utils/db.py", line 74, in wrapper
return func(*args, **kwargs)
File "/home/sshuser/.local/lib/python2.7/site-packages/airflow/jobs.py", line 1816, in process_file
dag.sync_to_db()
File "/home/sshuser/.local/lib/python2.7/site-packages/airflow/utils/db.py", line 74, in wrapper
return func(*args, **kwargs)
File "/home/sshuser/.local/lib/python2.7/site-packages/airflow/models.py", line 4296, in sync_to_db
DagModel).filter(DagModel.dag_id == self.dag_id).first()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2755, in first
ret = list(self[0:1])
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2547, in __getitem__
return list(res)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2855, in __iter__
return self._execute_and_instances(context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2876, in _execute_and_instances
close_with_result=True)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2885, in _get_bind_args
**kw
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2867, in _connection_from_session
conn = self.session.connection(**kw)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 1019, in connection
execution_options=execution_options)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 1024, in _connection_for_bind
engine, execution_options)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 409, in _connection_for_bind
conn = bind.contextual_connect()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 2112, in contextual_connect
self._wrap_pool_connect(self.pool.connect, None),
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 2151, in _wrap_pool_connect
e, dialect, self)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1465, in _handle_dbapi_exception_noconnection
exc_info
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 2147, in _wrap_pool_connect
return fn()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 387, in connect
return _ConnectionFairy._checkout(self)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 768, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 516, in checkout
rec = pool._do_get()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 1140, in _do_get
self._dec_overflow()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 1137, in _do_get
return self._create_connection()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 333, in _create_connection
return _ConnectionRecord(self)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 461, in __init__
self.__connect(first_connect_check=True)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 651, in __connect
connection = pool._invoke_creator(self)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/strategies.py", line 105, in connect
return dialect.connect(*cargs, **cparams)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 393, in connect
return self.dbapi.connect(*cargs, **cparams)
InterfaceError: (pyodbc.InterfaceError) ('28000', u"[28000] [unixODBC][Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'airflowuser'. (18456) (SQLDriverConnect)")
Airflow is configured to use LocalExecutor & pyodbc to connect to SQL Azure
# The executor class that airflow should use. Choices include
# SequentialExecutor, LocalExecutor, CeleryExecutor, DaskExecutor
#executor = SequentialExecutor
executor = LocalExecutor
# The SqlAlchemy connection string to the metadata database.
# SqlAlchemy supports many different database engine, more information
# their website
#sql_alchemy_conn = sqlite:////home/sshuser/airflow/airflow.db
#connection string to MS SQL Serv er
sql_alchemy_conn = mssql+pyodbc://airflowuser#afdsqlserver76:<password>#afdsqlserver76.database.windows.net:1433/airflowdb?driver=ODBC+Driver+17+for+SQL+Server
# The encoding for the databases
sql_engine_encoding = utf-8
# If SqlAlchemy should pool database connections.
sql_alchemy_pool_enabled = True
# The SqlAlchemy pool size is the maximum number of database connections
# in the pool. 0 indicates no limit.
sql_alchemy_pool_size = 10
# The SqlAlchemy pool recycle is the number of seconds a connection
# can be idle in the pool before it is invalidated. This config does
# not apply to sqlite. If the number of DB connections is ever exceeded,
# a lower config value will allow the system to recover faster.
sql_alchemy_pool_recycle = 180
# How many seconds to retry re-establishing a DB connection after
# disconnects. Setting this to 0 disables retries.
sql_alchemy_reconnect_timeout = 300
Dag is as follows
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2019, 1, 4),
'email': ['airflow#example.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(minutes=1),
# 'queue': 'bash_queue',
# 'pool': 'backfill',
# 'priority_weight': 10,
# 'end_date': datetime(2016, 1, 1),
}
dag = DAG('tutorial', default_args=default_args, schedule_interval='*/2 * * * *', max_active_runs=1, catchup=False)
# t1, t2 and t3 are examples of tasks created by instantiating operators
t1 = BashOperator(
task_id='print_date',
bash_command='date',
dag=dag)
t2 = BashOperator(
task_id='sleep',
bash_command='sleep 5',
retries=3,
dag=dag)
t2.set_upstream(t1)
I am a bit lost on why scheduler would not be able to connect to DB after it has run the first task successfully.
Any pointers to resolve this is much appreciated.
I have a sample program that uses sqlalchemy to connect to SQL Azure using the same credentials & this works.
import sqlalchemy
from sqlalchemy import create_engine
engine = create_engine("mssql+pyodbc://afdadmin#afdsqlserver76:<password>#afdsqlserver76.database.windows.net:1433/airflowdb?driver=ODBC+Driver+17+for+SQL+Server")
connection = engine.connect()
result = connection.execute("select version_num from alembic_version")
for row in result:
print("Version:", row['version_num'])
connection.close()

The issue was resolved after Pooling = True was set in odbcinst.ini
[ODBC]
Pooling = Yes

Related

odoo 14 connection to database failed

I do a clean Odoo 14 install and postgreSQL for a new Job, and I had this problem:
This is the odoo log file:
2022-09-26 22:08:19,881 4564 INFO ? odoo.sql_db: Connection to the database failed
2022-09-26 22:08:19,883 4564 INFO ? werkzeug: 127.0.0.1 - - [26/Sep/2022 22:08:19] "GET /favicon.ico HTTP/1.1" 500 - 0 0.000 0.019
2022-09-26 22:08:19,885 4564 ERROR ? werkzeug: Error on request:
Traceback (most recent call last):
File "D:\odoo\python\lib\site-packages\werkzeug\serving.py", line 306, in run_wsgi
execute(self.server.app)
File "D:\odoo\python\lib\site-packages\werkzeug\serving.py", line 294, in execute
application_iter = app(environ, start_response)
File "D:\odoo\server\odoo\service\server.py", line 441, in app
return self.app(e, s)
File "D:\odoo\server\odoo\service\wsgi_server.py", line 113, in application
return application_unproxied(environ, start_response)
File "D:\odoo\server\odoo\service\wsgi_server.py", line 88, in application_unproxied
result = odoo.http.root(environ, start_response)
File "D:\odoo\server\odoo\http.py", line 1328, in __call__
return self.dispatch(environ, start_response)
File "D:\odoo\server\odoo\http.py", line 1294, in __call__
return self.app(environ, start_wrapped)
File "D:\odoo\python\lib\site-packages\werkzeug\middleware\shared_data.py", line 220, in __call__
return self.app(environ, start_response)
File "D:\odoo\server\odoo\http.py", line 1479, in dispatch
self.setup_db(httprequest)
File "D:\odoo\server\odoo\http.py", line 1385, in setup_db
httprequest.session.db = db_monodb(httprequest)
File "D:\odoo\server\odoo\http.py", line 1567, in db_monodb
dbs = db_list(True, httprequest)
File "D:\odoo\server\odoo\http.py", line 1534, in db_list
dbs = odoo.service.db.list_dbs(force)
File "D:\odoo\server\odoo\service\db.py", line 384, in list_dbs
with closing(db.cursor()) as cr:
File "D:\odoo\server\odoo\sql_db.py", line 678, in cursor
return Cursor(self.__pool, self.dbname, self.dsn, serialized=serialized)
File "D:\odoo\server\odoo\sql_db.py", line 250, in __init__
self._cnx = pool.borrow(dsn)
File "D:\odoo\server\odoo\sql_db.py", line 561, in _locked
return fun(self, *args, **kwargs)
File "D:\odoo\server\odoo\sql_db.py", line 629, in borrow
**connection_info)
File "D:\odoo\python\lib\site-packages\psycopg2\__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError - - -
I'm new in the world of database and coding... It seems a little problem but I do know how to resolve it. thanks for reading
Check the status of the postgresql service. It seems it has not started.
Check status:
sudo service postgresql status
Restart:
sudo service postgresql restart

I cann't creat new table in sqlite3 from django

When I added new string in models.py his tables did't create in sqlite3. What I do wrong, again :)
python manage.py makemigrations
python manage.py migrate - I did!
It's happend, when I don't input templates information after messege:
Please enter the default value now as valid Python.
The datetime and django.utils.timezone module are available so you can do e.g. timezone.now.
I imputed just 1 and enter. After thet it broke.
If you need different information give me know, please.
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/meetups/meetup/add/
Django Version: 3.2.8
Python Version: 3.10.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'meetups']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
The above exception (table meetups_meetup has no column named enormus) was the direct cause of the following exception:
File "C:\install\Projects_1\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\install\Projects_1\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\contrib\admin\options.py", line 616, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\contrib\admin\sites.py", line 232, in inner
return view(request, *args, **kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\contrib\admin\options.py", line 1657, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "C:\install\Projects_1\env\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\contrib\admin\options.py", line 1540, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\install\Projects_1\env\lib\site-packages\django\contrib\admin\options.py", line 1586, in _changeform_view
self.save_model(request, new_object, form, not add)
File "C:\install\Projects_1\env\lib\site-packages\django\contrib\admin\options.py", line 1099, in save_model
obj.save()
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\base.py", line 763, in save_base
updated = self._save_table(
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\base.py", line 868, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\base.py", line 906, in _do_insert
return manager._insert(
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\query.py", line 1270, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\sql\compiler.py", line 1416, in execute_sql
cursor.execute(sql, params)
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\utils.py", line 79, in _execute
with self.db.wrap_database_errors:
File "C:\install\Projects_1\env\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
Exception Type: OperationalError at /admin/meetups/meetup/add/
Exception Value: table meetups_meetup has no column named enormus
Errors, when I input: makemigration and migrate
(env) PS C:\install\Projects_1> python manage.py makemigrations
System check identified some issues:
WARNINGS:
meetups.Meetup.participant: (fields.W340) null has no effect on ManyToManyField.
You are trying to add a non-nullable field 'dates' to meetup without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
>>> '2021-10-10'
You are trying to add a non-nullable field 'organizer_emails' to meetup without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option: 1
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
>>> test#.test.com
Invalid input: invalid syntax (<string>, line 1)
>>> 'test#.test.com'
Migrations for 'meetups':
meetups\migrations\0011_auto_20211026_2116.py
- Remove field enormus from meetup
- Add field dates to meetup
- Add field organizer_emails to meetup
(env) PS C:\install\Projects_1> python manage.py migrate
System check identified some issues:
WARNINGS:
meetups.Meetup.participant: (fields.W340) null has no effect on ManyToManyField.
Operations to perform:
Apply all migrations: admin, auth, contenttypes, meetups, sessions
Running migrations:
Applying meetups.0005_auto_20211026_1234...Traceback (most recent call last):
File "C:\install\Projects_1\manage.py", line 22, in <module>
main()
File "C:\install\Projects_1\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\install\Projects_1\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\install\Projects_1\env\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\install\Projects_1\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\install\Projects_1\env\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\install\Projects_1\env\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle
post_migrate_state = executor.migrate(
File "C:\install\Projects_1\env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "C:\install\Projects_1\env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "C:\install\Projects_1\env\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\install\Projects_1\env\lib\site-packages\django\db\migrations\migration.py", line 126, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\install\Projects_1\env\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards
schema_editor.add_field(
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 330, in add_field
self._remake_table(model, create_field=field)
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 191, in _remake_table
self.effective_default(create_field)
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\base\schema.py", line 324, in effective_default
return field.get_db_prep_save(self._effective_default(field), self.connection)
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\fields\__init__.py", line 842, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\fields\__init__.py", line 1271, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\fields\__init__.py", line 1266, in get_prep_value
return self.to_python(value)
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\fields\__init__.py", line 1228, in to_python
parsed = parse_date(value)
File "C:\install\Projects_1\env\lib\site-packages\django\utils\dateparse.py", line 75, in parse_date
match = date_re.match(value)
TypeError: expected string or bytes-like object

pyflink winerror 2 get_gateway()

Following a script on stackOverflow link as described by the link with the only change of the data in the sense I would like to evaluate the simple usage of pyflink in order to analyze if the installation of it works.You can see below the system and in order to install it I use pip -m install apache-flink into a virtual environment with python3.8.4. In order to install flink itself I used docker and I import the images of pyflink/playgrounds:1.10.0. Below is there the only the part taken from link that I modify
source_ddl = """
CREATE TABLE MyUserTable (
column_a INT,
column_b INT,
) WITH (
'connector' = 'filesystem',
'path' = 'file:///Users//code/examples/input.csv ',
'format' = 'csv'
)"""
#connector for data output/sink
sink_ddl = """
CREATE TABLE results (
score INT)
WITH (
'connector' = 'filesystem',
'path' = 'file:///Users//code/examples/output.csv',
'format' = 'csv'
)"""
#make the table corresponding to the schema mentioned
source_table = table_env.execute_sql(source_ddl)
sink_table = table_env.execute_sql(sink_ddl)
#convert the sql table to table API
table_path = table_env.from_path("MyUserTable")
# execute SELECT statement
table_result2 = table_env.execute_sql("SELECT column_a FROM MyUserTable")
table_result2.print()
The error is the following:
Traceback (most recent call last):
File ".\flink1.py", line 15, in <module>
env_settings = EnvironmentSettings.new_instance().in_batch_mode().use_blink_planner().build()
File "C:\Users\landr\AppData\Local\Programs\Python\Python38\lib\site-packages\pyflink\table\environment_settings.py", line 214, in new_instance
return EnvironmentSettings.Builder()
File "C:\Users\landr\AppData\Local\Programs\Python\Python38\lib\site-packages\pyflink\table\environment_settings.py", line 48, in __init__
gateway = get_gateway()
File "C:\Users\landr\AppData\Local\Programs\Python\Python38\lib\site-packages\pyflink\java_gateway.py", line 62, in get_gateway
_gateway = launch_gateway()
File "C:\Users\landr\AppData\Local\Programs\Python\Python38\lib\site-packages\pyflink\java_gateway.py", line 106, in launch_gateway
p = launch_gateway_server_process(env, args)
File "C:\Users\landr\AppData\Local\Programs\Python\Python38\lib\site-packages\pyflink\pyflink_gateway_server.py", line 221, in launch_gateway_server_process
return Popen(command, stdin=PIPE, preexec_fn=preexec_fn, env=env)
File "C:\Users\landr\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\landr\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 1307, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] Impossibile trovare il file specificato
I encountered this error today. I put a print statement into pyflink_gateway_server.py to show the command being passed. I found that the call was to a version of Java that no longer existed on my computer (I’d upgraded it).
The fix was to ensure that JAVA_HOME pointed to a valid Java installation.

Cant apply flask db migrate when using PyODBC w/ SQL Server. Error: Neither DSN nor SERVER keyword supplied (0). Connecting via pyodbc.connect works

I am trying to use Flask SQLAlchemy to connect to a SQL database hosted on Azure. Everything works when I use pyodbc.connect directly, like so:
import pyodbc
# I got the ODBC connection string directly from Azure's connection strings for the db.
odbc_string = 'Driver={ODBC Driver 17 for SQL Server};Server=tcp:sql-server-for-capstone.database.windows.net,1433;Database=MastersCapstone;Uid={my username};Pwd={my super secure password here};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;'
conn = pyodbc.connect(odbc_string)
# Works!
But when I try to connect using Flask SQLAlchemy, I get:
sqlalchemy.exc.OperationalError: (pyodbc.OperationalError) ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Neither DSN nor SERVER keyword supplied (0) (SQLDriverConnect)')
The config I am using to connect via SQLAlchemy looks like this:
odbc_string = 'Driver={ODBC Driver 17 for SQL Server};Server=tcp:sql-server-for-capstone.database.windows.net,1433;Database=MastersCapstone;Uid={my username};Pwd={my super secure password here};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;'
params = urllib.parse.quote_plus(odbc_string)
sqlalchemy_db_uri = f"mssql+pyodbc:///?odbc_connect={params}"
class Config:
# Database
SQLALCHEMY_DATABASE_URI = sqlalchemy_db_uri
And then I initialize the app like so in the directory's __init__.py file:
from flask import Flask
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from src.python.server.config import Config
db = SQLAlchemy()
migrate = Migrate(compare_type=True)
def create_app():
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
migrate.init_app(app, db)
with app.app_context():
from src.python.server import routes, models
return app
Finally, I get the error when I run the following in the terminal:
flask db migrate
Please note that everything worked fine when I was using a PostgreSQL database. Does anyone have any idea why this might be happening? I'm pretty stuck!
Additional info:
Output from running odbcinst -j in the terminal:
unixODBC 2.3.7
DRIVERS............: /usr/local/etc/odbcinst.ini
SYSTEM DATA SOURCES: /usr/local/etc/odbc.ini
FILE DATA SOURCES..: /usr/local/etc/ODBCDataSources
USER DATA SOURCES..: /Users/jordan/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8
Entire stack trace:
Traceback (most recent call last):
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 2285, in _wrap_pool_connect
return fn()
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/pool/base.py", line 303, in unique_connection
return _ConnectionFairy._checkout(self)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/pool/base.py", line 773, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/pool/base.py", line 492, in checkout
rec = pool._do_get()
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/pool/impl.py", line 238, in _do_get
return self._create_connection()
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/pool/base.py", line 308, in _create_connection
return _ConnectionRecord(self)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/pool/base.py", line 437, in __init__
self.__connect(first_connect_check=True)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/pool/base.py", line 657, in __connect
pool.logger.debug("Error on connect(): %s", e)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/util/langhelpers.py", line 68, in __exit__
compat.raise_(
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
raise exception
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/pool/base.py", line 652, in __connect
connection = pool._invoke_creator(self)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/engine/strategies.py", line 114, in connect
return dialect.connect(*cargs, **cparams)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 490, in connect
return self.dbapi.connect(*cargs, **cparams)
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Neither DSN nor SERVER keyword supplied (0) (SQLDriverConnect)')
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/jordan/Coding/survey-app/venv/bin/flask", line 8, in <module>
sys.exit(main())
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/flask/cli.py", line 967, in main
cli.main(args=sys.argv[1:], prog_name="python -m flask" if as_module else None)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/flask/cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/click/decorators.py", line 21, in new_func
return f(get_current_context(), *args, **kwargs)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/flask/cli.py", line 426, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/flask_migrate/cli.py", line 89, in migrate
_migrate(directory, message, sql, head, splice, branch_label, version_path,
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/flask_migrate/__init__.py", line 96, in wrapped
f(*args, **kwargs)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/flask_migrate/__init__.py", line 210, in migrate
command.revision(config, message, autogenerate=True, sql=sql,
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/alembic/command.py", line 214, in revision
script_directory.run_env()
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/alembic/script/base.py", line 489, in run_env
util.load_python_file(self.dir, "env.py")
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/alembic/util/pyfiles.py", line 98, in load_python_file
module = load_module_py(module_id, path)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/alembic/util/compat.py", line 184, in load_module_py
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "migrations/env.py", line 96, in <module>
run_migrations_online()
File "migrations/env.py", line 81, in run_migrations_online
with connectable.connect() as connection:
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 2218, in connect
return self._connection_cls(self, **kwargs)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 103, in __init__
else engine.raw_connection()
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 2317, in raw_connection
return self._wrap_pool_connect(
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 2288, in _wrap_pool_connect
Connection._handle_dbapi_exception_noconnection(
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1554, in _handle_dbapi_exception_noconnection
util.raise_(
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
raise exception
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 2285, in _wrap_pool_connect
return fn()
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/pool/base.py", line 303, in unique_connection
return _ConnectionFairy._checkout(self)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/pool/base.py", line 773, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/pool/base.py", line 492, in checkout
rec = pool._do_get()
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/pool/impl.py", line 238, in _do_get
return self._create_connection()
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/pool/base.py", line 308, in _create_connection
return _ConnectionRecord(self)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/pool/base.py", line 437, in __init__
self.__connect(first_connect_check=True)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/pool/base.py", line 657, in __connect
pool.logger.debug("Error on connect(): %s", e)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/util/langhelpers.py", line 68, in __exit__
compat.raise_(
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
raise exception
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/pool/base.py", line 652, in __connect
connection = pool._invoke_creator(self)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/engine/strategies.py", line 114, in connect
return dialect.connect(*cargs, **cparams)
File "/Users/jordan/Coding/survey-app/venv/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 490, in connect
return self.dbapi.connect(*cargs, **cparams)
sqlalchemy.exc.OperationalError: (pyodbc.OperationalError) ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Neither DSN nor SERVER keyword supplied (0) (SQLDriverConnect)')
(Background on this error at: http://sqlalche.me/e/e3q8)
I was able to solve this by workaround.
I edited migrations/env.py file:
import os
import urllib
DB_CREDENTIALS = os.environ.get("ENV_DB_CREDENTIALS")
SQLALCHEMY_DATABASE_URI = (
"mssql+pyodbc:///?odbc_connect=%s" % urllib.parse.quote_plus(DB_CREDENTIALS)
)
config.set_main_option(
"sqlalchemy.url",
SQLALCHEMY_DATABASE_URI.replace("%", "%%"),
)
I also read somewhere Trusted_Connection=Yes is issue some reason, not sure why.

mssql + pymssql engine with sqlalchemy doesn't take attributes in the connection string

I am trying to pass the attribute MultiSubnetFailover to the connection string using sqlalchemy engine. While passing parameters to pyodbc is pretty smooth, pymssql refuses to accept any parameters in the connection string.
This fails
attributes = "?driver=ODBC+Driver+17+for+sql+server"
engine = create_engine(
'mssql+pymssql://' +
"username" + ':' +
"password" + '#' +
"127.0.0.1" + "/" +
"databaseName" + attributes)
with the error
Traceback (most recent call last):
File "C:/Users/ChaitanyaB/PycharmProjects/Test/TestUpdate.py", line 35, in <module>
(TblServices.OrganizationId == '72A229D4-186B-4B0E-A98F-7DB5DB3566DB')
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\orm\query.py", line 2423, in all
return list(self)
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\orm\query.py", line 2571, in __iter__
return self._execute_and_instances(context)
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\orm\query.py", line 2584, in _execute_and_instances
close_with_result=True)
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\orm\query.py", line 2575, in _connection_from_session
**kw)
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\orm\session.py", line 893, in connection
execution_options=execution_options)
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\orm\session.py", line 898, in _connection_for_bind
engine, execution_options)
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\orm\session.py", line 334, in _connection_for_bind
conn = bind.contextual_connect()
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\engine\base.py", line 2039, in contextual_connect
self._wrap_pool_connect(self.pool.connect, None),
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\engine\base.py", line 2074, in _wrap_pool_connect
return fn()
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\pool.py", line 376, in connect
return _ConnectionFairy._checkout(self)
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\pool.py", line 713, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\pool.py", line 480, in checkout
rec = pool._do_get()
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\pool.py", line 1060, in _do_get
self._dec_overflow()
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\util\langhelpers.py", line 60, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\pool.py", line 1057, in _do_get
return self._create_connection()
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\pool.py", line 323, in _create_connection
return _ConnectionRecord(self)
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\pool.py", line 449, in __init__
self.connection = self.__connect()
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\pool.py", line 607, in __connect
connection = self.__pool._invoke_creator(self)
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\engine\strategies.py", line 97, in connect
return dialect.connect(*cargs, **cparams)
File "C:\Users\ChaitanyaB\NewVirtualEnvironment\lib\site-packages\sqlalchemy\engine\default.py", line 385, in connect
return self.dbapi.connect(*cargs, **cparams)
File "pymssql.pyx", line 578, in pymssql.connect (pymssql.c:9754)
TypeError: connect() got an unexpected keyword argument 'MultiSubnetFailover'
while it works if I make the attributes = ""
Also, the same connections string with pyodbc works
attributes = "?driver=ODBC+Driver+17+for+sql+server"
engine = create_engine(
'mssql+pyodbc://' +
"username" + ':' +
"password" + '#' +
"127.0.0.1" + "/" +
"databaseName" + attributes)
I am wondering if there is a different way to pass a connection attribute when we are using pymssql. Any help is appreciated.

Resources