Django MySQL server has gone away - mysql

I have a django site the was using sqlite for the backend, recently we upgraded to MySQL and now are receiving intermittent errors:
'MySQL server has gone away'
After starting the site it loads fine, clicking around to change pages will result in the error usually after viewing 1 to 6 pages. The page it occurs on appears to be irrelevant, the same page may load fine the first time but throw the error the 2nd time.
Here's my environment:
Nginx running on host machine as reverse proxy
Docker container running Nginx inside, Django 1.8, uwsgi, and Python 3.4.
Django is using the mysqlclient db driver.
Google Cloud MySQL, 2nd generation
I've tried using a local MySQL server rather than the Google Cloud MySQL, it didn't make a difference. I also tried using the MySQL Connector/Python DB driver instead of mysqlclient. It produced a different (but similar) error message and traceback.
If I go back to SQLite, it works fine. Running under the django development server rather than nginx also works fine.
I've seen posts for this error stating that the django CONN_MAX_AGE should be less than the MySQL wait_timeout, but I'm using the default CONN_MAX_AGE setting of 0. According to the django docs, setting this to 0 (default) causes django to create a new database connection for each request. A value greater than 0 will define how long the connection remains open so it can be reused by another request. If I set it to a value greater than 0 the error goes away, but I'm concerned that I'm just deferring the error until later after the persistent connection expires. Also the django development web server creates a new connection for each request (similar to CONN_MAX_AGE=0), but I don't get the error using the dev server. Django versions prior to 1.6 did not support persistent connections, so it seems like I should be able to keep the default CONN_MAX_AGE=0 setting.
I had to enable logging for uwsgi, it's error log shows the following:
*** Starting uWSGI 2.0.13.1 (64bit) on [Fri Nov 18 22:15:33 2016] ***
compiled with version: 4.8.4 on 18 May 2016 17:48:05
os: Linux-4.4.0-45-generic #66-Ubuntu SMP Wed Oct 19 14:12:37 UTC 2016
nodename: 083c33814e43
machine: x86_64
clock source: unix
detected number of CPU cores: 8
current working directory: /
detected binary path: /usr/local/bin/uwsgi
!!! no internal routing support, rebuild with pcre support !!!
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
chdir() to /srv/ftc
your memory page size is 4096 bytes
detected max file descriptor number: 65536
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to UNIX address /srv/ftc/ftc.sock fd 3
Python version: 3.4.3 (default, Oct 14 2015, 20:31:36) [GCC 4.8.4]
Set PythonHome to /srv/env/ftc
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0x22a73d0
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 1476189 bytes (1441 KB) for 10 cores
*** Operational MODE: preforking ***
Loading configuration from /srv/ftc/data/settings_local.py
WSGI app 0 (mountpoint='') ready in 2 seconds on interpreter 0x22a73d0 pid: 9 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 9)
spawned uWSGI worker 1 (pid: 17, cores: 1)
spawned uWSGI worker 2 (pid: 18, cores: 1)
spawned uWSGI worker 3 (pid: 19, cores: 1)
spawned uWSGI worker 4 (pid: 20, cores: 1)
spawned uWSGI worker 5 (pid: 21, cores: 1)
spawned uWSGI worker 6 (pid: 22, cores: 1)
spawned uWSGI worker 7 (pid: 23, cores: 1)
spawned uWSGI worker 8 (pid: 24, cores: 1)
spawned uWSGI worker 9 (pid: 25, cores: 1)
spawned uWSGI worker 10 (pid: 26, cores: 1)
[pid: 21|app: 0|req: 1/1] 192.168.1.15 () {38 vars in 637 bytes} [Fri Nov 18 17:15:39 2016] GET /faq/ => generated 13018 bytes in 3021 msecs (HTTP/1.1 200) 8 headers in 412 bytes (1 switches on core 0)
[pid: 21|app: 0|req: 2/2] 192.168.1.15 () {40 vars in 707 bytes} [Fri Nov 18 17:16:20 2016] GET /find-local-food/ => generated 20480 bytes in 1510 msecs (HTTP/1.1 200) 7 headers in 290 bytes (2 switches on core 0)
[pid: 21|app: 0|req: 3/3] 192.168.1.15 () {40 vars in 711 bytes} [Fri Nov 18 17:16:23 2016] GET /my-programs/ => generated 9297 bytes in 1454 msecs (HTTP/1.1 200) 7 headers in 290 bytes (2 switches on core 0)
[pid: 21|app: 0|req: 4/4] 192.168.1.15 () {40 vars in 683 bytes} [Fri Nov 18 17:16:26 2016] GET / => generated 13562 bytes in 3037 msecs (HTTP/1.1 200) 8 headers in 412 bytes (2 switches on core 0)
[pid: 21|app: 0|req: 5/5] 192.168.1.15 () {40 vars in 683 bytes} [Fri Nov 18 17:16:30 2016] GET /about/ => generated 10064 bytes in 1586 msecs (HTTP/1.1 200) 7 headers in 290 bytes (2 switches on core 0)
[pid: 21|app: 0|req: 6/6] 192.168.1.15 () {40 vars in 685 bytes} [Fri Nov 18 17:16:33 2016] GET /faq/ => generated 13018 bytes in 1145 msecs (HTTP/1.1 200) 8 headers in 412 bytes (2 switches on core 0)
[pid: 21|app: 0|req: 7/7] 192.168.1.15 () {40 vars in 691 bytes} [Fri Nov 18 17:16:35 2016] GET /contact/ => generated 8734 bytes in 1352 msecs (HTTP/1.1 200) 7 headers in 290 bytes (2 switches on core 0)
[pid: 21|app: 0|req: 8/8] 192.168.1.15 () {40 vars in 711 bytes} [Fri Nov 18 17:16:38 2016] GET /find-local-food/ => generated 20480 bytes in 1484 msecs (HTTP/1.1 200) 7 headers in 290 bytes (2 switches on core 0)
[pid: 21|app: 0|req: 9/9] 192.168.1.15 () {40 vars in 699 bytes} [Fri Nov 18 17:16:41 2016] GET /about/ => generated 10064 bytes in 1723 msecs (HTTP/1.1 200) 7 headers in 290 bytes (2 switches on core 0)
Traceback (most recent call last):
File "/srv/env/ftc/lib/python3.4/site-packages/django/core/urlresolvers.py", line 393, in urlconf_module
return self._urlconf_module
AttributeError: 'RegexURLResolver' object has no attribute '_urlconf_module'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/srv/env/ftc/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/srv/env/ftc/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 124, in execute
return self.cursor.execute(query, args)
File "/srv/env/ftc/lib/python3.4/site-packages/MySQLdb/cursors.py", line 250, in execute
self.errorhandler(self, exc, value)
File "/srv/env/ftc/lib/python3.4/site-packages/MySQLdb/connections.py", line 42, in defaulterrorhandler
raise errorvalue
File "/srv/env/ftc/lib/python3.4/site-packages/MySQLdb/cursors.py", line 247, in execute
res = self._query(query)
File "/srv/env/ftc/lib/python3.4/site-packages/MySQLdb/cursors.py", line 411, in _query
rowcount = self._do_query(q)
File "/srv/env/ftc/lib/python3.4/site-packages/MySQLdb/cursors.py", line 374, in _do_query
db.query(q)
File "/srv/env/ftc/lib/python3.4/site-packages/MySQLdb/connections.py", line 270, in query
_mysql.connection.query(self, query)
_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away')
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/srv/env/ftc/lib/python3.4/site-packages/django/core/handlers/wsgi.py", line 170, in __call__
self.load_middleware()
File "/srv/env/ftc/lib/python3.4/site-packages/django/core/handlers/base.py", line 52, in load_middleware
mw_instance = mw_class()
File "/srv/env/ftc/lib/python3.4/site-packages/django/middleware/locale.py", line 24, in __init__
for url_pattern in get_resolver(None).url_patterns:
File "/srv/env/ftc/lib/python3.4/site-packages/django/core/urlresolvers.py", line 401, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/srv/env/ftc/lib/python3.4/site-packages/django/core/urlresolvers.py", line 395, in urlconf_module
self._urlconf_module = import_module(self.urlconf_name)
File "/srv/env/ftc/lib/python3.4/importlib/__init__.py", line 109, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
File "<frozen importlib._bootstrap>", line 1129, in _exec
File "<frozen importlib._bootstrap>", line 1471, in exec_module
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "./ftc/urls.py", line 23, in <module>
url(r'^', include('areas.public.urls')),
File "/srv/env/ftc/lib/python3.4/site-packages/django/conf/urls/__init__.py", line 33, in include
urlconf_module = import_module(urlconf_module)
File "/srv/env/ftc/lib/python3.4/importlib/__init__.py", line 109, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
File "<frozen importlib._bootstrap>", line 1129, in _exec
File "<frozen importlib._bootstrap>", line 1471, in exec_module
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "./areas/public/urls.py", line 36, in <module>
url(r'^paypal/', include('areas.public.paypal.urls')),
File "/srv/env/ftc/lib/python3.4/site-packages/django/conf/urls/__init__.py", line 33, in include
urlconf_module = import_module(urlconf_module)
File "/srv/env/ftc/lib/python3.4/importlib/__init__.py", line 109, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
File "<frozen importlib._bootstrap>", line 1129, in _exec
File "<frozen importlib._bootstrap>", line 1471, in exec_module
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "./areas/public/paypal/urls.py", line 5, in <module>
from . import payment_complete
File "./areas/public/paypal/payment_complete.py", line 9, in <module>
PublicCommon = PublicCommon()
File "./areas/public/common/__init__.py", line 34, in __init__
self.login_page = self.get_cms_page('pu_login')
File "./areas/public/common/__init__.py", line 27, in get_cms_page
return get_object_or_404(Page, reverse_id=reverse_id, publisher_is_draft=False)
File "/srv/env/ftc/lib/python3.4/site-packages/django/shortcuts.py", line 155, in get_object_or_404
return queryset.get(*args, **kwargs)
File "/srv/env/ftc/lib/python3.4/site-packages/django/db/models/query.py", line 328, in get
num = len(clone)
File "/srv/env/ftc/lib/python3.4/site-packages/django/db/models/query.py", line 144, in __len__
self._fetch_all()
File "/srv/env/ftc/lib/python3.4/site-packages/django/db/models/query.py", line 965, in _fetch_all
self._result_cache = list(self.iterator())
File "/srv/env/ftc/lib/python3.4/site-packages/django/db/models/query.py", line 238, in iterator
results = compiler.execute_sql()
File "/srv/env/ftc/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql
cursor.execute(sql, params)
File "/srv/env/ftc/lib/python3.4/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/srv/env/ftc/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/srv/env/ftc/lib/python3.4/site-packages/django/db/utils.py", line 98, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/srv/env/ftc/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/srv/env/ftc/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/srv/env/ftc/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 124, in execute
return self.cursor.execute(query, args)
File "/srv/env/ftc/lib/python3.4/site-packages/MySQLdb/cursors.py", line 250, in execute
self.errorhandler(self, exc, value)
File "/srv/env/ftc/lib/python3.4/site-packages/MySQLdb/connections.py", line 42, in defaulterrorhandler
raise errorvalue
File "/srv/env/ftc/lib/python3.4/site-packages/MySQLdb/cursors.py", line 247, in execute
res = self._query(query)
File "/srv/env/ftc/lib/python3.4/site-packages/MySQLdb/cursors.py", line 411, in _query
rowcount = self._do_query(q)
File "/srv/env/ftc/lib/python3.4/site-packages/MySQLdb/cursors.py", line 374, in _do_query
db.query(q)
File "/srv/env/ftc/lib/python3.4/site-packages/MySQLdb/connections.py", line 270, in query
_mysql.connection.query(self, query)
django.db.utils.OperationalError: (2006, 'MySQL server has gone away')
[pid: 20|app: 0|req: 1/10] 192.168.1.15 () {40 vars in 701 bytes} [Fri Nov 18 17:16:43 2016] GET /my-programs/ => generated 0 bytes in 258 msecs (HTTP/1.1 500) 0 headers in 0 bytes (1 switches on core 0)
...brutally killing workers...
worker 1 buried after 1 seconds
worker 2 buried after 1 seconds
worker 3 buried after 1 seconds
worker 4 buried after 1 seconds
worker 5 buried after 1 seconds
worker 6 buried after 1 seconds
worker 7 buried after 1 seconds
worker 8 buried after 1 seconds
worker 9 buried after 1 seconds
worker 10 buried after 1 seconds
binary reloading uWSGI...
chdir() to /
closing all non-uwsgi socket fds > 2 (max_fd = 65536)...
found fd 3 mapped to socket 0 (/srv/ftc/ftc.sock)
running /usr/local/bin/uwsgi
[uWSGI] getting INI configuration from /srv/ftc/conf/uwsgi.ini
Thanks in advance for any help!

This is usually a mysql configuration problem. The settings in particular that you want to adjust for your website are:
max_allowed_packet: http://dev.mysql.com/doc/refman/5.7/en/packet-too-large.html
wait_timeout: http://dev.mysql.com/doc/refman/5.7/en/gone-away.html
But if you’ll look at your log, the mysql gone away problem is only during the handling of an exception that is being caused somewhere else. I would try and solve this exception first before trying to tackle the mysql issue
Traceback (most recent call last):
File "/srv/env/ftc/lib/python3.4/site-packages/django/core/urlresolvers.py", line 393, in urlconf_module
return self._urlconf_module
AttributeError: 'RegexURLResolver' object has no attribute '_urlconf_module'

I found the solution. I added lazy-apps to uwsgi.ini. See ningx, uwsgi, python permanent mysql error after some time from starting application
I'm not using sql alchemy but this did fix the mysql server has gone away error.

Related

Airflow upon starting - MySQL server has gone away

We added a second airflow database to support our staging airflow instance, and now both staging and production seem to have intermittent connection issues. We recently upgraded to 2.2.4, but looking through past RDS logs, I see aborted connections (Got an error reading communication packets) prior to the upgrade as well (previous version 1.10.11). Both instances have a webserver UI that pull in past DAG runs fine, and the scheduler is running DAGs appropriately and storing dag_run data. When the service is started however, we receive an error "MySQL server has gone away" (see below for stack trace). airflow db check and airflow db shell both return successful connections. Some relevant airflow config values are:
sql_alchemy_pool_enabled = True
sql_alchemy_pool_size = 5
sql_alchemy_max_overflow = 10
sql_alchemy_pool_recycle = 1800
sql_alchemy_pool_pre_ping = True
sql_alchemy_schema =
sql_alchemy_reconnect_timeout = 300
I've also tried upping the pool size to 20, and also confirmed that our db size should be able to handle at least 90 concurrent connections.
[2022-04-28 16:32:03,212] {manager.py:512} WARNING - Refused to delete permission view, assoc with role exists DAG Runs.can_create Admin
Process ForkProcess-19:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1277, in _execute_context
cursor, statement, parameters, context
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 608, in do_execute
cursor.execute(statement, parameters)
File "/usr/local/lib/python3.6/site-packages/MySQLdb/cursors.py", line 206, in execute
res = self._query(query)
File "/usr/local/lib/python3.6/site-packages/MySQLdb/cursors.py", line 319, in _query
db.query(q)
File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 254, in query
_mysql.connection.query(self, query)
MySQLdb._exceptions.OperationalError: (2006, 'MySQL server has gone away')
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/usr/local/lib/python3.6/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.6/site-packages/airflow/dag_processing/manager.py", line 287, in _run_processor_manager
processor_manager.start()
File "/usr/local/lib/python3.6/site-packages/airflow/dag_processing/manager.py", line 520, in start
return self._run_parsing_loop()
File "/usr/local/lib/python3.6/site-packages/airflow/dag_processing/manager.py", line 585, in _run_parsing_loop
self._find_zombies()
File "/usr/local/lib/python3.6/site-packages/airflow/utils/session.py", line 70, in wrapper
return func(*args, session=session, **kwargs)
File "/usr/local/lib/python3.6/site-packages/airflow/dag_processing/manager.py", line 1079, in _find_zombies
LJ.latest_heartbeat < limit_dttm,
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 3373, in all
return list(self)
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 3535, in __iter__
return self._execute_and_instances(context)
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 3560, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1011, in execute
return meth(self, multiparams, params)
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/sql/elements.py", line 298, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1130, in _execute_clauseelement
distilled_params,
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1317, in _execute_context
e, statement, parameters, cursor, context
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1511, in _handle_dbapi_exception
sqlalchemy_exception, with_traceback=exc_info[2], from_=e
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 182, in raise_
raise exception
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1277, in _execute_context
cursor, statement, parameters, context
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 608, in do_execute
cursor.execute(statement, parameters)
File "/usr/local/lib/python3.6/site-packages/MySQLdb/cursors.py", line 206, in execute
res = self._query(query)
File "/usr/local/lib/python3.6/site-packages/MySQLdb/cursors.py", line 319, in _query
db.query(q)
File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 254, in query
_mysql.connection.query(self, query)
sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (2006, 'MySQL server has gone away')
[SQL: SELECT task_instance.try_number AS task_instance_try_number, task_instance.task_id AS task_instance_task_id, task_instance.dag_id AS task_instance_dag_id, task_instance.run_id AS task_instance_run_id, task_instance.start_date AS task_instance_start_date, task_instance.end_date AS task_instance_end_date, task_instance.duration AS task_instance_duration, task_instance.state AS task_instance_state, task_instance.max_tries AS task_instance_max_tries, task_instance.hostname AS task_instance_hostname, task_instance.unixname AS task_instance_unixname, task_instance.job_id AS task_instance_job_id, task_instance.pool AS task_instance_pool, task_instance.pool_slots AS task_instance_pool_slots, task_instance.queue AS task_instance_queue, task_instance.priority_weight AS task_instance_priority_weight, task_instance.operator AS task_instance_operator, task_instance.queued_dttm AS task_instance_queued_dttm, task_instance.queued_by_job_id AS task_instance_queued_by_job_id, task_instance.pid AS task_instance_pid, task_instance.executor_config AS task_instance_executor_config, task_instance.external_executor_id AS task_instance_external_executor_id, task_instance.trigger_id AS task_instance_trigger_id, task_instance.trigger_timeout AS task_instance_trigger_timeout, task_instance.next_method AS task_instance_next_method, task_instance.next_kwargs AS task_instance_next_kwargs, dag.fileloc AS dag_fileloc, dag_run_1.state AS dag_run_1_state, dag_run_1.id AS dag_run_1_id, dag_run_1.dag_id AS dag_run_1_dag_id, dag_run_1.queued_at AS dag_run_1_queued_at, dag_run_1.execution_date AS dag_run_1_execution_date, dag_run_1.start_date AS dag_run_1_start_date, dag_run_1.end_date AS dag_run_1_end_date, dag_run_1.run_id AS dag_run_1_run_id, dag_run_1.creating_job_id AS dag_run_1_creating_job_id, dag_run_1.external_trigger AS dag_run_1_external_trigger, dag_run_1.run_type AS dag_run_1_run_type, dag_run_1.conf AS dag_run_1_conf, dag_run_1.data_interval_start AS dag_run_1_data_interval_start, dag_run_1.data_interval_end AS dag_run_1_data_interval_end, dag_run_1.last_scheduling_decision AS dag_run_1_last_scheduling_decision, dag_run_1.dag_hash AS dag_run_1_dag_hash
FROM task_instance INNER JOIN job ON task_instance.job_id = job.id AND job.job_type IN (%s) INNER JOIN dag ON task_instance.dag_id = dag.dag_id INNER JOIN dag_run AS dag_run_1 ON dag_run_1.dag_id = task_instance.dag_id AND dag_run_1.run_id = task_instance.run_id
WHERE task_instance.state = %s AND (job.state != %s OR job.latest_heartbeat < %s)]
[parameters: ('LocalTaskJob', <TaskInstanceState.RUNNING: 'running'>, <TaskInstanceState.RUNNING: 'running'>, datetime.datetime(2022, 4, 28, 16, 27, 2, 870459))]
(Background on this error at: http://sqlalche.me/e/13/e3q8)```

How to fix AttributeError: 'bytes' object has no attribute 'encode' if using mysql?

Django development server was running fine using mysql up to yesterday. But today I get the error AttributeError: 'bytes' object has no attribute 'encode'.
I created a new blank django instance by running django-admin startproject newProject. It runs with 'ENGINE': 'django.db.backends.sqlite3'. But produces same error when I change it to 'ENGINE': 'django.db.backends.mysql'
System specification:
os: manjaro linux
virtual environment python version: 3.6
Django version: 2.2
MariaDB version: 10.3.15-1
Have not updated any related package in last 3 days.
The error:
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/lib64/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/lib64/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run
self.check_migrations()
File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/core/management/base.py", line 453, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__
self.build_graph()
File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/migrations/loader.py", line 212, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations
if self.has_table():
File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 56, in has_table
return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/backends/base/base.py", line 256, in cursor
return self._cursor()
File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/backends/base/base.py", line 233, in _cursor
self.ensure_connection()
File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection
self.connect()
File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/backends/base/base.py", line 197, in connect
self.init_connection_state()
File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 232, in init_connection_state
if self.features.is_sql_auto_is_null_enabled:
File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/backends/mysql/features.py", line 82, in is_sql_auto_is_null_enabled
cursor.execute('SELECT ##SQL_AUTO_IS_NULL')
File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/backends/utils.py", line 103, in execute
sql = self.db.ops.last_executed_query(self.cursor, sql, params)
File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/backends/mysql/operations.py", line 147, in last_executed_query
query = query.encode(errors='replace')
AttributeError: 'bytes' object has no attribute 'encode'
How do I fix this ?
Thank to Martijn, I have fixed this.
In the source, stable 2.2 branch line 146 of django/db/backends/mysql/operations.py is
query = query.decode(errors='replace')
In my system path/to/virtualenv/django/db/backends/mysql/operations.py was like
# query = query.decode(errors='replace')
query = query.encode(errors='replace')
I changed it to
query = query.decode(errors='replace')
# query = query.encode(errors='replace')
It is working correctly now.

mysql.connector.errors.InterfaceError: Failed parsing EOF packet

I run into such problems when I running my Django project(a week ago, the project work properly, today find this problem):
My Django version is 1.10.2 with python version 3.5.2, MySQL version is 5.5 on ubuntu 14.0.
/Users/deja/Virtualenv/python3.5/bin/python3.5 /Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py --multiproc --qt-support --client 127.0.0.1 --port 60850 --file /Users/mozat/project/crawler_management_system/manage.py runserver 0.0.0.0:6380
pydev debugger: process 81527 is connecting
Connected to pydev debugger (build 145.1504)
pydev debugger: process 81528 is connecting
Performing system checks...
System check identified no issues (0 silenced).
You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
January 03, 2017 - 07:55:47
Django version 1.10.2, using settings 'crawler_management_system.settings'
Starting development server at http://0.0.0.0:6380/
Quit the server with CONTROL-C.
Internal Server Error: /
Traceback (most recent call last):
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/network.py", line 226, in recv_plain
chunk = self.sock.recv(4 - packet_len)
socket.timeout: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/mozat/project/crawler_management_system/crawler_management_system/mysql_utility.py", line 32, in open_db
raise err
File "/Users/mozat/project/crawler_management_system/crawler_management_system/mysql_utility.py", line 28, in open_db
yield cursor
File "/Users/mozat/project/crawler_management_system/crawler_management_system/views.py", line 40, in select_batch_records
cursor.execute(sql.format(table=self.table,times=times))
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/cursor.py", line 515, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/connection.py", line 488, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/connection.py", line 267, in _send_cmd
return self._socket.recv()
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/network.py", line 255, in recv_plain
errno=2055, values=(self.get_address(), _strioerror(err)))
mysql.connector.errors.OperationalError: 2055: Lost connection to MySQL server at '127.0.0.1:10189', system error: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/connection.py", line 710, in reset_session
self.cmd_reset_connection()
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/connection.py", line 1046, in cmd_reset_connection
raise errors.NotSupportedError("MySQL version 5.7.2 and "
mysql.connector.errors.NotSupportedError: MySQL version 5.7.2 and earlier does not support COM_RESET_CONNECTION.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/protocol.py", line 267, in parse_eof
unpacked = struct_unpack('<xxxBBHH', packet)
struct.error: unpack requires a bytes object of length 9
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/mozat/project/crawler_management_system/crawler_management_system/views.py", line 99, in mainpage
result = batch_record_repo.select_batch_records(times)
File "/Users/mozat/project/crawler_management_system/crawler_management_system/views.py", line 41, in select_batch_records
return cursor.fetchall()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/contextlib.py", line 77, in __exit__
self.gen.throw(type, value, traceback)
File "/Users/mozat/project/crawler_management_system/crawler_management_system/mysql_utility.py", line 40, in open_db
connection.close()
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/pooling.py", line 117, in close
cnx.reset_session()
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/connection.py", line 713, in reset_session
self._database, self._charset_id)
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/connection.py", line 661, in cmd_change_user
self._post_connection()
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/abstracts.py", line 695, in _post_connection
self.set_charset_collation(self._charset_id)
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/abstracts.py", line 654, in set_charset_collation
charset_name, collation_name))
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/connection.py", line 869, in _execute_query
self.cmd_query(query)
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/connection.py", line 488, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/connection.py", line 393, in _handle_result
return self._handle_eof(packet)
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/connection.py", line 344, in _handle_eof
eof = self._protocol.parse_eof(packet)
File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/protocol.py", line 269, in parse_eof
raise errors.InterfaceError(err_msg)
mysql.connector.errors.InterfaceError: Failed parsing EOF packet.
[03/Jan/2017 07:56:40] "GET / HTTP/1.1" 500 172448
anyone happen to see same problem?Could you please give me some suggestion.
all ,nothing wrong with mysql, and Django. It's for I use a complex SQL to access mysql:
SELECT *
FROM
(SELECT *,
#batch_rank := IF(#current_batch = spider , #batch_rank + 1, 1) AS batch_rank,
#current_batch := spider
FROM deja_crawler.crawl_batch_record
where spider in (select distinct spider from deja_crawler.crawl_batch_record where spider like '%_new' or spider like '%_update')
ORDER BY spider, create_time DESC)
ranked
WHERE batch_rank <= 3
the tables used to have not too much data, so it works, later, the table became huge, and the access time cost is almost 30s, but the connection time out is set as 20s, so it will raise time out error.

Jupyter Octave Kernel on Windows7

Followed the instructions at https://github.com/Calysto/octave_kernel to install octave_kernel on a Windows1 machine and everything went ok. However, when I select Octave as my kernal from Jupyter, the following occurs.
The kernel has died, and the automatic restart has failed. It is
possible the kernel cannot be restarted. If you are not able to
restart the kernel, you will still be able to save the notebook, but
running code will no longer work until the notebook is reopened.
I also cannot get oct2py to work.
The Jupyter console output from the octave_kernal attempt follows.
PermissionError: [WinError 5] Access is denied
[I 18:00:38.987 NotebookApp] KernelRestarter: restarting kernel (4/5)
WARNING:root:kernel f15e40d3-8288-4b9b-bb32-dea6b67484e1 restarted
Traceback (most recent call last):
File "C:\Anaconda3\lib\runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "C:\Anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Anaconda3\lib\site-packages\octave_kernel\__main__.py", line 6, in <m
odule>
IPKernelApp.launch_instance(kernel_class=OctaveKernel)
File "C:\Anaconda3\lib\site-packages\traitlets\config\application.py", line 59
5, in launch_instance
app.initialize(argv)
File "<decorator-gen-123>", line 2, in initialize
File "C:\Anaconda3\lib\site-packages\traitlets\config\application.py", line 74
, in catch_config_error
return method(app, *args, **kwargs)
File "C:\Anaconda3\lib\site-packages\ipykernel\kernelapp.py", line 421, in ini
tialize
self.init_kernel()
File "C:\Anaconda3\lib\site-packages\ipykernel\kernelapp.py", line 360, in ini
t_kernel
user_ns=self.user_ns,
File "C:\Anaconda3\lib\site-packages\traitlets\config\configurable.py", line 4
05, in instance
inst = cls(*args, **kwargs)
File "C:\Anaconda3\lib\site-packages\metakernel\process_metakernel.py", line 5
3, in __init__
self._start()
File "C:\Anaconda3\lib\site-packages\metakernel\process_metakernel.py", line 5
8, in _start
self.wrapper = self.makeWrapper()
File "C:\Anaconda3\lib\site-packages\octave_kernel\kernel.py", line 82, in mak
eWrapper
if 'version 4' in self.banner:
File "C:\Anaconda3\lib\site-packages\octave_kernel\kernel.py", line 63, in ban
ner
banner = subprocess.check_output([self.executable, '--version'])
File "C:\Anaconda3\lib\subprocess.py", line 629, in check_output
**kwargs).stdout
File "C:\Anaconda3\lib\subprocess.py", line 696, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\Anaconda3\lib\subprocess.py", line 950, in __init__
restore_signals, start_new_session)
File "C:\Anaconda3\lib\subprocess.py", line 1220, in _execute_child
startupinfo)
PermissionError: [WinError 5] Access is denied
[W 18:00:42.002 NotebookApp] KernelRestarter: restart failed
[W 18:00:42.002 NotebookApp] Kernel f15e40d3-8288-4b9b-bb32-dea6b67484e1 died, r
emoving from map.
ERROR:root:kernel f15e40d3-8288-4b9b-bb32-dea6b67484e1 restarted failed!
[W 18:00:42.002 NotebookApp] Kernel deleted before session
[W 18:00:42.002 NotebookApp] 410 DELETE /api/sessions/d25e7956-2a56-4977-a2de-8b
9c3f828a05 (::1) 0.00ms referer=http://localhost:8888/notebooks/Untitled6.ipynb?
kernel_name=octave
I saw the permission error and tried to run Jupyter as an administrator to no avail.
Set enviornment variale OCTAVE_EXECUTABLE as C:\Octave\Octave-4.2.1\bin\octave-cli-4.2.1.exe. Provide full R/W permission to user Everyone on Octave install folder

Django 1.6 w/ gunicorn - OperationalError: (2006, 'MySQL server has gone away')

In the process of upgrading to Django 1.6 I've started to get a frequent OperationalError: (2006, 'MySQL server has gone away') message on requests to the gunicorn server I use to run the django app. These errors occur instantly from the moment the server is started, on requests that should only take a second which makes me doubt that it is a timeout issue. This error isn't present on the old 1.4 branch of the project and the 1.6 branch doesn't behave this way if it's served simply through django-admin.py runserver.
I generally run gunicorn through an sv process (though it errors if I run it manually too) with the command django-admin.py run_gunicorn --workers=4 -b localhost:8000 which results in many requests, even ones for static media, returning with:
[ERROR] 2015-07-29 14:30:27,931 - gunicorn.error:260 - Error handling request
Traceback (most recent call last):
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 125, in handle_request
respiter = self.wsgi(environ, resp.start_response)
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 187, in __call__
self.load_middleware()
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 47, in load_middleware
mw_instance = mw_class()
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/django/middleware/locale.py", line 24, in __init__
for url_pattern in get_resolver(None).url_patterns:
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 365, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 360, in urlconf_module
self._urlconf_module = import_module(self.urlconf_name)
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/opt/apps/maplecroft/versions/current/websites/maplecroft/urls.py", line 2, in <module>
from maplecroft.views import RiskAtlasesLandingView
File "/opt/apps/maplecroft/versions/current/maplecroft/views.py", line 40, in <module>
import maplecroft.search as _search
File "/opt/apps/maplecroft/versions/current/maplecroft/search.py", line 71, in <module>
class MaplecroftSearchForm(SearchForm):
File "/opt/apps/maplecroft/versions/current/maplecroft/search.py", line 111, in MaplecroftSearchForm
choices=model_choices(),
File "/opt/apps/maplecroft/versions/current/maplecroft/search.py", line 57, in model_choices
for category in reversed(Category.objects.filter(parent=None)):
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/django/db/models/query.py", line 77, in __len__
self._fetch_all()
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/django/db/models/query.py", line 857, in _fetch_all
self._result_cache = list(self.iterator())
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/django/db/models/query.py", line 220, in iterator
for row in compiler.results_iter():
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 713, in results_iter
for rows in self.execute_sql(MULTI):
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 786, in execute_sql
cursor.execute(sql, params)
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/django/db/backends/util.py", line 69, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/django/db/utils.py", line 99, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 124, in execute
return self.cursor.execute(query, args)
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/opt/envs/maplecroft/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
OperationalError: (2006, 'MySQL server has gone away')
However, if I drop to --workers=1 everything seems to run smoothly so my current thoughts are that it is an issue with the threaded workers feature of gunicorn?
Edit: I just tried upgrading gunicorn to the latest version (was on 0.17.2) but that doesn't seem to have made a difference.
I am wondering if this question: https://serverfault.com/questions/407612/error-2006-mysql-server-has-gone-away is relevant, but struggling to overlay it with my current issues
It appears that it was the gunicorn version after all- I tried upgrading gunicorn but was still using the django-admin.py run_gunicorn method of starting the server. Upgrading gunicorn and switching to the non-deprecated gunicorn wsgi:application method solved it.