I'm trying to setup Postgres as backend database for my Airflow installation.
I followed what the documentation suggests. Particularly, I created a specific user for Airflow in Postgres, a specific new table, and granted all privileges to the user. I executed the commands, similar as suggested:
CREATE DATABASE airflow_db;
CREATE USER airflow_user WITH PASSWORD 'airflow_pass';
GRANT ALL PRIVILEGES ON DATABASE airflow_db TO airflow_user;
Also, I edited the sql_alchemy_conn string in airflow.cfg.
Now, when I run airflow db init, I always get the same error:
DB: postgresql+psycopg2://airflow_user:***#localhost:5434/airflow_db
[2022-11-10 15:19:38,319] {migration.py:204} INFO - Context impl PostgresqlImpl.
[2022-11-10 15:19:38,319] {migration.py:207} INFO - Will assume transactional DDL.
Traceback (most recent call last):
File "/Users/phil/airflowv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1802, in _execute_context
self.dialect.do_execute(
File "/Users/phil/airflowv/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 719, in do_execute
cursor.execute(statement, parameters)
psycopg2.errors.InsufficientPrivilege: permission denied for schema public
LINE 2: CREATE TABLE dag_code (
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/phil/airflowv/bin/airflow", line 8, in <module>
sys.exit(main())
File "/Users/phil/airflowv/lib/python3.10/site-packages/airflow/__main__.py", line 39, in main
args.func(args)
File "/Users/phil/airflowv/lib/python3.10/site-packages/airflow/cli/cli_parser.py", line 52, in command
return func(*args, **kwargs)
File "/Users/phil/airflowv/lib/python3.10/site-packages/airflow/cli/commands/db_command.py", line 37, in initdb
db.initdb()
File "/Users/phil/airflowv/lib/python3.10/site-packages/airflow/utils/session.py", line 75, in wrapper
return func(*args, session=session, **kwargs)
File "/Users/phil/airflowv/lib/python3.10/site-packages/airflow/utils/db.py", line 683, in initdb
_create_db_from_orm(session=session)
File "/Users/phil/airflowv/lib/python3.10/site-packages/airflow/utils/db.py", line 666, in _create_db_from_orm
Base.metadata.create_all(settings.engine)
File "/Users/phil/airflowv/lib/python3.10/site-packages/sqlalchemy/sql/schema.py", line 4785, in create_all
bind._run_ddl_visitor(
File "/Users/phil/airflowv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 3110, in _run_ddl_visitor
conn._run_ddl_visitor(visitorcallable, element, **kwargs)
File "/Users/phil/airflowv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 2113, in _run_ddl_visitor
visitorcallable(self.dialect, self, **kwargs).traverse_single(element)
File "/Users/phil/airflowv/lib/python3.10/site-packages/sqlalchemy/sql/visitors.py", line 524, in traverse_single
return meth(obj, **kw)
File "/Users/phil/airflowv/lib/python3.10/site-packages/sqlalchemy/sql/ddl.py", line 846, in visit_metadata
self.traverse_single(
File "/Users/phil/airflowv/lib/python3.10/site-packages/sqlalchemy/sql/visitors.py", line 524, in traverse_single
return meth(obj, **kw)
File "/Users/phil/airflowv/lib/python3.10/site-packages/sqlalchemy/sql/ddl.py", line 890, in visit_table
self.connection.execute(
File "/Users/phil/airflowv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1289, in execute
return meth(self, multiparams, params, _EMPTY_EXECUTION_OPTS)
File "/Users/phil/airflowv/lib/python3.10/site-packages/sqlalchemy/sql/ddl.py", line 77, in _execute_on_connection
return connection._execute_ddl(
File "/Users/phil/airflowv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1381, in _execute_ddl
ret = self._execute_context(
File "/Users/phil/airflowv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1845, in _execute_context
self._handle_dbapi_exception(
File "/Users/phil/airflowv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 2026, in _handle_dbapi_exception
util.raise_(
File "/Users/phil/airflowv/lib/python3.10/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
raise exception
File "/Users/phil/airflowv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1802, in _execute_context
self.dialect.do_execute(
File "/Users/phil/airflowv/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 719, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.InsufficientPrivilege) permission denied for schema public
LINE 2: CREATE TABLE dag_code (
^
[SQL:
CREATE TABLE dag_code (
fileloc_hash BIGINT NOT NULL,
fileloc VARCHAR(2000) NOT NULL,
last_updated TIMESTAMP WITH TIME ZONE NOT NULL,
source_code TEXT NOT NULL,
CONSTRAINT dag_code_pkey PRIMARY KEY (fileloc_hash)
)
]
(Background on this error at: https://sqlalche.me/e/14/f405)
The SQLAlchemy doc didn't help. I tried to resolve this, but no success. Again, I granted ALL privileges to the airflow user on the new airflow database.
After trying out several different things, I found a simple fix:
ALTER DATABASE airflow_db OWNER TO airflow_user;
sets the owner of the database from the standard/admin user (e.g. postgres) to airflow_user.
Now I run airflow db init again, and the error doesn't come up, instead I get Initialization done.
Related
After successfully adding a pot file to my new i18n folder in my local machine, as well as setting "translate=True" in a couple of fields in my carddecks module, and verifying that in localhost I could acess my model data, I decided to update my server.
But when I try to access my model data I get the following error:
LINE 1: ..."write_date", COALESCE("carddecks_card"."cardText"->>'pt_PT'...
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
Anyone might know what may be causing this?
source code for the module can be found at https://github.com/diogocsc/carddecks
Full error:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/odoo/http.py", line 1579, in _serve_db
return service_model.retrying(self._serve_ir_http, self.env)
File "/usr/lib/python3/dist-packages/odoo/service/model.py", line 134, in retrying
result = func()
File "/usr/lib/python3/dist-packages/odoo/http.py", line 1608, in _serve_ir_http
response = self.dispatcher.dispatch(rule.endpoint, args)
File "/usr/lib/python3/dist-packages/odoo/http.py", line 1805, in dispatch
result = self.request.registry['ir.http']._dispatch(endpoint)
File "/usr/lib/python3/dist-packages/odoo/addons/website/models/ir_http.py", line 235, in _dispatch
response = super()._dispatch(endpoint)
File "/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_http.py", line 144, in _dispatch
result = endpoint(**request.params)
File "/usr/lib/python3/dist-packages/odoo/http.py", line 698, in route_wrapper
result = endpoint(self, *args, **params_ok)
File "/usr/lib/python3/dist-packages/odoo/addons/web/controllers/dataset.py", line 42, in call_kw
return self._call_kw(model, method, args, kwargs)
File "/usr/lib/python3/dist-packages/odoo/addons/web/controllers/dataset.py", line 33, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/usr/lib/python3/dist-packages/odoo/api.py", line 457, in call_kw
result = _call_kw_model(method, model, args, kwargs)
File "/usr/lib/python3/dist-packages/odoo/api.py", line 430, in _call_kw_model
result = method(recs, *args, **kwargs)
File "/usr/lib/python3/dist-packages/odoo/addons/web/models/models.py", line 62, in web_search_read
records = self.search_read(domain, fields, offset=offset, limit=limit, order=order)
File "/usr/lib/python3/dist-packages/odoo/models.py", line 4968, in search_read
result = records.read(fields, **read_kwargs)
File "/usr/lib/python3/dist-packages/odoo/models.py", line 2992, in read
self._read(stored_fields)
File "/usr/lib/python3/dist-packages/odoo/models.py", line 3235, in _read
cr.execute(query_str, params + [sub_ids])
File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 315, in execute
res = self._obj.execute(query, params)
psycopg2.errors.UndefinedFunction: operator does not exist: character varying ->> unknown
LINE 1: ..."write_date", COALESCE("carddecks_card"."cardText"->>'pt_PT'...
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
The above server error caused the following client error:
OwlError: The following error occurred in onWillStart: "Odoo Server Error"
at wrapError (https://www.relationalgames.com/web/assets/504-41b52e3/web.assets_common.min.js:1445:77)
at onWillStart (https://www.relationalgames.com/web/assets/504-41b52e3/web.assets_common.min.js:1451:117)
at useModel (https://www.relationalgames.com/web/assets/505-11285c6/web.assets_backend.min.js:4709:1)
at ListController.setup (https://www.relationalgames.com/web/assets/505-11285c6/web.assets_backend.min.js:4430:645)
at new ComponentNode (https://www.relationalgames.com/web/assets/504-41b52e3/web.assets_common.min.js:1407:136)
at https://www.relationalgames.com/web/assets/504-41b52e3/web.assets_common.min.js:1929:6
at View.slot1 (eval at compile (https://www.relationalgames.com/web/assets/504-41b52e3/web.assets_common.min.js:1892:370), <anonymous>:15:36)
at callSlot (https://www.relationalgames.com/web/assets/504-41b52e3/web.assets_common.min.js:1508:25)
at WithSearch.template (eval at compile (https://www.relationalgames.com/web/assets/504-41b52e3/web.assets_common.min.js:1892:370), <anonymous>:8:12)
at Fiber._render (https://www.relationalgames.com/web/assets/504-41b52e3/web.assets_common.min.js:1336:96)
Caused by: RPC_ERROR: Odoo Server Error
at makeErrorFromResponse (https://www.relationalgames.com/web/assets/505-11285c6/web.assets_backend.min.js:967:163)
at XMLHttpRequest.<anonymous> (https://www.relationalgames.com/web/assets/505-11285c6/web.assets_backend.min.js:974:13)
Found the answer for this. In my localhost I was updating my module. In my server i was just running docker-compose up. Not updating the module in the db.
The solution was going to settings -> apps search by cardecks and upgrade it.
i am trying to run this simple flask app and I keep getting this error in the terminal when trying to run the flask app
FLASK_APP=app.py flask run
i keep getting this error :
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) fe_sendauth: no password supplied
here is my app:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres#localhost:5432/testdb'
db = SQLAlchemy(app)
class Person(db.Model):
__tablename__ = 'persons'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(), nullable=False)
db.create_all()
#app.route('/')
def index():
return 'Hello World!'
just to clarify i have psycopg2, flask-SQLAlchemy and all dependencies installed AND THERE IS NO PASSWORD FOR USER postgres by default and i haven't changed that and i can log in to database as postgres using psql without password without any problems.
Full error output:
FLASK_APP=app.py flask run
* Serving Flask app "app.py"
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
/usr/lib/python3/dist-packages/flask_sqlalchemy/__init__.py:800: UserWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning.
warnings.warn('SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning.')
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 1122, in _do_get
return self._pool.get(wait, self._timeout)
File "/usr/lib/python3/dist-packages/sqlalchemy/util/queue.py", line 145, in get
raise Empty
sqlalchemy.util.queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 2147, in _wrap_pool_connect
return fn()
File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 387, in connect
return _ConnectionFairy._checkout(self)
File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 766, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 516, in checkout
rec = pool._do_get()
File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 1138, in _do_get
self._dec_overflow()
File "/usr/lib/python3/dist-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/usr/lib/python3/dist-packages/sqlalchemy/util/compat.py", line 187, in reraise
raise value
File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 1135, in _do_get
return self._create_connection()
File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 333, in _create_connection
return _ConnectionRecord(self)
File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 461, in __init__
self.__connect(first_connect_check=True)
File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 651, in __connect
connection = pool._invoke_creator(self)
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/strategies.py", line 105, in connect
return dialect.connect(*cargs, **cparams)
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/default.py", line 393, in connect
return self.dbapi.connect(*cargs, **cparams)
File "/home/aa/.local/lib/python3.6/site-packages/psycopg2/__init__.py", line 126, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: fe_sendauth: no password supplied
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/aa/.local/bin/flask", line 11, in <module>
sys.exit(main())
File "/home/aa/.local/lib/python3.6/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 "/home/aa/.local/lib/python3.6/site-packages/flask/cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "/home/aa/.local/lib/python3.6/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/home/aa/.local/lib/python3.6/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/aa/.local/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/aa/.local/lib/python3.6/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/home/aa/.local/lib/python3.6/site-packages/click/decorators.py", line 73, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "/home/aa/.local/lib/python3.6/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/home/aa/.local/lib/python3.6/site-packages/flask/cli.py", line 848, in run_command
app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
File "/home/aa/.local/lib/python3.6/site-packages/flask/cli.py", line 305, in __init__
self._load_unlocked()
File "/home/aa/.local/lib/python3.6/site-packages/flask/cli.py", line 330, in _load_unlocked
self._app = rv = self.loader()
File "/home/aa/.local/lib/python3.6/site-packages/flask/cli.py", line 388, in load_app
app = locate_app(self, import_name, name)
File "/home/aa/.local/lib/python3.6/site-packages/flask/cli.py", line 240, in locate_app
__import__(module_name)
File "/home/aa/Desktop/Udacity - FullStackND 2020/FullStackND2020/Practice Projects/flask hello world app/app.py", line 18, in <module>
db.create_all()
File "/usr/lib/python3/dist-packages/flask_sqlalchemy/__init__.py", line 972, in create_all
self._execute_for_all_tables(app, bind, 'create_all')
File "/usr/lib/python3/dist-packages/flask_sqlalchemy/__init__.py", line 964, in _execute_for_all_tables
op(bind=self.get_engine(app, bind), **extra)
File "/usr/lib/python3/dist-packages/sqlalchemy/sql/schema.py", line 3934, in create_all
tables=tables)
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1928, in _run_visitor
with self._optional_conn_ctx_manager(connection) as conn:
File "/usr/lib/python3.6/contextlib.py", line 81, in __enter__
return next(self.gen)
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1921, in _optional_conn_ctx_manager
with self.contextual_connect() as conn:
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 2112, in contextual_connect
self._wrap_pool_connect(self.pool.connect, None),
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 2151, in _wrap_pool_connect
e, dialect, self)
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1465, in _handle_dbapi_exception_noconnection
exc_info
File "/usr/lib/python3/dist-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/usr/lib/python3/dist-packages/sqlalchemy/util/compat.py", line 186, in reraise
raise value.with_traceback(tb)
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 2147, in _wrap_pool_connect
return fn()
File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 387, in connect
return _ConnectionFairy._checkout(self)
File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 766, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 516, in checkout
rec = pool._do_get()
File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 1138, in _do_get
self._dec_overflow()
File "/usr/lib/python3/dist-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/usr/lib/python3/dist-packages/sqlalchemy/util/compat.py", line 187, in reraise
raise value
File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 1135, in _do_get
return self._create_connection()
File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 333, in _create_connection
return _ConnectionRecord(self)
File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 461, in __init__
self.__connect(first_connect_check=True)
File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 651, in __connect
connection = pool._invoke_creator(self)
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/strategies.py", line 105, in connect
return dialect.connect(*cargs, **cparams)
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/default.py", line 393, in connect
return self.dbapi.connect(*cargs, **cparams)
File "/home/aa/.local/lib/python3.6/site-packages/psycopg2/__init__.py", line 126, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) fe_sendauth: no password supplied
Other than just setting a password, you can log in without a password by:
Enable trust authentication, eg echo "local all all trust" | sudo tee -a /etc/postgresql/10/main/pg_hba.conf
Create a role with login access with the same username as your local username, eg if whoami returns myname, then sudo -u postgres psql -c "CREATE ROLE myname WITH LOGIN"
Use sqlalchemy's postgresql unix domain connection instead of tcp (ref), eg "postgres+psycopg2://myname#/mydb"
Note that this requires installing pip3 install psycopg2-binary
so apparently you need a password to connect to database from SQLAlchemy, I was able to work around this by simply creating a password or adding new user with password.
let me know if there is a different work around/solution
I'm getting the following error when trying to run an async transcription request on a .flac file hosted on google cloud.
$ python3 transcribe_async.py gs://[file].flac
Traceback (most recent call last):
File "[]/anaconda3/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 54, in error_remapped_callable
return callable_(*args, **kwargs)
File "[]/anaconda3/lib/python3.6/site-packages/grpc/_channel.py", line 514, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "[]/anaconda3/lib/python3.6/site-packages/grpc/_channel.py", line 448, in _end_unary_response_blocking
raise _Rendezvous(state, None, None, deadline)
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with:
status = StatusCode.PERMISSION_DENIED
details = "The caller does not have permission"
debug_error_string = "{"created":"#1533912393.258761000","description":"Error received from peer","file":"src/core/lib/surface/call.cc","file_line":1095,"grpc_message":"The caller does not have permission","grpc_status":7}"
>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "transcribe_async.py", line 105, in <module>
transcribe_gcs(args.path)
File "transcribe_async.py", line 83, in transcribe_gcs
operation = client.long_running_recognize(config, audio)
File "[]/anaconda3/lib/python3.6/site-packages/google/cloud/speech_v1/gapic/speech_client.py", line 284, in long_running_recognize
request, retry=retry, timeout=timeout, metadata=metadata)
File "[]/anaconda3/lib/python3.6/site-packages/google/api_core/gapic_v1/method.py", line 139, in __call__
return wrapped_func(*args, **kwargs)
File "[]/anaconda3/lib/python3.6/site-packages/google/api_core/retry.py", line 260, in retry_wrapped_func
on_error=on_error,
File "[]/anaconda3/lib/python3.6/site-packages/google/api_core/retry.py", line 177, in retry_target
return target()
File "[]/anaconda3/lib/python3.6/site-packages/google/api_core/timeout.py", line 206, in func_with_timeout
return func(*args, **kwargs)
File "[]/anaconda3/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 56, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
google.api_core.exceptions.PermissionDenied: 403 The caller does not have permission
I've added an export statement to my .zshrc file that points to the service account json, I've added myself, the service account email and the project owner and editor as owners of the cloud bucket through the browser, and I ran gcloud auth activate-service-account --key-file="[].json", but nothing helps. What have I forgotten? Any help much appreciated.
You need to make your file publicly readable. Once you set the permissions to allUsers, you will be able to use your file in your request.
Background
We're using Flask to develop a fairly simple application to "scratch an itch" we realized we had while working on a previous project. Session management is handled through the Flask-Login extension, coupled with the Github-Flask extension which we use for user authentication. The app uses Flask-SQLAlchemy and Psycopg2 (2.6.3) to connect to a PostgreSQL 9.1 database where user data is stored.
Issue
When the app is run locally (or deployed to a remote server) for testing we're seeing a strange condition during the first login attempt. The first time I log in I successfully get through the Github authentication sets, but immediately see this error.
DataError: (DataError) invalid input syntax for integer: "None"
LINE 3: WHERE "user".id = 'None'
^
'SELECT "user".id AS user_id, "user".date_created AS user_date_created,
"user".date_modified AS user_date_modified, "user".nickname AS user_nickname,
"user".email AS user_email, "user".about_me AS user_about_me,
"user".github_access_token AS user_github_access_token, "user".github_id AS
user_github_id \nFROM "user" \nWHERE "user".id = %(param_1)s' {'param_1': u'None'}
I can close the browser tab and then revisit the application URL and see the same message. However, if I close the browser window, completely clear my browser's cache, and then attempt to log back in, it works as expected and I'm able to use the application. From that point on I can log out, switch browsers, clear browser cache again, etc., and there don't appear to be any problems -- it's only that first login until browser cache is cleared that this happens.
My testing shows that this happens on any user and two different users can be in two different states at the same time (one has cleared cache and now isn't having problems, the other who hasn't taken those steps is still stuck in the error state.
Originally we used a local SQLite database instead of Postgres. The issue does not exist there. It only has occurred since the switch to Postgres.
I'm at a loss for what steps I can take to remedy this situation. So far the questions I know to ask haven't been able to lead to the right answers when I search online.
For reference, I'll include the full stack trace as well.
Full Stack Trace
Traceback (most recent call last):
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/flask_debugtoolbar/__init__.py", line 124, in dispatch_request
return view_func(**req.view_args)
File "/Users/dev/PRODUCT/app/modules/mod_profile/controllers.py", line 26, in profile
title='PRODUCT')
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/flask/templating.py", line 126, in render_template
ctx.app.update_template_context(context)
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/flask/app.py", line 716, in update_template_context
context.update(func())
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/flask_login.py", line 825, in _user_context_processor
return dict(current_user=_get_user())
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/flask_login.py", line 794, in _get_user
current_app.login_manager._load_user()
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/flask_login.py", line 363, in _load_user
return self.reload_user()
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/flask_login.py", line 325, in reload_user
user = self.user_callback(user_id)
File "/Users/dev/PRODUCT/app/modules/mod_auth/controllers.py", line 31, in load_user
return User.query.get(id)
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 840, in get
return loading.load_on_ident(self, key)
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/sqlalchemy/orm/loading.py", line 231, in load_on_ident
return q.one()
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2395, in one
ret = list(self)
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2438, in __iter__
return self._execute_and_instances(context)
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2453, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 729, in execute
return meth(self, multiparams, params)
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 322, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 826, in _execute_clauseelement
compiled_sql, distilled_params
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 958, in _execute_context
context)
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1159, in _handle_dbapi_exception
exc_info
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 199, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb)
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 951, in _execute_context
context)
File "/Users/dev/PRODUCT/venv/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 436, in do_execute
cursor.execute(statement, parameters)
DataError: (DataError) invalid input syntax for integer: "None"
LINE 3: WHERE "user".id = 'None'
^
'SELECT "user".id AS user_id, "user".date_created AS user_date_created, "user".date_modified AS user_date_modified, "user".nickname AS user_nickname, "user".email AS user_email, "user".about_me AS user_about_me, "user".github_access_token AS user_github_access_token, "user".github_id AS user_github_id \nFROM "user" \nWHERE "user".id = %(param_1)s' {'param_1': u'None'}
Resolved!
This was a race condition. During the login process our application redirects an authenticated user to their profile page. This was getting triggered correctly, but for new users it was getting called before the user was actually committed to the database.
Visually it happened at the same time, so you could confirm that the callback was supplied with the "right" information, but it wasn't until I deconstructed and then reconstructed the login steps that I realized that it was hitting the route just before the record was actually committed to the database. Since the function that added the record wasn't interrupted by the redirect it did what it was supposed to do, but just a hair late.
Perhaps someone else will find this extract of my code helpful when troubleshooting a similar issue:
## from mod_auth/controllers.py
#mod_auth.before_app_request
def before_request():
g.user = current_user
#mod_auth.route('/login', methods=['GET'])
def login():
if g.user.is_authenticated():
redirect(url_for('mod_home.index'))
return github.authorize()
#login_manager.user_loader
def load_user(id):
return User.query.get(id)
#github.access_token_getter
def token_getter():
user = g.user
if user is not None:
return user.github_access_token
#mod_auth.route('/github')
#github.authorized_handler
def authorized(oauth_token):
next_url = request.args.get('next') or url_for('mod_home.index')
if oauth_token is None:
flash("Authorization failed.")
return redirect(next_url)
user = User.query.filter_by(github_access_token=oauth_token).first()
if user is None:
user = User(github_access_token=oauth_token)
db.session.add(user)
db.session.commit() ## <-- adding a commit here fixed the issue
user.github_access_token = oauth_token
login_user(user)
## login_user called, but because the oauth_token exist and had been
## added to the session, the user was flagged as "is_authenticated"
## and the redirect was triggered
ghinfo = github.get('user')
if 'login' in ghinfo:
user.nickname = ghinfo['login'].lower()
else:
user.nickname = 'nameless'
db.session.commit() ## this was the only commit, originally
return redirect(url_for('mod_profile.profile', username=user.nickname))
I'm facing following exception when celery is trying to cleanup back-end.
Most probably, this is happening due to MySQL disconnect issue and can be solved by using pool_recycle parameter and retrying the task later. But this is out of my hand - I guess celery needs to provide support for this?
Now my question is, what is backend cleanup task and how such a failed task may affect our system?
Log:
[2014-04-08 04:00:00,017: INFO/Beat] Scheduler: Sending due task celery.backend_cleanup (celery.backend_cleanup)
[2014-04-08 04:00:00,020: INFO/MainProcess] Received task: celery.backend_cleanup[b70acd50-e72d-43b1-a702-0bfa8e7e83a6] expires:[2014-04-08 16:00:00.018317+01:00]
[2014-04-08 04:00:00,036: ERROR/MainProcess] Task celery.backend_cleanup[b70acd50-e72d-43b1-a702-0bfa8e7e83a6] raised unexpected: OperationalError('(OperationalError) MySQL Connection not available.',)
Traceback (most recent call last):
File "/webapps/phoenix/lib/python3.3/site-packages/celery/app/trace.py", line 238, in trace_task
R = retval = fun(*args, **kwargs)
File "/webapps/phoenix/lib/python3.3/site-packages/celery/app/trace.py", line 416, in __protected_call__
return self.run(*args, **kwargs)
File "/webapps/phoenix/lib/python3.3/site-packages/celery/app/builtins.py", line 56, in backend_cleanup
app.backend.cleanup()
File "/webapps/phoenix/lib/python3.3/site-packages/celery/backends/database/__init__.py", line 180, in cleanup
Task.date_done < (now - expires)).delete()
File "/webapps/phoenix/lib/python3.3/site-packages/sqlalchemy/orm/query.py", line 2626, in delete
delete_op.exec_()
File "/webapps/phoenix/lib/python3.3/site-packages/sqlalchemy/orm/persistence.py", line 866, in exec_
self._do_exec()
File "/webapps/phoenix/lib/python3.3/site-packages/sqlalchemy/orm/persistence.py", line 991, in _do_exec
params=self.query._params)
File "/webapps/phoenix/lib/python3.3/site-packages/sqlalchemy/orm/session.py", line 978, in execute
clause, params or {})
File "/webapps/phoenix/lib/python3.3/site-packages/sqlalchemy/engine/base.py", line 664, in execute
return meth(self, multiparams, params)
File "/webapps/phoenix/lib/python3.3/site-packages/sqlalchemy/sql/elements.py", line 282, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/webapps/phoenix/lib/python3.3/site-packages/sqlalchemy/engine/base.py", line 761, in _execute_clauseelement
compiled_sql, distilled_params
File "/webapps/phoenix/lib/python3.3/site-packages/sqlalchemy/engine/base.py", line 828, in _execute_context
None, None)
File "/webapps/phoenix/lib/python3.3/site-packages/sqlalchemy/engine/base.py", line 1023, in _handle_dbapi_exception
exc_info
File "/webapps/phoenix/lib/python3.3/site-packages/sqlalchemy/util/compat.py", line 174, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=exc_value)
File "/webapps/phoenix/lib/python3.3/site-packages/sqlalchemy/util/compat.py", line 167, in reraise
raise value.with_traceback(tb)
File "/webapps/phoenix/lib/python3.3/site-packages/sqlalchemy/engine/base.py", line 824, in _execute_context
context = constructor(dialect, self, conn, *args)
File "/webapps/phoenix/lib/python3.3/site-packages/sqlalchemy/engine/default.py", line 507, in _init_compiled
self.cursor = self.create_cursor()
File "/webapps/phoenix/lib/python3.3/site-packages/sqlalchemy/engine/default.py", line 671, in create_cursor
return self._dbapi_connection.cursor()
File "/webapps/phoenix/lib/python3.3/site-packages/sqlalchemy/pool.py", line 548, in cursor
return self.connection.cursor(*args, **kwargs)
File "/webapps/phoenix/lib/python3.3/site-packages/mysql/connector/connection.py", line 1231, in cursor
raise errors.OperationalError("MySQL Connection not available.")
sqlalchemy.exc.OperationalError: (OperationalError) MySQL Connection not available. 'DELETE FROM celery_taskmeta WHERE celery_taskmeta.date_done < %(date_done_1)s' [{}]
PS I've checked this SO question but seems like it's due to a different exception: Celery log shows cleanup failed
The closest Celery has to retrying is short lived sessions.
The task is cleaning out un-read task results. If it's failing, you may see those results start to build up, but should be OK otherwise.
You're right that there's very little documentation about it!