I've started getting this error on the production environment this morning, after getting Django-storages, Boto, and Django-compressor working to put static files on S3 yesterday, though I don't know if that is related...
OperationalError: could not fork new process for connection: Cannot allocate memory
could not fork new process for connection: Cannot allocate memory
could not fork new process for connection: Cannot allocate memory
Stacktrace (most recent call last):
File "django/core/handlers/base.py", line 89, in get_response
response = middleware_method(request)
File "reversion/middleware.py", line 17, in process_request
if hasattr(request, "user") and request.user.is_authenticated():
File "django/utils/functional.py", line 184, in inner
self._setup()
File "django/utils/functional.py", line 248, in _setup
self._wrapped = self._setupfunc()
File "django/contrib/auth/middleware.py", line 16, in <lambda>
request.user = SimpleLazyObject(lambda: get_user(request))
File "django/contrib/auth/middleware.py", line 8, in get_user
request._cached_user = auth.get_user(request)
File "django/contrib/auth/__init__.py", line 98, in get_user
user_id = request.session[SESSION_KEY]
File "django/contrib/sessions/backends/base.py", line 39, in __getitem__
return self._session[key]
File "django/contrib/sessions/backends/base.py", line 165, in _get_session
self._session_cache = self.load()
File "django/contrib/sessions/backends/db.py", line 19, in load
expire_date__gt=timezone.now()
File "django/db/models/manager.py", line 131, in get
return self.get_query_set().get(*args, **kwargs)
File "django/db/models/query.py", line 361, in get
num = len(clone)
File "django/db/models/query.py", line 85, in __len__
self._result_cache = list(self.iterator())
File "django/db/models/query.py", line 291, in iterator
for row in compiler.results_iter():
File "django/db/models/sql/compiler.py", line 763, in results_iter
for rows in self.execute_sql(MULTI):
File "django/db/models/sql/compiler.py", line 817, in execute_sql
cursor = self.connection.cursor()
File "django/db/backends/__init__.py", line 308, in cursor
cursor = util.CursorWrapper(self._cursor(), self)
File "django/db/backends/postgresql_psycopg2/base.py", line 177, in _cursor
self.connection = Database.connect(**conn_params)
File "psycopg2/__init__.py", line 178, in connect
return _connect(dsn, connection_factory=connection_factory, async=async)
I am deploying the site on Heroku. It works for a bit after I restart the application, but stops working again after a few minutes.
Any ideas as to what might be causing this?
I encountered the same problem trying to set up a simple django web application with a postgresql database on heroku and managed to solve it.
I don't fully understand the error but the fix is fairly simple: when you are passing python lists created by queries to your database, you need to limit the size of the list.
So for example if you are passing as context the following list:
set_list = userSetTable.objects.all()
return render(request, 'fc/user.html', {'set_list': set_list,})
That will cause an error because set_list might be really big. You need to specify a maximum size:
set_list = userSetTable.objects.all()[0:20]
So in a real-world application, you might want to display the list as page results or whatever... you get the point.
Related
Stack:
Ubuntu (20.04 LTS)
Nginx
Postgresql (v13.3)
An AWS load balancer sends traffic to the Ubuntu instance(k8s cluster), which is handled by Nginx, which forwards on to Django (4.0.3) running in gunicorn (19.9.0). Django connects to the database using psycopg2 (2.8.6).
The issue I have is that the database connection seems to shut down randomly.
Django reports errors like this:
`InterfaceError: connection already closed
File "django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "contextlib.py", line 79, in inner
return func(*args, **kwds)
File "django/views/generic/base.py", line 84, in view
return self.dispatch(request, *args, **kwargs)
File "django/utils/decorators.py", line 46, in _wrapper
return bound_method(*args, **kwargs)
File "django/views/decorators/cache.py", line 62, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "django/views/generic/base.py", line 119, in dispatch
return handler(request, *args, **kwargs)
File "django/views/generic/detail.py", line 108, in get
self.object = self.get_object()
File "django/views/generic/detail.py", line 53, in get_object
obj = queryset.get()
File "django/db/models/query.py", line 492, in get
num = len(clone)
File "django/db/models/query.py", line 302, in __len__
self._fetch_all()
File "django/db/models/query.py", line 1507, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "django/db/models/query.py", line 57, in __iter__
results = compiler.execute_sql(
File "django/db/models/sql/compiler.py", line 1359, in execute_sql
cursor = self.connection.cursor()
File "django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "django/db/backends/base/base.py", line 284, in cursor
return self._cursor()
File "django/db/backends/base/base.py", line 262, in _cursor
return self._prepare_cursor(self.create_cursor(name))
File "django/db/utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "django/db/backends/base/base.py", line 262, in _cursor
return self._prepare_cursor(self.create_cursor(name))
File "django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "django/db/backends/postgresql/base.py", line 256, in create_cursor
cursor = self.connection.cursor()`
Postgresql does not report any major errors: I can only assume that the connection was closed correctly and Django was not expecting it.
This happens quite rarely, but enough to be a concern: once every 3 days.
Any suggestions of how to investigate this further would be gratefully accepted. Thanks in advance!
I'm using django-service-objects and Django-Q for a distributed data mining code. I ran into a error "django.db.utils.InterfaceError: connection already closed" when I was running Django-Q cluster async_task(..., sync=True) to debug and attempted to query the Django PostgreSQL 13 DB using Model.object.get(pk=...).
I resolved the issue by setting db_transaction = False within the Service class.
class dataMining(Service):
db_transaction = False
https://django-service-objects.readthedocs.io/en/stable/pages/usage.html#database-transactions
The effect of db_transaction=True (enabled by default) is to "...process method on services ... inside a transaction". Meaning changes to the Django PostgreSQL DB are not actually saved until the def process(self) method of the Service class completes successfully. https://django-service-objects.readthedocs.io/en/stable/pages/usage.html#service
I suspect the self.object = self.get_object() call in your code sample is experiencing the same problem of being 'locked out' during a process method within a DB transaction.
After forcefully killing (kill -9) the idle db connections. Celery log showing the below error
[2016-03-08 19:28:04,765: CRITICAL/MainProcess] Task users.tasks.refresh_trend_buzz_messages[85a2430a-9a39-4979-b99d-fcaae86b3ba1] INTERNAL ERROR: InterfaceError('connection already closed',)
Traceback (most recent call last):
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/celery/app/trace.py", line 253, in trace_task
I, R, state, retval = on_error(task_request, exc, uuid)
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/celery/app/trace.py", line 201, in on_error
R = I.handle_error_state(task, eager=eager)
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/celery/app/trace.py", line 85, in handle_error_state
}[self.state](task, store_errors=store_errors)
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/celery/app/trace.py", line 118, in handle_failure
req.id, exc, einfo.traceback, request=req,
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/celery/backends/base.py", line 120, in mark_as_failure
traceback=traceback, request=request)
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/celery/backends/base.py", line 251, in store_result
request=request, **kwargs)
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/djcelery/backends/database.py", line 29, in _store_result
traceback=traceback, children=self.current_task_children(request),
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/djcelery/managers.py", line 42, in _inner
return fun(*args, **kwargs)
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/djcelery/managers.py", line 181, in store_result
'meta': {'children': children}})
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/djcelery/managers.py", line 87, in update_or_create
return get_queryset(self).update_or_create(**kwargs)
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/djcelery/managers.py", line 70, in update_or_create
obj, created = self.get_or_create(**kwargs)
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/django/db/models/query.py", line 373, in get_or_create
return self.get(**lookup), False
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/django/db/models/query.py", line 301, in get
num = len(clone)
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/django/db/models/query.py", line 77, in __len__
self._fetch_all()
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/django/db/models/query.py", line 854, in _fetch_all
self._result_cache = list(self.iterator())
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/django/db/models/query.py", line 220, in iterator
for row in compiler.results_iter():
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 710, in results_iter
for rows in self.execute_sql(MULTI):
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 780, in execute_sql
cursor = self.connection.cursor()
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 159, in cursor
cursor = util.CursorWrapper(self._cursor(), self)
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 131, in _cursor
return self.create_cursor()
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/django/db/utils.py", line 99, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 131, in _cursor
return self.create_cursor()
File "/home/.virtualenvs/backend/local/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 139, in create_cursor
cursor = self.connection.cursor()
InterfaceError: connection already closed
I'm using Django==1.6.1, celery==3.1.10, django-celery==3.1.10 and psycopg2==2.4.1
How can I fix the error ?
This is the expected behaviour. Each celery worker will open a connection to the database and try to reuse it to avoid the overhead of negotiation every time. By killing the database processes you close the connection, hence the error.
What are you trying to achieve by killing the database processes?
You need to adjust max_connections in your PostgreSQL configuration.
You will need at least 1 connection for each celery worker plus enough for any other client code.
Thanks for taking the time to look at my question!
I am trying to run the following raw query in django on googleappgine:
models.MyModel.objects.raw(
'select count(1) from myapp_mymodel where %s >= my_column',
[4])
I keep getting the error:
NotImplementedError: Cursors are not supported.
However, cursors do seem to be implemented in djangoappengine.
Has anyone else run into this issue??
Traceback:
File "..../django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "..../promotions/views.py", line 562, in task_alert_stats
auto_join_sql, auto_join_params)[0]
File "..../django/db/models/query.py", line 1381, in __getitem__
return list(self)[k]
File "..../django/db/models/query.py", line 1326, in __iter__
query = iter(self.query)
File "..../django/db/models/sql/query.py", line 67, in __iter__
self._execute_query()
File "..../django/db/models/sql/query.py", line 81, in _execute_query
self.cursor.execute(self.sql, self.params)
File "..../django/db/backends/util.py", line 34, in execute
return self.cursor.execute(sql, params)
File "..../djangotoolbox/db/base.py", line 620, in __getattribute__
raise NotImplementedError("Cursors are not supported.")
To anyone who comes across this:
I ended up doing a simple filter and then going through the results to further filter them.
When I run a management command it opens a browser window.
I authenticate the app which creates a oauth file ~/.googlesql_oauth2.dat.
But it throws a DatabaseError afterwards.
End user Google Account not authorized.enter
Any ideas how to fix this?
Stacktrace:
Unhandled exception in thread started by <bound method Command.inner_run of <django.core.management.commands.runserver.Command object at 0x100646f50>>
Traceback (most recent call last):
File "/usr/local/google_appengine/lib/django_1_3/django/core/management/commands/runserver.py", line 88, in inner_run
self.validate(display_num_errors=True)
File "/usr/local/google_appengine/lib/django_1_3/django/core/management/base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "/usr/local/google_appengine/lib/django_1_3/django/core/management/validation.py", line 102, in get_validation_errors
connection.validation.validate_field(e, opts, f)
File "/usr/local/google_appengine/lib/django_1_3/django/db/backends/mysql/validation.py", line 14, in validate_field
db_version = self.connection.get_server_version()
File "/usr/local/google_appengine/lib/django_1_3/django/db/backends/mysql/base.py", line 338, in get_server_version
self.cursor()
File "/usr/local/google_appengine/lib/django_1_3/django/db/backends/__init__.py", line 250, in cursor
cursor = self.make_debug_cursor(self._cursor())
File "/usr/local/google_appengine/google/storage/speckle/python/django/backend/base.py", line 223, in _cursor
self.connection = Connect(**kwargs)
File "/usr/local/google_appengine/google/storage/speckle/python/django/backend/base.py", line 195, in Connect
return driver.connect(**kwargs)
File "/usr/local/google_appengine/google/storage/speckle/python/api/rdbms_googleapi.py", line 183, in __init__
super(GoogleApiConnection, self).__init__(*args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/storage/speckle/python/api/rdbms.py", line 583, in __init__
self.OpenConnection()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/storage/speckle/python/api/rdbms.py", line 606, in OpenConnection
response = self.MakeRequest('OpenConnection', request)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/storage/speckle/python/api/rdbms.py", line 718, in MakeRequest
response.sql_exception.message))
google.storage.speckle.python.api.rdbms.DatabaseError: 0: End user Google Account not authorized.enter
All right, I was logged in as a different user when authorizing -.-
add_to_builtins('gravatar.gravatar')
is being used in my settings.py file, and it causes a crash on page load with this error:
Traceback (most recent call last):
File "C:\development\python\Lib\site-packages\django\core\servers\basehttp.py", line 283, in run
self.result = application(self.environ, self.start_response)
File "C:\development\python\Lib\site-packages\django\contrib\staticfiles\handlers.py", line 68, in call
return self.application(environ, start_response)
File "C:\development\python\Lib\site-packages\django\core\handlers\wsgi.py", line 272, in call
response = self.get_response(request)
File "C:\development\python\Lib\site-packages\django\core\handlers\base.py", line 169, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "C:\development\python\Lib\site-packages\django\core\handlers\base.py", line 203, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "C:\development\python\Lib\site-packages\django\views\debug.py", line 59, in technical_500_response
html = reporter.get_traceback_html()
File "C:\development\python\Lib\site-packages\django\views\debug.py", line 128, in get_traceback_html
t = Template(TECHNICAL_500_TEMPLATE, name='Technical 500 template')
File "C:\development\python\Lib\site-packages\django\template\base.py", line 108, in init
self.nodelist = compile_string(template_string, origin)
File "C:\development\python\Lib\site-packages\django\template\base.py", line 135, in compile_string
parser = parser_class(lexer.tokenize())
File "C:\development\python\Lib\site-packages\django\template\debug.py", line 34, in init
super(DebugParser, self).init(lexer)
File "C:\development\python\Lib\site-packages\django\template\base.py", line 208, in init
print lib.tags
AttributeError: 'NoneType' object has no attribute 'tags'
If i don't have any issue with using gravatar if i don't use the add_to_builtins functionality - that is, with plain old load tags in my views. I'm just using it a fair bit, so thought i might make use of the add_to_builtins functionality.
From the looks of things, the imported version crashes because the import_library(module) for gravatar.gravatar returns None (i know this because i printed out that line, and it returns None) - what is wrong with what i've done?
oh gravatar.
Ok, so i was all wrong in how to import this using the add_to_builtins - what i needed to do was:
add_to_builtins('gravatar.templatetags.gravatar')
i'm unsure as to why, but that works a treat. Now i don't need to have any messy "load" statements, and i can happily call
{% gravatar story.user 40 %}
from any of my templates. yay!