I'm a beginner in python. I'm not able to understand what the problem is?
the runtime process for the instance running on port 43421 has unexpectedly quit
ERROR 2019-12-24 17:29:10,258 base.py:209] Internal Server Error: /input/
Traceback (most recent call last):
File "/var/www/html/sym_math/google_appengine/lib/django-1.3/django/core/handlers/base.py", line 178, in get_response
response = middleware_method(request, response)
File "/var/www/html/sym_math/google_appengine/lib/django-1.3/django/middleware/common.py", line 94, in process_response
if response.status_code == 404:
AttributeError: 'tuple' object has no attribute 'status_code'
Whatever middleware_method returns is a tuple, so in the form ('a', 1, []) or something.
The error is telling you that you can't access members of the tuple by name, because they don't have names.
Maybe you created a tuple like this:
status_code = 404
name = 'Not found'
response = (name, status_code)
Once you declare the tuple, the names that went into it are lost. You have a couple of options for getting things out.
Direct access
You can get the objects by index, like you would with a list:
assert response[1] == 404
If you don't know what the tuple looks like, just print it, and calculate the index.
Named tuple
If you're determined to use names, you can create a namedtuple, provided that the tuple is going to be in the same format every time.
from collections import namedtuple
Response = namedtuple('Response', ('name', 'status_code')
response = Response('Not found', 404)
assert response.status_code == 404
Alternatively there may be a mistake in your code, where you are inadvertently returning a tuple, but one part of it is a requests.Response object. In that case, you can just extract the object as in "Direct access", and then use as you are already.
Would have to see the code to be of more help, but it might be something like:
response[2].status_code
I will try to explain how this error comes with a simple example
def example_error():
a1 = "I am here"
b1 = "you are there"
c1 = "This is error"
return a1, b1, c1
def call_function():
strings = example_error()
s1 = strings.a1
s2 = strings.b1
s3 = strings.c1
print(s1, s2, s3)
call_function()
This will return the error
AttributeError: 'tuple' object has no attribute 'a1'
Because I have returned three variables a1, b1, c1 in example_error function and trying to get them by using single variable strings.
I can get rid of this by using the following modified call_function
def call_function():
strings = example_error()
s1 = strings[0]
s2 = strings[1]
s3 = strings[2]
print(s1, s2, s3)
call_function()
As you did not show your code, I assume you have done something similar as here in the first case.
Related
Here is a function to check the data and update it
div , update are my mongodb collection object
def data_updater(user1_id,code):
device_id = dvi.find_one({"user_id":user1_id},{"_id":0,"user_id":0})["device_id"]
prv_data = update.find_one({"device_id":device_id},{"_id":0,"device_id":0})
prv_date = prv_data["date"]
msg = prv_data["message"]
if prv_date < current_date and msg != code:
x = update.find_one_and_update({"device_id":id,},{"$set":message":code,"date":current_date}})
print(x.acknowledged)
and when I am calling the function it is giving TypeError data_updater(95626,972681)
the error
Traceback (most recent call last):
File line 170, in <module>
data_updater(95626,972681)
File line 71, in data_updater
device_id = dvi.find_one({"user_id":int(user1_id)},{"_id":0,"user_id":0})["device_id"]
TypeError: 'NoneType' object is not subscriptable
I am not able to find any mistake please help
Your context isn't very clear, however, from the error trace as generated it seems that your find_one() function returns None with the arguments as passed and you are trying to access the value for the key device_id. I recommend you refactor your find_one() function or make use of the following code to resolve the issue at hand:
def data_updater(user1_id,code):
try:
device_id = dvi.find_one({"user_id":user1_id},{"_id":0,"user_id":0})["device_id"]
prv_data = update.find_one({"device_id":device_id},{"_id":0,"device_id":0})
prv_date = prv_data["date"]
msg = prv_data["message"]
if prv_date < current_date and msg != code:
x = update.find_one_and_update({"device_id":id,},{"message":code,"date":current_date}})
print(x.acknowledged)
except TypeError:
print('No value found for specified parameters :/')
PS: I also didn't understand the use of $ in your code, so I removed it thinking of it as a mistake. Hope this helps! 😊
when I test this view
#action(methods=['GET'], detail=True)
def nearby(self, request, pk=None):
"""get nearby energy resources to
the current energy resource in detail"""
energy_resource = self.get_object()
energy_resources = EnergyResource.objects.annotate(
distance=Distance('location', energy_resource.location)
).order_by('distance')[0:3]
serializer = self.get_serializer(energy_resources, many=True)
return Response(serializer.data)
with this test
def test_retrieve_nearby_energy_resources(self):
"""Test getting a list of three nearby energy resources"""
test_user2 = get_user_model().objects.create_user(
username='test2', password='test2password')
r = sample_resource(self.user, 5, 5)
sample_resource(test_user2, 4, 5)
sample_resource(test_user2, 5, 4)
sample_resource(test_user2, 5, 3)
r4 = sample_resource(test_user2, 25, 63)
url = reverse('energy-resource-nearby',
args=[r.id])
response = self.client.get(url)
resources_nearby = EnergyResource.objects.exclude(id=r4.id).order_by()
resource_not_nearby = EnergyResource.objects.get(id=r4.id)
serializer_nearby = EnergyResourceSerializer(
resources_nearby, many=True)
serializer_not_nearby = EnergyResourceSerializer(resource_not_nearby)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertContains(response.data, serializer_nearby.data)
self.assertNotContains(response.data, serializer_not_nearby)
it returns
ERROR: test_retrieve_nearby_energy_resources (energy_resources.tests.test_views.EnergyResourcePrivateAPITests)
Test getting a list of three nearby energy resources
----------------------------------------------------------------------
Traceback (most recent call last):
File "/workspace/energy_resources/tests/test_views.py", line 210, in test_retrieve_nearby_energy_resources
self.assertContains(response.data, serializer_nearby.data)
File "/root/.local/share/virtualenvs/workspace-dqq3IVyd/lib/python3.8/site-packages/django/test/testcases.py", line 445, in assertContains
text_repr, real_count, msg_prefix = self._assert_contains(
File "/root/.local/share/virtualenvs/workspace-dqq3IVyd/lib/python3.8/site-packages/django/test/testcases.py", line 416, in _assert_contains
response.status_code, status_code,
AttributeError: 'ReturnList' object has no attribute 'status_code'
----------------------------------------------------------------------
Ran 12 tests in 2.250s
it works in broswer and if I commented out assertContain and assertNotContain the test passes so it meants the response has status code attribute, right? what is different about assertContain and assertNotContain?
The error message misleading, but the stacktrace clearly shows the problem happens on the next line (so deleting it makes the test pass)
# this is not the function you are looking for
self.assertContains(response.data, serializer_nearby.data)
The problem is assertContains. It doesn't do what it sounds like at all, it actually checks some things releated to a django response:
def assertContains(self, response, text, count=None, status_code=200, msg_prefix='', html=False):
"""
Assert that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected) and that
``text`` occurs ``count`` times in the content of the response.
If ``count`` is None, the count doesn't matter - the assertion is true
if the text occurs at least once in the response.
"""
This method is so bad that my custom test base throwns an exception if anyone calls it, but I still accidentally do sometimes. In those cases I really wanted to call assertIn.
In your case it looks like you want to compare to dict instances for equality. TestCase has some methods like that, but be aware that they aren't perfect.
self.assertDictEqual({"a":1}, {"a":2})
# passes, all items in subset are in dictionary
self.assertDictContainsSubset(
subset={"a": 1},
dictionary={"z": 2, "a": 2}
)
I use if isinstance(ins,list): to check . but it returned false Although ins is the List[Object]
def getname(ins):
name=[]
if isinstance(ins,list):
for i in ins:
name.append(i.Name)
else:
name.append(ins.Name)
return name
Levels = FilteredElementCollector(doc).OfClass(Level).ToElements()
ULevels = UnwrapElement(Levels)
Levelsname = getname(ULevels)
Error message is:
AttributeError: 'List[object]' object has no attribute 'Name'
You can do it in a single line of code like this:
[UnwrapElement(x).Name for x in FilteredElementCollector(doc).OfClass(Level).ToElements()]
Since I can see you are using Dynamo you can also do it like this:
I was trying to analyse the play-by-play data of a basketball team
What I did was to read a csv file into a DataFrame object.
I want to preserve the functionality of the DataFrame object while adding in new attributes to the existing object. Thus I wrote a class called Basketball:
from data_math import *
import pandas as pd
class Basketball(pd.DataFrame):
def __init__(self,*args,**kargs):
pd.DataFrame.__init__(self,*args,**kargs)
self.FGM = calculate_FGM(pd.DataFrame)
self.FGA = calculate_FGA(pd.DateFrame)
self.FGP = self.FGM / self.FGA
self.M3 = calculate_3M(pd.DataFrame)
self.A3 = calcualte_3A(pd.DataFrame)
self.P3 = self.M3 / self.A3
self.FTM = calcualte_FTM(pd.DataFrame)
self.FTA = calculate_FTA(pd.DataFrame)
self.FTP = self.FTM / self.FTA
# self.P = score_calculate(pd.DataFrame)
I wrote another data_math.py file to help calculate the different attributes I wanted to include into the Basketball class.
from pandas import DataFrame
def score_calculate(df):
df_pt_scored = df[((df['etype']=='shot') & (df['result']=='made'))]
df_ft_scored = df[((df['etype']=='free throw') & (df['result']=='made'))]
return df_pt_scored['points'].sum()+len(df_ft_scored.index)
def calculate_FGM(df):
cond_pt = (df['etype']=='shots') & (df['results']=='made')
cond_ft = (df['etype']=='freethrow') & (df['results']=='made')
return len(df[cond_pt].index)+len(df[cond_ft].index)
def calculate_FGA(df):
shot_cond= df['etype']=='shot'
free_throw_cond = df['etype']=='free throw'
return len(df[shot_cond].index)+len(df[free_throw_cond].index)
def calculate_3M(df):
cond_3M= (df['etype']=='shot')&(df['type']=='3pt')&(df['result']=='made')
return len(df[cond_3M].index)
def calcualte_3A(df):
cond_3A = (df['etype']=='shot')&(df['type']=='3pt')
return len(df[cond_3A].index)
def calculate_FTM(df):
cond_FTM =(df['etype']=='free throw') & (df['result']=='made')
return len(df[cond_FTM].index)
def calcualte_FTA(df):
cond_FTA =(df['etype']=='free throw')
return len(df[cond_FTA].index)
In the end I start my program from main.py which I hope would give me the correct output. However while executing on this line:
team1= Basketball(tm1)
I received the following Traceback
Traceback (most recent call last):
File "/Users/luoyicheng/Developer/STAR-Research/data_analysis/source code/main.py", line 20, in <module>
team1= Basketball(tm1)
File "/Users/luoyicheng/Developer/STAR-Research/data_analysis/source code/Basketball.py", line 6, in __init__
self.FGM = calculate_FGM(pd.DataFrame)
File "/Users/luoyicheng/Developer/STAR-Research/data_analysis/source code/data_math.py", line 9, in calculate_FGM
cond_pt = (df['etype']=='shots') & (df['results']=='made')
TypeError: 'type' object has no attribute '__getitem__'
I am new to python programming and could not figure out why this error has occurred. To my understanding, this error means I am unable to use indexing feature of the DataFrame. However, if I try to code in my main function similar things I am able to get the output I want. I am also not clear of how to extend the existing DataFrame class so that I can still access the methods in the DataFrame class while extending the team1 object to have attributes such as FGM, FGA, etc.
The idea of extending this class is to allow me to pass any DataFrame object in the Basketball() so that I can have an object with extending attributes and methods. I think I also lack an understanding of the use of init and self.
Please don't blame for not describing the problem clearly as I am not familiar with all the terminology in OOP.
Thank you so much!
You're passing each function pd.DataFrame which is of type type:
In [11]: type(pd.DataFrame)
Out[11]: type
Hence the exception message.
You mean to be passing self (which is of type DataFrame):
self.FGM = calculate_FGM(pd.DataFrame)
...
should read:
self.FGM = calculate_FGM(self)
...
I'm trying to get results from a SOAP service called Chrome ADS (for vehicle data). They provided php and Java samples, but I need python (our site is in Django). My question is:
What should I be passing as a request to the SOAP service when using wsdl2py-generated classes?
Following the examples I'm using a DataVersionsRequest object as the request parameter, but the code generated by wsdl2py seems to want a getDataVersions object, and there's something like that defined at the bottom of the generated _client.py file. But that too seems to throw an error. So I'm not sure what I should be passing as the request obj. Any suggestions?
$sudo apt-get install python-zsi
$wsdl2py http://platform.chrome.com/***********
$python
>>> url = "http://platform.chrome.com/***********"
>>> from AutomotiveDescriptionService6_client import *
>>> from AutomotiveDescriptionService6_types import *
>>> locator = AutomotiveDescriptionService6Locator()
>>> service = locator.getAutomotiveDescriptionService6Port()
>>> locale = ns0.Locale_Def('locale')
>>> locale._country="US"
>>> locale._language="English"
>>> acctInfo = ns0.AccountInfo_Def('accountInfo')
>>> acctInfo._accountNumber=*****
>>> acctInfo._accountSecret="*****"
>>> acctInfo._locale = locale
>>> dataVersionsRequest = ns0.DataVersionsRequest_Dec()
>>> dataVersionsRequest._accountInfo = acctInfo
>>> service.getDataVersions(dataVersionsRequest)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "AutomotiveDescriptionService6_client.py", line 36, in getDataVersions
raise TypeError, "%s incorrect request type" % (request.__class__)
TypeError: <class 'AutomotiveDescriptionService6_types.DataVersionsRequest_Dec'> incorrect request type
>>> dataVersionsRequest = getDataVersions
>>> dataVersionsRequest._accountInfo = acctInfo
>>> service.getDataVersions(dataVersionsRequest)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "AutomotiveDescriptionService6_client.py", line 36, in getDataVersions
raise TypeError, "%s incorrect request type" % (request.__class__)
AttributeError: class DataVersionsRequest_Holder has no attribute '__class__'
>>> quit()
$cat AutomotiveDescriptionService6_client.py
.....
# Locator
class AutomotiveDescriptionService6Locator:
AutomotiveDescriptionService6Port_address = "http://platform.chrome.com:80/AutomotiveDescriptionService/AutomotiveDescriptionService6"
def getAutomotiveDescriptionService6PortAddress(self):
return AutomotiveDescriptionService6Locator.AutomotiveDescriptionService6Port_address
def getAutomotiveDescriptionService6Port(self, url=None, **kw):
return AutomotiveDescriptionService6BindingSOAP(url or AutomotiveDescriptionService6Locator.AutomotiveDescriptionService6Port_address, **kw)
# Methods
class AutomotiveDescriptionService6BindingSOAP:
def __init__(self, url, **kw):
kw.setdefault("readerclass", None)
kw.setdefault("writerclass", None)
# no resource properties
self.binding = client.Binding(url=url, **kw)
# no ws-addressing
# op: getDataVersions
def getDataVersions(self, request, **kw):
if isinstance(request, getDataVersions) is False:
raise TypeError, "%s incorrect request type" % (request.__class__)
# no input wsaction
self.binding.Send(None, None, request, soapaction="", **kw)
# no output wsaction
response = self.binding.Receive(getDataVersionsResponse.typecode)
return response
.....
getDataVersions = GED("urn:description6.kp.chrome.com", "DataVersionsRequest").pyclass
Also, as an aside, I'm not sure that the strings I'm passing to the pname parameter are correct, I assume that those are the ones I see inside the XML when I explore the service with SOAP UI, right?
It looks like you might be passing a class to service.getDataVersions() the second time instead of an instance (it can't be an instance if it doesn't have __class__).
What's happening is isinstance() returns false, and in the process of trying to raise a type error, an attribute error gets raised instead because it's trying to access __class__ which apparently doesn't exist.
What happens if you try:
>>> dataVersionsRequest = getDataVersions**()**
>>> dataVersionsRequest._accountInfo = acctInfo
>>> service.getDataVersions(dataVersionsRequest)
?
Based on the line:
if isinstance(request, getDataVersions) is False:
raise TypeError, "%s incorrect request type" % (request.__class__)
it definitely looks like you should be passing an instance of getDataVersions, so you're probably on the right track.
You probably need to be instantiating your definition objects and then populating them. Look for type == pyclass_type objects associated with the request you're wanting to make and instantiate them.
e.g. (just guessing)
>>> versionrequest = getDataVersions()
>>> versionrequest.AccountInfo = versionrequest.new_AccountInfo()
>>> versionrequest.AccountInfo.accountNumber = "123"
>>> versionrequest.AccountInfo.accountSecret = "shhhh!"
>>> service.getDataVersions(versionrequest)
I found that the code generated by wsdl2py was too slow for my purposes. Good luck.