TypeError: in Python - python

I have an issue, where a function returns a number. When I then try to assemble a URL that includes that number I am met with failure.
Specifically the error I get is
TypeError: cannot concatenate 'str' and 'NoneType' objects
Not sure where to go from here.
Here is the relevant piece of code:
# Get the raw ID number of the current configuration
configurationID = generate_configurationID()
# Update config name at in Cloud
updateConfigLog = open(logBase+'change_config_name_log.xml', 'w')
# Redirect stdout to file
sys.stdout = updateConfigLog
rest.rest(('put', baseURL+'configurations/'+configurationID+'?name=this_is_a_test_', user, token))
sys.stdout = sys.__stdout__
It works perfectly if I manually type the following into rest.rest()
rest.rest(('put', http://myurl.com/configurations/123456?name=this_is_a_test_, myusername, mypassword))
I have tried str(configurationID) and it spits back a number, but I no longer get the rest of the URL...
Ideas? Help?
OK... In an attempt to show my baseURL and my configurationID here is what I did.
print 'baseURL: '+baseURL
print 'configurationID: '+configurationID
and here is what I got back
it-tone:trunk USER$ ./skynet.py fresh
baseURL: https://myurl.com/
369596
Traceback (most recent call last):
File "./skynet.py", line 173, in <module>
main()
File "./skynet.py", line 30, in main
fresh()
File "./skynet.py", line 162, in fresh
updateConfiguration()
File "./skynet.py", line 78, in updateConfiguration
print 'configurationID: '+configurationID
TypeError: cannot concatenate 'str' and 'NoneType' objects
it-tone:trunk USER$
What is interesting to me is that the 369596 is the config ID, but like before it seems to clobber everything called up around it.
As kindall pointed out below, my generate_configurationID was not returning the value, but rather it was printing it.
# from generate_configurationID
def generate_configurationID():
dom = parse(logBase+'provision_template_log.xml')
name = dom.getElementsByTagName('id')
p = name[0].firstChild.nodeValue
print p
return p

Your configurationID is None. This likely means that generate_configurationID() is not returning a value. There is no way in Python for a variable name to "lose" its value. The only way, in the code you posted, for configurationID to be None is for generate_configurationID() to return None which is what will happen if you don't explicitly return any value.
"But it prints the configurationID right on the screen!" you may object. Sure, but that's probably in generate_configurationID() where you are printing it to make sure it's right but forgetting to return it.
You may prove me wrong by posting generate_configurationID() in its entirety, and I will admit that your program is magic.

Related

Trying to e.164 a phone number from form input

I'm trying to take a UK mobile phone number input from a web form and use Python to clean it into a E.164 format, then validate it, before entering it into a database.
The library I'm trying to use is "Phonenumbers" and the code I'm experimenting with so far is:
def Phone():
my_number = '+4407808765066'
clean_phone = phonenumbers.parse(my_number, "GB")
cleaner_phone = phonenumbers.format_number(clean_phone,
phonenumbers.PhoneNumberFormat.E164)
valid = phonenumbers.is_possible_number(cleaner_phone)
print(cleaner_phone)
Just working through the logic, my expectation is that it should take the contents of my_number variable, format it through into the clean_phone variable, then format it to E.164 standard before passing it to the validation and return the output to valid. The print statement is for me to see the output.
Everything looks to work ok if I comment out the valid variable line. As soon as I uncomment it, I get an error (see below).
Traceback (most recent call last):
File "phone_test.py", line 14, in <module>
Phone()
File "phone_test.py", line 10, in Phone
valid = phonenumbers.is_possible_number(cleaner_phone)
File "D:\Dropbox\Coding Projects\learner_driver_app\env\lib\site-packages\phonenumbers\phonenumberutil.py", line 2257, in is_possible_number
result = is_possible_number_with_reason(numobj)
File "D:\Dropbox\Coding Projects\learner_driver_app\env\lib\site-packages\phonenumbers\phonenumberutil.py", line 2358, in is_possible_number_with_reason
return is_possible_number_for_type_with_reason(numobj, PhoneNumberType.UNKNOWN)
File "D:\Dropbox\Coding Projects\learner_driver_app\env\lib\site-packages\phonenumbers\phonenumberutil.py", line 2393, in is_possible_number_for_type_with_reason
national_number = national_significant_number(numobj)
File "D:\Dropbox\Coding Projects\learner_driver_app\env\lib\site-packages\phonenumbers\phonenumberutil.py", line 1628, in national_significant_number
if numobj.italian_leading_zero:
AttributeError: 'str' object has no attribute 'italian_leading_zero'
Where am I going wrong?
Your my_number is a variable of type str (string), thus the last line of your error). The string class does not know the attribute national_number.
Reading through their examples on GitHub, I suspect you need to pass your string through the parse() function first before you can use functions from the library.
def Phone():
my_number = '+4407811111111'
number_prased = phonenumbers.parse(my_number, None) # this is new
clean_phone = phonenumbers.format_number(number_parsed,
phonenumbers.PhoneNumberFormat.E164)
return clean_phone
The None in parse() may be replaced by a country code if it is known. Otherwise, it will try to figure it out but may fail.
Edit to account for more information in the original question:
Apparently phonenumbers.format_number() returns a string, therefore you have to re-parse the number again to get an object of type phonenumbers.phonenumber.PhoneNumber (you can check the type of objects with type(my_object)). After that, your code will return True.
You can't use the format_number function with a string as argument, it expects a PhoneNumber object.
You can get one by using the parse function.
See https://github.com/daviddrysdale/python-phonenumbers/tree/dev/python#example-usage

Don't understand this ConfigParser.InterpolationSyntaxError

So I have tried to write a small config file for my script, which should specify an IP address, a port and a URL which should be created via interpolation using the former two variables. My config.ini looks like this:
[Client]
recv_url : http://%(recv_host):%(recv_port)/rpm_list/api/
recv_host = 172.28.128.5
recv_port = 5000
column_list = Name,Version,Build_Date,Host,Release,Architecture,Install_Date,Group,Size,License,Signature,Source_RPM,Build_Host,Relocations,Packager,Vendor,URL,Summary
In my script I parse this config file as follows:
config = SafeConfigParser()
config.read('config.ini')
column_list = config.get('Client', 'column_list').split(',')
URL = config.get('Client', 'recv_url')
If I run my script, this results in:
Traceback (most recent call last):
File "server_side_agent.py", line 56, in <module>
URL = config.get('Client', 'recv_url')
File "/usr/lib64/python2.7/ConfigParser.py", line 623, in get
return self._interpolate(section, option, value, d)
File "/usr/lib64/python2.7/ConfigParser.py", line 691, in _interpolate
self._interpolate_some(option, L, rawval, section, vars, 1)
File "/usr/lib64/python2.7/ConfigParser.py", line 716, in _interpolate_some
"bad interpolation variable reference %r" % rest)
ConfigParser.InterpolationSyntaxError: bad interpolation variable reference '%(recv_host):%(recv_port)/rpm_list/api/'
I have tried debugging, which resulted in giving me one more line of error code:
...
ConfigParser.InterpolationSyntaxError: bad interpolation variable reference '%(recv_host):%(recv_port)/rpm_list/api/'
Exception AttributeError: "'NoneType' object has no attribute 'path'" in <function _remove at 0x7fc4d32c46e0> ignored
Here I am stuck. I don't know where this _remove function is supposed to be... I tried searching for what the message is supposed to tell me, but quite frankly I have no idea. So...
Is there something wrong with my code?
What does '< function _remove at ... >' mean?
There was indeed a mistake in my config.ini file. I did not regard the s at the end of %(...)s as a necessary syntax element. I suppose it refers to "string" but I couldn't really confirm this.
My .ini file for starting the Python Pyramid server had a similar problem.
And to use the variable from the .env file, I needed to add the following: %%(VARIEBLE_FOR_EXAMPLE)s
But I got other problems, and I solved them with this: How can I use a system environment variable inside a pyramid ini file?

Feedparser Python Error : KeyError : 'title'

I have seen a lot of KeyCount Errors online but none of them quite match the troubles that I'm having. I am using feed parser to try and create a one run application that accesses all the URLs in a text file and outputs all the entries in each URL. When I run this code :
import feedparser as f
with open('addresses.rtf', 'r') as addresses:
for line in addresses:
d = f.parse(line)
print d["feed"]["title"]
print ""
print d.feed.subtitle
print ""
for post in d.entries:
print post.title
print post.link
print ""
I get this error message :
Traceback (most recent call last):
File "/Users/Josh/Desktop/Feed Parser Python Project/init.py", line 7, in <module>
print d["feed"]["title"]
File "build/bdist.macosx-10.6-intel/egg/feedparser.py", line 375, in __getitem__
return dict.__getitem__(self, key)
KeyError: 'title'
My text file is just a .rtf file that has a URL on each line (3 lines).
If someone could give us a hand please let me know and if you need any extra info please don't hesitate to ask. Any help is welcome. Thank you!
It's hard to tell exactly what is wrong here, but in the general case, any KeyError is because the data you are trying to access is not exactly what you expected. It's best to throw your assumptions out the window and take a close look at the actual data that your code is working with.
For debugging, I would recommend taking a close look at what happens before the error. What is the value of line as you read the file? Is it correct? What is the value of d? Did the call to f.parse(line) result in a valid object?

python: 'str' object is not callable?

I have gone through many similar posts here and there but non of them seem solve my problem. I have a method that searches for file path:
def getDumpFile(self):
self.saveDump()
dumpname = str(self.filename)+'-01.netxml'
filepath = os.path.join('/some/path/to/file',dumpname)
try:
if os.path.exists(os.path.join('/some/path/to/file',dumpname)):
logging.debug( "Filepath "+str(filepath) )
return filepath
else:
logging.debug( "File Not Found" )
return None
except OSError as e:
logging.debug( "File not created: "+str(e) )
return None
and in the main function I call this function like this:
xmlfile = wscanner.getDumpFile()
and when I execute above code, it finds the correct path in getDumpFile() method but the server gives out exception:
Unexpected exception in wireless.views.attackAP with type <type 'exceptions.TypeError'> and error 'str' object is not callable
I really don't know why passing the filepath to xmlfile variable(which I believe is never initiated before)could cause error,please help. Thanks.
Edit: It is actually the code xmlfile = wscanner.getDumpFile() that gives out error, but I don't know why. Comment out this line would get rid of the error, but I need this path later on.
This is why I enjoy StackOverflow -- it causes you to really plunge deeper.
The last poster is 100% correct. I wrote a quick class to demo the problem. If I had to go on what we know from the poster, I'd suggest to take a closer look at references to getDumpFile, to ensure someone is not accidentally assigning a string value to it:
class MyClass:
def getDumpFile(self):
pass
myclass = MyClass()
myclass.getDumpFile = 'hello world'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
There's a bit of 'non-pythonic' stuff going on in this module. But let's ignore that for a moment.
You're saying the error message comes from calling method:
xmlfile = wscanner.getDumpFile()
If I had to guess, I'd say 'wscanner' is not defined how you think it is -- and specifically, the python interpreter thinks it's a string.
Try adding this call right before the call to getDumpFile()
print type(wscanner)
See what it shows.

AppEngine -> "AttributeError: 'unicode' object has no attribute 'has_key'" when using blobstore

There have been a number of other questions on AttributeErrors here, but I've read through them and am still not sure what's causing the type mismatch in my specific case.
Thanks in advance for any thoughts on this.
My model:
class Object(db.Model):
notes = db.StringProperty(multiline=False)
other_item = db.ReferenceProperty(Other)
time = db.DateTimeProperty(auto_now_add=True)
new_files = blobstore.BlobReferenceProperty(required=True)
email = db.EmailProperty()
is_purple = db.BooleanProperty()
My BlobstoreUploadHandler:
class FormUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
try:
note = self.request.get('notes')
email_addr = self.request.get('email')
o = self.request.get('other')
upload_file = self.get_uploads()[0]
# Save the object record
new_object = Object(notes=note,
other=o,
email=email_addr,
is_purple=False,
new_files=upload_file.key())
db.put(new_object)
# Redirect to let user know everything's peachy.
self.redirect('/upload_success.html')
except:
self.redirect('/upload_failure.html')
And every time I submit the form that uploads the file, it throws the following exception:
ERROR 2010-10-30 21:31:01,045 __init__.py:391] 'unicode' object has no attribute 'has_key'
Traceback (most recent call last):
File "/home/user/Public/dir/google_appengine/google/appengine/ext/webapp/__init__.py", line 513, in __call__
handler.post(*groups)
File "/home/user/Public/dir/myapp/myapp.py", line 187, in post
new_files=upload_file.key())
File "/home/user/Public/dir/google_appengine/google/appengine/ext/db/__init__.py", line 813, in __init__
prop.__set__(self, value)
File "/home/user/Public/dir/google_appengine/google/appengine/ext/db/__init__.py", line 3216, in __set__
value = self.validate(value)
File "/home/user/Public/dir/google_appengine/google/appengine/ext/db/__init__.py", line 3246, in validate
if value is not None and not value.has_key():
AttributeError: 'unicode' object has no attribute 'has_key'
What perplexes me most is that this code is nearly straight out of the documentation, and jives with other examples of blob upload handler's I've found online in tutorials as well.
I've run --clear-datastore to ensure that any changes I've made to the DB schema aren't causing problems, and have tried casting upload_file as all sorts of things to see if it would appease Python - any ideas on what I've screwed up?
Edit: I've found a workaround, but it's suboptimal.
Altering the UploadHandler to this instead resolves the issue:
...
# Save the object record
new_object = Object()
new_object.notes = note
new_object.other = o
new_object.email = email.addr
new_object.is_purple = False
new_object.new_files = upload_file.key()
db.put(new_object)
...
I made this switch after noticing that commenting out the files line threw the same issues for the other line, and so on. This isn't an optimal solution, though, as I can't enforce validation this way (in the model, if I set anything as required, I can't declare an empty entity like above without throwing an exception).
Any thoughts on why I can't declare the entity and populate it at the same time?
You're passing in o as the value of other_item (in your sample code, you call it other, but I presume that's a typo). o is a string fetched from the request, though, and the model definition specifies that it's a ReferenceProperty, so it should either be an instance of the Other class, or a db.Key object.
If o is supposed to be a stringified key, pass in db.Key(o) instead, to deserialize it.
Object is a really terrible name for a datastore class (or any class, really), by the way - the Python base object is called object, and that's only one capitalized letter away - very easy to mistake.
has_key error is due to the ReferenceProperty other_items. You are most likely passing in '' for other_items when appengine's api expects a dict. In order to get around this, you need to convert other_items to hash.
[caveat lector: I know zilch about "google_app_engine"]
The message indicates that it is expecting a dict (the only known object that has a has_key attribute) or a work-alike object, not the unicode object that you supplied. Perhaps you should be passing upload_file, not upload_file.key() ...

Categories