AttributeError: 'search' object has no attribute 'status_code' in django project - python

I'm testing a django project using the test sever when it gives me the following exception
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.6/django/core/servers/basehttp.py", line 280, in run
self.result = application(self.environ, self.start_response)
File "/usr/lib/pymodules/python2.6/django/core/servers/basehttp.py", line 674, in >call
return self.application(environ, start_response)
File "/usr/lib/pymodules/python2.6/django/core/handlers/wsgi.py", line 245, in call
response = middleware_method(request, response)
File "/usr/lib/pymodules/python2.6/django/middleware/common.py", line 84, in >process_response
if response.status_code == 404:
AttributeError: 'search' object has no attribute 'status_code'
Just from reading this traceback, I don't think the problem is in my code, but I'm not sure. Could someone look through my code and help me solve this problem? my code is hosted on GitHub and any other comments or suggestions are greatly appreciated. Thanks in advance for your time and consideration.

MusicGrep/musicgrep/views.py is not returning a HttpResponse instance

There are quite a few problems with your code, but the one that's causing the actual error you quote is that you don't instantiate your FormWizard subclass in your urlconf.
As the documentation shows, you need to actually call the search class in urls.py to instantiate it, so you pass an instance rather than a class.
(r'^MusicGrep/$', 'MusicGrep.musicgrep.forms.search()'),
It might help if you followed the PEP8 guidelines on naming - if your class was called Search with a capital S, it would be more obvious that it was actually a class and not a function.

Related

AttributeError: 'str' object has no attribute 'errno'

I placed a ClientConnectionError exception in a multiprocessing.Queue that was generated by asyncio. I did this to pass an exception generated in asyncio land back to a client in another thread/process.
My assumption is that this exception occurred during the deserialization process reading the exception out of the queue. It looks pretty much impossible to reach otherwise.
Traceback (most recent call last):
File "model_neural_simplified.py", line 318, in <module>
main(**arg_parser())
File "model_neural_simplified.py", line 314, in main
globals()[command](**kwargs)
File "model_neural_simplified.py", line 304, in predict
next_neural_data, next_sample = reader.get_next_result()
File "/project_neural_mouse/src/asyncs3/s3reader.py", line 174, in get_next_result
result = future.result()
File "/usr/lib/python3.6/concurrent/futures/_base.py", line 432, in result
return self.__get_result()
File "/usr/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result
raise self._exception
File "/usr/lib/python3.6/concurrent/futures/thread.py", line 56, in run
result = self.fn(*self.args, **self.kwargs)
File "model_neural_simplified.py", line 245, in read_sample
f_bytes = s3f.read(read_size)
File "/project_neural_mouse/src/asyncs3/s3reader.py", line 374, in read
size, b = self._issue_request(S3Reader.READ, (self.url, size, self.position))
File "/project_neural_mouse/src/asyncs3/s3reader.py", line 389, in _issue_request
response = self.communication_channels[uuid].get()
File "/usr/lib/python3.6/multiprocessing/queues.py", line 113, in get
return _ForkingPickler.loads(res)
File "/usr/local/lib/python3.6/dist-packages/aiohttp/client_exceptions.py", line 133, in __init__
super().__init__(os_error.errno, os_error.strerror)
AttributeError: 'str' object has no attribute 'errno'
I figure it's a long shot to ask, but does anyone know anything about this issue?
Python 3.6.8, aiohttp.__version__ == 3.6.0
Update:
I managed to reproduce the issue (credit to Samuel in comments for improving the minimal reproducible test case, and later xtreak at bugs.python.org for furthing distilling it to a pickle-only test case):
import pickle
ose = OSError(1, 'unittest')
class SubOSError(OSError):
def __init__(self, foo, os_error):
super().__init__(os_error.errno, os_error.strerror)
cce = SubOSError(1, ose)
cce_pickled = pickle.dumps(cce)
pickle.loads(cce_pickled)
./python.exe ../backups/bpo38254.py
Traceback (most recent call last):
File "/Users/karthikeyansingaravelan/stuff/python/cpython/../backups/bpo38254.py", line 12, in <module>
pickle.loads(cce_pickled)
File "/Users/karthikeyansingaravelan/stuff/python/cpython/../backups/bpo38254.py", line 8, in __init__
super().__init__(os_error.errno, os_error.strerror)
AttributeError: 'str' object has no attribute 'errno'
References:
https://github.com/aio-libs/aiohttp/issues/4077
https://bugs.python.org/issue38254
OSError has a custom __reduce__ implementation; unfortunately, it's not subclass friendly for subclasses that don't match the expected arguments. You can see the intermediate state of the pickling by calling __reduce__ manually:
>>> SubOSError.__reduce__(cce)
(modulename.SubOSError, (1, 'unittest'))
The first element of the tuple is the callable to call, the second is the tuple of arguments to pass. So when it tries to recreate your class, it does:
modulename.SubOSError(1, 'unittest')
having lost the information about the OSError you were originally created with.
If you must accept arguments that don't match what OSError.__reduce__/OSError.__init__ expects, you're going to need to write your own __reduce__ override to ensure the correct information is pickled. A simple version might be:
class SubOSError(OSError):
def __init__(self, foo, os_error):
self.foo = foo # Must preserve information for pickling later
super().__init__(os_error.errno, os_error.strerror)
def __reduce__(self):
# Pickle as type plus tuple of args expected by type
return type(self), (self.foo, OSError(*self.args))
With that design, SubOSError.__reduce__(cce) would now return:
(modulename.SubOSError, (1, PermissionError(1, 'unittest')))
where the second element of the tuple is the correct arguments needed to recreate the instance (the change from OSError to PermissionError is expected; OSError actually returns its own subclasses based on the errno).
This issue was fixed and merged to master in aiohttp on 25 Sep 2019. I'll update this answer in the future if I note a version that the fix goes into (feel free to edit this answer in the future to note a version containing this update).
Git issue with the fix:
https://github.com/aio-libs/aiohttp/issues/4077

Tweepy issues with twitter bot and python

I have a few twitterbots that I run on my raspberryPi. I have most functions wrapped in a try / except to ensure that if something errors it doesn't break the program and continues to execute.
I'm also using Python's Streaming library as my source of monitoring for the tags that I want the bot to retweet.
Here is an issue that happens that kills the program although I have the main function wrapped in a try/except:
Unhandled exception in thread started by <function startBot5 at 0x762fbed0>
Traceback (most recent call last):
File "TwitButter.py", line 151, in startBot5
'<botnamehere>'
File "/home/pi/twitter/bots/TwitBot.py", line 49, in __init__
self.startFiltering(trackList)
File "/home/pi/twitter/bots/TwitBot.py", line 54, in startFiltering
self.myStream.filter(track=tList)
File "/usr/local/lib/python3.4/dist-packages/tweepy/streaming.py", line 445, in filter
self._start(async)
File "/usr/local/lib/python3.4/dist-packages/tweepy/streaming.py", line 361, in _start
self._run()
File "/usr/local/lib/python3.4/dist-packages/tweepy/streaming.py", line 294, in _run
raise exception
File "/usr/local/lib/python3.4/dist-packages/tweepy/streaming.py", line 263, in _run
self._read_loop(resp)
File "/usr/local/lib/python3.4/dist-packages/tweepy/streaming.py", line 313, in _read_loop
line = buf.read_line().strip()
AttributeError: 'NoneType' object has no attribute 'strip'
My setup:
I have a parent class TwitButter.py, that creates an object from the TwitBot.py. These objects are the bots, and they are started on their own thread so they can run independently.
I have a function in the TwitBot that runs the startFiltering() function. It is wrapped in a try/except, but my except code is never triggered.
My guess is that the error is occurring within the Streaming library. Maybe that library is poorly coded and breaks on the line that is specified at the bottom of the traceback.
Any help would be awesome, and I wonder if others have experienced this issue?
I can provide extra details if needed.
Thanks!!!
This actually is problem in tweepy that was fixed by github #870 in 2017-04. So, should be resolved by updating your local copy to latest master.
What I did to discover that:
Did a web search to find the tweepy source repo.
Looked at streaming.py for context on the last traceback lines.
Noticed the most recent change to the file was the same problem.
I'll also note that most of the time you get a traceback from deep inside a Python library, the problem comes from the code calling it incorrectly, rather than a bug in the library. But not always. :)

Attribute Error when using Specialized JSON-oriented Flask App Example

I'm trying to get all errors returned as JSON for my webservice. I found the following snippet: http://flask.pocoo.org/snippets/83/ which described a way to implement this. When I attempted to use it I get the following stack trace
127.0.0.1 - - [30/Oct/2016 00:27:57] "GET /401 HTTP/1.1" 500 -
Traceback (most recent call last):
File "/opt/thermostat/python/venv/lib/python2.7/site-packages/flask/app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "/opt/thermostat/python/venv/lib/python2.7/site-packages/flask/app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/opt/thermostat/python/venv/lib/python2.7/site-packages/flask/app.py", line 1559, in handle_exception
handler = self._find_error_handler(InternalServerError())
File "/opt/thermostat/python/venv/lib/python2.7/site-packages/flask/app.py", line 1476, in _find_error_handler
.get(code))
File "/opt/thermostat/python/venv/lib/python2.7/site-packages/flask/app.py", line 1465, in find_handler
handler = handler_map.get(cls)
AttributeError: 'function' object has no attribute 'get'
Source code using this sample app: https://github.com/domenicosolazzo/flask_examples/blob/master/json-oriented-app_example.py. Disclaimer: this is not my code but the sample I pulled from but I get the same error.
I need all errors to come back as JSON rather than the HTML the Flask defaults to. Is there a better way to do what I want?
I just ran the same issue as you did, find out that new version of Flask introduced the problem. Found this workaround from this commit, just replace the following error handler assignment :
app.error_handler_spec[None][error_code] = function
by
app.register_error_handler(error_code, function)
In flask/app.py you can find:
.. versionadded:: 0.7
Use :meth:`register_error_handler` instead of modifying
:attr:`error_handler_spec` directly, for application wide error
handlers.
So if you want to jsonify flask app errors:
for code in default_exceptions.iterkeys():
# don't modyfy the dictionary directly
# app.error_handler_spec[None][code] = make_json_error
# use method
app.register_error_handler(code, make_json_error)

AttributeError: 'NoneType' object has no attribute '_default_manager' when running lettuce with django rest framework

I am trying to use lettuce to implement BDD for creating an rest framework api but when I execute the command python manage.py harvest I get following error
/rest_framework/serializers.py", line 818, in get_related_field
'queryset': related_model._default_manager,
AttributeError: 'NoneType' object has no attribute '_default_manager'
Detailed stack trace is:
(envSamplePayApp)root#ubuntu:/pythonWorkspace/samplePayProject# python manage.py harvest
Django's builtin server is running at 0.0.0.0:8000
Traceback (most recent call last):
File "/pythonWorkspace/samplePayProject/envSamplePayApp/local/lib/python2.7/site-packages/lettuce/django/management/commands/harvest.py", line 167, in handle
result = runner.run()
File "/pythonWorkspace/samplePayProject/envSamplePayApp/local/lib/python2.7/site-packages/lettuce/__init__.py", line 137, in run
self.loader.find_and_load_step_definitions()
File "/pythonWorkspace/samplePayProject/envSamplePayApp/local/lib/python2.7/site-packages/lettuce/fs.py", line 49, in find_and_load_step_definitions
module = __import__(to_load)
File "/pythonWorkspace/samplePayProject/envSamplePayApp/local/lib/python2.7/site-packages/rest_framework/tests/test_serializer_import.py", line 4, in <module>
from rest_framework.tests.accounts.serializers import AccountSerializer
File "/pythonWorkspace/samplePayProject/envSamplePayApp/local/lib/python2.7/site-packages/rest_framework/tests/accounts/serializers.py", line 6, in <module>
class AccountSerializer(serializers.ModelSerializer):
File "/pythonWorkspace/samplePayProject/envSamplePayApp/local/lib/python2.7/site-packages/rest_framework/tests/accounts/serializers.py", line 8, in AccountSerializer
admins = UserSerializer(many=True)
File "/pythonWorkspace/samplePayProject/envSamplePayApp/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 196, in __init__
self.fields = self.get_fields()
File "/pythonWorkspace/samplePayProject/envSamplePayApp/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 232, in get_fields
default_fields = self.get_default_fields()
File "/pythonWorkspace/samplePayProject/envSamplePayApp/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 716, in get_default_fields
field = self.get_related_field(model_field, related_model, to_many)
File "/pythonWorkspace/samplePayProject/envSamplePayApp/local/lib/python2.7/site-packages
All the code can be found at downloadcode.
Note when I run the api from browser it works fine.
What is causing the AttributeError: 'NoneType' object has no attribute '_default_manager'?
I ran into this error just now. The cause of my error was due to the fact that I had created a ManyToManyField from Model X of App A to Model Y of App B. When I tried to create schema migration via python manage.py schemamigration --auto app_a, it raised this error because I had yet to:
include 'app_b' in the INSTALLED_APPS tuple of settings.py
not having created the initial schema migration for app_b (which would not be possible with adding app_b to INSTALLED_APPS).
Effectively, I linked to an model that was not known at the time. Hopefully this can help someone in the future.
EDIT: Actually, on further inspection, I realize now the reason that this error is being raised so ambiguously is because of django-debug-toolbar. Apparently DjangoDebugToolbar is causing some issues around errors propagating properly. Disabling it in INSTALLED_APPS allowed the errors to become apparent.

__name__ attribute in Python for Win32_ComputerSystem?

I'm trying to get the name of a WMI win32 class. But the __name__ attribute is not defined for it.
>> import wmi
>> machine = wmi.WMI()
>> machine.Win32_ComputerSystem.__name__
I get the following error:
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
machine.Win32_ComputerSystem.__name__
File "C:\Python27\lib\site-packages\wmi.py", line 796, in __getattr__
return _wmi_object.__getattr__ (self, attribute)
File "C:\Python27\lib\site-packages\wmi.py", line 561, in __getattr__
return getattr (self.ole_object, attribute)
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 457, in __getattr__
raise AttributeError(attr)
AttributeError: __name__
I thought that the __name__ attribute is defined for all Python functions, so I don't know what the problem is here. How is it possible that this function doesn't have that attribute?
OK, The reason that I thought it was a method is because machine.Win32_ComputerSystem() is defined, but I guess that isn't enough for something to be a method. I realise that it isn't a method.
However, this doesn't work:
>> machine.Win32_ComputerSystem.__class__.__name__
'_wmi_class'
I want it to return 'Win32_ComputerSystem'. How can I do this?
From what I can tell looking at the documentation (specifically, based on this snippet), wmi.Win32_ComputerSystem is a class, not a method. If you want to get its name you could try:
machine.Win32_ComputerSystem.__class__.__name__
I've found a way to get the output that I want, however it doesn't satisfy me.
repr(machine.Win32_ComputerSystem).split(':')[-1][:-1]
returns: 'Win32_ComputerSystem'
There must be a more Pythonic way to do this.

Categories

Resources