DRF - Getting 'NoneType object is not callable' error on delete instance from ModelViewSet - postgresql

I am getting TypeError, when I try to delete Warehouse instance.
Note: If I delete Shop instance, Warehouse under that Shop needs be deleted, that's why I used on_delete=models.CASCADE.
class Warehouse(models.Model):
"""Warehouse model"""
name = models.CharField(max_length=255)
shop = models.ForeignKey(Shop, on_delete=models.CASCADE)
class WarehouseViewSet(viewsets.ModelViewSet):
"""Viewset"""
queryset = models.Warehouse.objects.all()
serializer_class = serializers.WarehouseSerializer
Error:
TypeError: 'NoneType' object is not callable
[14/Feb/2021 22:10:46] "DELETE /api/v1/shop/warehouse/2/ HTTP/1.1" 500 113266
Internal Server Error: /api/v1/shop/warehouse/2/
Traceback (most recent call last):
File "C:\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python38\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Python38\lib\site-packages\rest_framework\viewsets.py", line 114, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Python38\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Python38\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Python38\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Python38\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Python38\lib\site-packages\rest_framework\mixins.py", line 91, in destroy
self.perform_destroy(instance)
File "C:\Python38\lib\site-packages\rest_framework\mixins.py", line 95, in perform_destroy
instance.delete()
File "C:\Python38\lib\site-packages\django\db\models\base.py", line 921, in delete
collector.collect([self], keep_parents=keep_parents)
File "C:\Python38\lib\site-packages\django\db\models\deletion.py", line 224, in collect
field.remote_field.on_delete(self, field, sub_objs, self.using)

Found the solution. I did not handle on_delete for Children model.
SOLUTION
class WarehouseChildren(models.Model):
data = models.PositiveIntegerField(default=0)
warehouse = models.ForeignKey(Warehouse, on_delete=models.SET_NULL, null=True)
or
class WarehouseChildren(models.Model):
data = models.PositiveIntegerField(default=0)
warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE)

Related

Error when using find/find_one pymongo methods when on an apache2 server (mongodb atlas)

when using find/find_one pymongo methods when on an apache2 server i get the following error :
No <class 'cryptography.x509.extensions.TLSFeature'> extension was found
when using pymongo on an apache2 server to connect and insert or delete in my mongodb collections it works just fine, but when i try to pull something out of the database (using find or find_one methods) i get an error, please note that this error only occurs while running the apache2 server, because when i connected and used find methods in a locally run python script it gave me the information without any errors.
if it is of any relevance, the web framework i am using is flask.
Edit : As for what is producing the error i dont know for sure, so here are the logs.
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/flask/app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.10/dist-packages/flask/app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.10/dist-packages/flask/app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.10/dist-packages/flask/app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "/var/www/html/srv21/SRVApp.py", line 17, in downloadpage
ThreadID = ThreadID.next()
File "/usr/local/lib/python3.10/dist-packages/pymongo/cursor.py", line 1248, in next
if len(self.__data) or self._refresh():
File "/usr/local/lib/python3.10/dist-packages/pymongo/cursor.py", line 1165, in _refresh
self.__send_message(q)
File "/usr/local/lib/python3.10/dist-packages/pymongo/cursor.py", line 1052, in __send_message
response = client._run_operation(
File "/usr/local/lib/python3.10/dist-packages/pymongo/_csot.py", line 105, in csot_wrapper
return func(self, *args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/pymongo/mongo_client.py", line 1330, in _run_operation
return self._retryable_read(
File "/usr/local/lib/python3.10/dist-packages/pymongo/_csot.py", line 105, in csot_wrapper
return func(self, *args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/pymongo/mongo_client.py", line 1442, in _retryable_read
with self._socket_from_server(read_pref, server, session) as (sock_info, read_pref):
File "/usr/lib/python3.10/contextlib.py", line 135, in __enter__
return next(self.gen)
File "/usr/local/lib/python3.10/dist-packages/pymongo/mongo_client.py", line 1282, in _socket_from_server
with self._get_socket(server, session) as sock_info:
File "/usr/lib/python3.10/contextlib.py", line 135, in __enter__
return next(self.gen)
File "/usr/local/lib/python3.10/dist-packages/pymongo/mongo_client.py", line 1217, in _get_socket
with server.get_socket(handler=err_handler) as sock_info:
File "/usr/lib/python3.10/contextlib.py", line 135, in __enter__
return next(self.gen)
File "/usr/local/lib/python3.10/dist-packages/pymongo/pool.py", line 1407, in get_socket
sock_info = self._get_socket(handler=handler)
File "/usr/local/lib/python3.10/dist-packages/pymongo/pool.py", line 1520, in _get_socket
sock_info = self.connect(handler=handler)
File "/usr/local/lib/python3.10/dist-packages/pymongo/pool.py", line 1358, in connect
sock = _configured_socket(self.address, self.opts)
File "/usr/local/lib/python3.10/dist-packages/pymongo/pool.py", line 1061, in _configured_socket
sock = ssl_context.wrap_socket(sock, server_hostname=host)
File "/usr/local/lib/python3.10/dist-packages/pymongo/pyopenssl_context.py", line 369, in wrap_socket
ssl_conn.do_handshake()
File "/usr/local/lib/python3.10/dist-packages/pymongo/pyopenssl_context.py", line 125, in do_handshake
return self._call(super(_sslConn, self).do_handshake, *args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/pymongo/pyopenssl_context.py", line 108, in _call
return call(*args, **kwargs)
File "/usr/lib/python3/dist-packages/OpenSSL/SSL.py", line 1894, in do_handshake
self._raise_ssl_error(self._ssl, result)
File "/usr/lib/python3/dist-packages/OpenSSL/SSL.py", line 1603, in _raise_ssl_error
self._context._ocsp_helper.raise_if_problem()
File "/usr/lib/python3/dist-packages/OpenSSL/SSL.py", line 319, in raise_if_problem
raise self._problems.pop(0)
File "/usr/lib/python3/dist-packages/OpenSSL/SSL.py", line 539, in wrapper
valid = callback(conn, ocsp_data, data)
File "/usr/local/lib/python3.10/dist-packages/pymongo/ocsp_support.py", line 298, in _ocsp_callback
ext = _get_extension(cert, _TLSFeature)
File "/usr/local/lib/python3.10/dist-packages/pymongo/ocsp_support.py", line 114, in _get_extension
return cert.extensions.get_extension_for_class(klass)
File "/usr/local/lib/python3.10/dist-packages/cryptography/x509/extensions.py", line 135, in get_extension_for_class
raise ExtensionNotFound(
cryptography.x509.extensions.ExtensionNotFound: No <class 'cryptography.x509.extensions.TLSFeature'> extension was found

Why Pgadmin gives me 500 error? _pickle.PicklingError: Can't pickle <class 'wtforms.form.Meta'>: attribute lookup Meta on wtforms.form failed

Occasionally, Pgadmin gives me the 500 error in a browser. After reloading the page, the issue disappears for a while and then comes back again. Here's the log I see while getting the error:
[2022-01-21 14:35:21 +0000] [93] [ERROR] Error handling request /authenticate/login
Traceback (most recent call last):
File "/venv/lib/python3.8/site-packages/gunicorn/workers/gthread.py", line 271, in handle
keepalive = self.handle_request(req, conn)
File "/venv/lib/python3.8/site-packages/gunicorn/workers/gthread.py", line 323, in handle_request
respiter = self.wsgi(environ, resp.start_response)
File "/venv/lib/python3.8/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/pgadmin4/pgAdmin4.py", line 77, in __call__
return self.app(environ, start_response)
File "/venv/lib/python3.8/site-packages/werkzeug/middleware/proxy_fix.py", line 169, in __call__
return self.app(environ, start_response)
File "/venv/lib/python3.8/site-packages/flask_socketio/__init__.py", line 43, in __call__
return super(_SocketIOMiddleware, self).__call__(environ,
File "/venv/lib/python3.8/site-packages/engineio/middleware.py", line 74, in __call__
return self.wsgi_app(environ, start_response)
File "/venv/lib/python3.8/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/venv/lib/python3.8/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/venv/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/venv/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/venv/lib/python3.8/site-packages/flask/app.py", line 1953, in full_dispatch_request
return self.finalize_request(rv)
File "/venv/lib/python3.8/site-packages/flask/app.py", line 1970, in finalize_request
response = self.process_response(response)
File "/venv/lib/python3.8/site-packages/flask/app.py", line 2269, in process_response
self.session_interface.save_session(self, ctx.session, response)
File "/pgadmin4/pgadmin/utils/session.py", line 307, in save_session
self.manager.put(session)
File "/pgadmin4/pgadmin/utils/session.py", line 166, in put
self.parent.put(session)
File "/pgadmin4/pgadmin/utils/session.py", line 270, in put
dump(
_pickle.PicklingError: Can't pickle <class 'wtforms.form.Meta'>: attribute lookup Meta on wtforms.form failed
The issue appeared after enabling Oauth2 authentication. I've tried using different version but no luck.
Pgadmin is running in Kubernetes.
Please try setting
PGADMIN_CONFIG_ENHANCED_COOKIE_PROTECTION = False in configuration file according to your operating system as mentioned here.

google.api_core.exceptions.ServiceUnavailable: 503 Deadline Exceeded

google.api_core.exceptions.ServiceUnavailable: 503 Deadline Exceeded
using python 3.7 ,google-cloud-pubsub ==1.1.0 publishing data on topic. In my local machine it's working perfectly fine and able to publish data on that topic and also able to pull data from that topic through subscriber.
but don't understand it's not working when i deploy the code on server and it's failing with INLINE ERROR however when i explicitly call the publisher method on server it's publishing fine over server box also.code which is failing at below line while publishing:
future = publisher.publish(topic_path, data=data)
**ERROR:2020-02-20 14:24:42,714 ERROR Failed to publish 1 messages.**
Trackback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
return callable_(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/grpc/_channel.py", line 826, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/usr/local/lib/python3.7/site-packages/grpc/_channel.py", line 729, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.UNAVAILABLE
details = "Deadline Exceeded"
debug_error_string = "{"created":"#1582208682.711481693","description":"Deadline Exceeded","file":"src/core/ext/filters/deadline/deadline_filter.cc","file_line":69,"grpc_status":14}"
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/google/api_core/retry.py", line 184, in retry_target
return target()
File "/usr/local/lib/python3.7/site-packages/google/api_core/timeout.py", line 214, in func_with_timeout
return func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
google.api_core.exceptions.ServiceUnavailable: 503 Deadline Exceeded
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/google/cloud/pubsub_v1/publisher/_batch/thread.py", line 219, in _commit
response = self._client.api.publish(self._topic, self._messages)
File "/usr/local/lib/python3.7/site-packages/google/cloud/pubsub_v1/gapic/publisher_client.py", line 498, in publish
request, retry=retry, timeout=timeout, metadata=metadata
File "/usr/local/lib/python3.7/site-packages/google/api_core/gapic_v1/method.py", line 143, in call
return wrapped_func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/google/api_core/retry.py", line 286, in retry_wrapped_func
on_error=on_error,
File "/usr/local/lib/python3.7/site-packages/google/api_core/retry.py", line 206, in retry_target
last_exc,
File "", line 3, in raise_from
google.api_core.exceptions.RetryError: Deadline of 60.0s exceeded while calling functools.partial(.error_remapped_callable at 0x7f67d064e950>
You should try to chunk your data in reasonable sized chunks (max_messages) and don't forget to add a done callback.
# Loop over json containing records/rows
for idx, row in enumerate(rows_json):
publish_json(row, idx, rowmax=len(rows_json), topic_name)
# Publish messages asynchronous
def publish_json(msg, rowcount, rowmax, topic_project_id, topic_name):
batch_settings = pubsub_v1.types.BatchSettings(max_messages=100)
publisher = pubsub_v1.PublisherClient(batch_settings)
topic_path = publisher.topic_path(topic_project_id, topic_name)
future = publisher.publish(
topic_path, bytes(json.dumps(msg).encode('utf-8')))
future.add_done_callback(
lambda x: logging.info(
'Published msg with ID {} ({}/{} rows).'.format(
future.result(), rowcount, rowmax))
)

Odoo 8 -Browse a model in Object Class

I have Object class and i need to browse the model document.directory in this class. I tried this.
class node_database(object):
obj=openerp.registry(cr.dbname).get('document.directory')
print'obj',obj # it ptints document.directory
datas=obj.browse(cr,uid,ids)
print'datas',datas # Here nothing print
and also tried this:
osv_pool = pooler.get_pool(dbname)
dir_obj=osv_pool.get('document.directory')
Search function works fine but browse not?
Getting this error:
2016-06-24 06:41:52,690 9427 ERROR dms1 openerp.addons.document_ftp.ftpserver: Traceback (most recent call last):
File "/home/kabeer/odoo-8.0-20151229/openerp/addons/document_ftp/ftpserver/ftpserver.py", line 1806, in try_as_current_user
re=self.run_as_current_user(function, *args, **kwargs)
File "/home/kabeer/odoo-8.0-20151229/openerp/addons/document_ftp/ftpserver/ftpserver.py", line 1779, in run_as_current_user
return function(*args, **kwargs)
File "/home/kabeer/odoo-8.0-20151229/openerp/addons/document_ftp/ftpserver/abstracted_fs.py", line 509, in get_list_dir
listing = self.listdir(datacr)
File "/home/kabeer/odoo-8.0-20151229/openerp/addons/document_ftp/ftpserver/abstracted_fs.py", line 377, in listdir
res = node.children(cr)
File "/home/kabeer/odoo-8.0-20151229/openerp/addons/document/document.py", line 981, in children
res = self._child_get(cr, domain=domain) + self._file_get(cr)
File "/home/kabeer/odoo-8.0-20151229/openerp/addons/document/document.py", line 1022, in _child_get
print'cntobj_search_read',cntobj.search_read(cr, uid,[('id','=',1)],['name'],context=ctx)
File "/home/kabeer/odoo-8.0-20151229/openerp/api.py", line 256, in wrapper
return old_api(self, *args, **kwargs)
File "/home/kabeer/odoo-8.0-20151229/openerp/models.py", line 5186, in search_read
result = self.read(cr, uid, record_ids, fields, context=read_ctx)
File "/home/kabeer/odoo-8.0-20151229/openerp/api.py", line 256, in wrapper
return old_api(self, *args, **kwargs)
File "/home/kabeer/odoo-8.0-20151229/openerp/models.py", line 3144, in read
records = self.browse(cr, user, ids, context)
File "/home/kabeer/odoo-8.0-20151229/openerp/api.py", line 256, in wrapper
return old_api(self, *args, **kwargs)
File "/home/kabeer/odoo-8.0-20151229/openerp/models.py", line 5266, in browse
return self._browse(Environment(cr, uid, context or {}), ids)
File "/home/kabeer/odoo-8.0-20151229/openerp/api.py", line 740, in __new__
env, envs = None, cls.envs
File "/home/kabeer/odoo-8.0-20151229/openerp/tools/func.py", line 109, in __get__
return self.fget.__get__(None, owner)()
File "/home/kabeer/odoo-8.0-20151229/openerp/api.py", line 713, in envs
return cls._local.environments
File "/usr/lib/python2.7/dist-packages/werkzeug/local.py", line 71, in __getattr__
raise AttributeError(name)
AttributeError: environments
Any solution pls?
for item in obj.search(cr, uid, []):
obj = self.browse(cr, uid, item)
print obj.name
Resolved this issue by create a new cursor.
new_cr = openerp.sql_db.db_connect(self.context.cr.dbname).cursor()
uid, context = self.context.uid, self.context.context
with api.Environment.manage():
self.env = api.Environment(new_cr, uid, context)
try:
datas=obj.browse(cr,uid,ids)
print'datas',datas # Here print
finally:
self.env.cr.close()

download file from mongo gridfs with python

I have uploaded files to the mongo.But when I want to download from mongo by httpresonse on the web browser,that did not work.
Here is the views.py:
if filename is not None:
file_ = db.fs.files.find_one({
'filename':filename
})
file_id = file_['_id']
wrapper = fs.get(file_id).read()
response = StreamingHttpResponse(FileWrapper(wrapper),content_type=file_['contentType'])
response['Content-Disposition'] = 'attachment; filename=%s' % str(filename)
response['Content-Length'] = file_['length']
return response
I got this error:
Traceback (most recent call last):
File "/usr/lib/python2.7/wsgiref/handlers.py", line 86, in run
self.finish_response()
File "/usr/lib/python2.7/wsgiref/handlers.py", line 126, in finish_response
for data in self.result:
File "/usr/local/lib/python2.7/dist-packages/django/utils/six.py", line 473, in next
return type(self).__next__(self)
File "/usr/local/lib/python2.7/dist-packages/django/http/response.py", line 292, in __next__
return self.make_bytes(next(self._iterator))
File "/usr/lib/python2.7/wsgiref/util.py", line 30, in next
data = self.filelike.read(self.blksize)
AttributeError: 'str' object has no attribute 'read'
But when I change the StreamingHttpResponse to HttpResponse,the error is as follow:
[30/Jul/2014 17:29:43] "GET /download/cs101/ HTTP/1.1" 200 664
/usr/lib/python2.7/wsgiref/handlers.py:126: DeprecationWarning:
Creating streaming responses with `HttpResponse` is deprecated.
Use `StreamingHttpResponse`instead if you need the streaming behavior.
for data in self.result:
Traceback (most recent call last):
File "/usr/lib/python2.7/wsgiref/handlers.py", line 86, in run
self.finish_response()
File "/usr/lib/python2.7/wsgiref/handlers.py", line 126, in finish_response
for data in self.result:
File "/usr/local/lib/python2.7/dist-packages/django/utils/six.py", line 473, in next
return type(self).__next__(self)
File "/usr/local/lib/python2.7/dist-packages/django/http/response.py", line 292, in __next__
return self.make_bytes(next(self._iterator))
File "/usr/lib/python2.7/wsgiref/util.py", line 30, in next
data = self.filelike.read(self.blksize)
AttributeError: 'str' object has no attribute 'read'
Thanks in advance!
You're calling the read method in:
wrapper = fs.get(file_id).read()
So you're getting a str (assuming Python 2, if 3, you're getting bytes). FileWrapper needs file like object, which of course str is not one.
Try to use:
wrapper = fs.get(file_id)
This will return file like object.
OTOH, pymongo's .get() returns a GridOut instance, which already supports iteration, so why not try something like:
wrapper = fs.get(file_id)
response = StreamingHttpResponse(wrapper, content_type=file_['contentType'])