"str object is not callable" - python

I'm trying to make it so the api will lookup the item code that has been inputted by the user. Everytime I run this code it allows the user to input an item code but rather than process that code into the api it says:
"str object is not callable" with reference to line 14 which is result=api.item_lookup('')
The code below works when you remove api.item_lookup=raw_input() and manually put the item code in api.item_lookup, eg: result=api.item_lookup('B017WMMAVU').
from flask import Flask
from flask import render_template
from flask_bootstrap import Bootstrap
app = Flask("charity_third_page")
from amazonproduct import API
from lxml import etree
from lxml import objectify
api=API(locale='uk')
api.item_lookup = raw_input()
result=api.item_lookup('')
for item in result.Items.Item:
print '%s' % (item.ItemAttributes.Title)
item=api.item_lookup('', ResponseGroup='OfferSummary')
print str(item.Items.Item.OfferSummary.LowestNewPrice.getchildren()[0]/ 100.0)
Any help on how to get this to run would be much appreciated.

Because:
api.item_lookup = raw_input()
Is assigning a string (the result of raw_input) to api.item_lookup. Then you're trying to call it as a method. Maybe:
myStr = raw_input()
result = api.item_lookup(myStr)
instead.

You assigned the results of raw_input, a string, to api.item_lookup. A string is not callable, but on the next line you try to call the method api.item_lookup. Perhaps you meant to pass the input to the function, rather than overwriting it.
result = api.item_lookup(raw_input())

Related

Python: TypeError: 'int' object is not iterable - when iterating a dict

I am trying to get the list of local user my windows have.
I figured it out i can get the list in a form of a dictionary using win32net.NetUserEnum, however, since i just need the username, i'm trying to fetch that information from the dict and i've managed to do it already.
But i still have a problem, the script it's returning this message:
Administrator Traceback (most recent call last): Guest File
"D:/QUIZ/OCRLAB/orissupportaut.py", line 9, in DefaultAccount
for user in listausers[i]: userjohn TypeError: 'int' object is not iterable teste UtilityAccount
Anyway knows why this is happening?
Thanks
import win32api
import win32net
import win32netcon
listausers = win32net.NetUserEnum(None,2)
utilizadores= []
for i in range(len(listausers)):
for user in listausers[i]:
if type(user) == int:
pass
else:
print(user.get("name"))
Does this meet your requirements? Using isinstance instead of checking value of type. You're getting this error because NetUserEnum returns a list consisting of the users dict, and a few extra values (ints) as described here.
import win32api
import win32net
import win32netcon
listausers = win32net.NetUserEnum(None,2)
utilizadores= []
for i, users in enumerate(listausers):
if not isinstance(users, int):
for user in users:
if isinstance(user, int):
pass
else:
print(user.get("name"))
You could also just look at the dictionary itself by slicing the list.
for user in listausers[0]:
print(user.get("name"))
Building on CDJB's answer, I would compact everything to simply:
import win32api
import win32net
import win32netcon
listausers = win32net.NetUserEnum(None, 2)[0] # 0 to ignore the extra returned values.
utilizadores = [user.get("name") for user in listausers]

How to deal with globals in modules?

I try to make a non blocking api calls for OpenWeatherMap, but my problem is:
When i was doing tests on the file, and run it, the global api was taking effect, but when importing the function, global dont work anymore, and api dident change: api = ""?
Just after declaring the function i put global api, and then when I use print 'The API link is: ' + api I get the exact api, but global dident took effect!
Here is the code: https://github.com/abdelouahabb/tornadowm/blob/master/tornadowm.py#L62
What am I doing wrong?
When I import the file:
from tornadowm import *
forecast('daily', q='london', lang='fr')
The API link is: http://api.openweathermap.org/data/2.5/forecast/daily?lang=fr&q=london
api
Out[5]: ''
When executing the file instead of importing it:
runfile('C:/Python27/Lib/site-packages/tornadowm.py', wdir='C:/Python27/Lib/site-packages')
forecast('daily', q='london', lang='fr')
The API link is: http://api.openweathermap.org/data/2.5/forecast/daily?lang=fr&q=london
api
Out[8]: 'http://api.openweathermap.org/data/2.5/forecast/daily?lang=fr&q=london'
Edit: here is the code, if the Git got updated:
from tornado.httpclient import AsyncHTTPClient
import json
import xml.etree.ElementTree as ET
http_client = AsyncHTTPClient()
url = ''
response = ''
args = []
link = 'http://api.openweathermap.org/data/2.5/'
api = ''
result = {}
way = ''
def forecast(way, **kwargs):
global api
if way in ('weather', 'forecast', 'daily', 'find'):
if way == 'daily':
way = 'forecast/daily?'
else:
way += '?'
for i, j in kwargs.iteritems():
args.append('&{0}={1}'.format(i, j))
a = ''.join(set(args))
api = (link + way + a.replace(' ', '+')).replace('?&', '?')
print 'The API link is: ' + api
def handle_request(resp):
global response
if resp.error:
print "Error:", resp.error
else:
response = resp.body
http_client.fetch(api, handle_request)
else:
print "please put a way: 'weather', 'forecast', 'daily', 'find' "
def get_result():
global result
if response.startswith('{'):
print 'the result is JSON, stored in the variable result'
result = json.loads(response)
elif response.startswith('<'):
print 'the result is XML, parse the result variable to work on the nodes,'
print 'or, use response to see the raw result'
result = ET.fromstring(response)
else:
print '''Sorry, no valid response, or you used a parameter that is not compatible with the way!\n please check http://www.openweathermap.com/api for more informations''
It's the side effect of using global.
When you do from tornadowm import * your forecast() function is, we could say metaphorically, "on its own" and is not "hard-linked" to your global space anymore.
Why? Because any effect you make on your global api will "end" with your function, and the definition of api = "" in your global space will take precedence.
Also, as a side note, it's not considered a good practice to use from something import *. You should do from tornadowm import forecast or even better, import tornadown and then use tornadowm.forecast().
OR
Even better, I just noticed your forecast() function doesn't return anything. Which technically makes it not a function anymore, but a procedure (a procedure is like a function but it returns nothing, it just "does" stuff).
Instead of using a global, you should define api in this function and then return api from it. Like this:
def forecast(blablabla):
api = "something"
blablabla
return api
And then
import tornadowm
api = tornadown.forecast(something)
And you're done.
Globals are global only to the module they're defined in. So, normally, you would expect tornadowm.api to be changed when you call forecast, but not api in some other namespace.
The import * is contributing to your understanding of the problem. This imports api (among other names) into the importing namespace. This means that api and tornadowm.api initially point to the same object. But these two names are not linked in any way, and so calling forecast() changes only tornadowm.api and now the two names point to different objects.
To avoid this, don't use import *. It is bad practice anyway and this is just one of the reasons. Instead, import tornadowm and access the variable in the importing module as tornadowm.api.
I'm afraid this is because global is coupled within module, by the time you from tornadowm import * you have imported the api name, but the global api won't take any effects within another module.

Passing a variable to a JSON web service

I am accessing the class from the code api_service.py, which can be found here. When I call the first function, I have no problem, because no variables are passed:
from api_service import ApiService
import json
def main():
api_key = *removed*
access_token = *removed*
calling = ApiService(api_key,access_token)
survey_list = calling.get_survey_list()
But when I use the same type of routine as above to call a function from ApiService that requires a variable, I'm told that I should pass an object.
survey_details = calling.get_survey_details("1234")
survey_details = json.loads(json.dumps(survey_details))
print survey_details
The specific error message:
{u'status': 3, u'errmsg': u"Value '1234' for field '_data' is not of type object"}
Details for the get_survey_details aspect of the SurveyMonkey API are here, although I think a python-guru can solve this without knowing about the API.
This is a javascript/json object:
{field:'value'}
You have passed a string which, doesn't count as an "object" for these purposes.
Note that the error message is being generated by the service you are accessing. This question would be better directed to the creator of the service.

passing strftime() into Google app engine and jinja2

I have a Google App Engine Python script trying to pass the variable "time" as a strftime() call. I have jinja2 set up to read the html file with {{time}} in it as that variables destination
class MainPage(BlogHandler):
time = ''
def get_time(you):
return strftime('%U %A',gmtime())
def get(self):
time = self.get_time
self.render('front.html',time = time)
When I render/write out the whole thing into a simple div tag I get an object memory locator rendered in html
<bound method MainPage.get_time of <main.MainPage object at 0x1030f0610>>
obviously its not processing this out as a string. Am I using the wrong time function, is this a GAE issue? is this a Jinja2 issue? Is this a python issue? I'm clearly not sure how to follow up and resolve this. Thanks or any good critical advice.
All I want is to render a formattable time function to a string so i can use it in GAE scripts.
All you have to do is call the get_time() method:
time = self.get_time()
By not calling the method, all you do is store a reference to the method, and Jinja2 then takes the str() result of that method to include it in your template output:
>>> from time import strftime, gmtime
>>> class MainPage():
... def get_time(self):
... return strftime('%U %A',gmtime())
...
>>> mp = MainPage()
>>> mp.get_time
<bound method MainPage.get_time of <__main__.MainPage instance at 0x1031c7320>>
>>> mp.get_time()
'07 Saturday'

Why do I get TypeError: get() takes exactly 2 arguments (1 given)? Google App Engine

I have been trying and trying for several hours now and there must be an easy way to retreive the url. I thought this was the way:
#from data.models import Program
import basehandler
class ProgramViewHandler(basehandler.BaseHandler):
def get(self,slug):
# query = Program.all()
# query.filter('slug =', fslug)
self.render_template('../presentation/program.html',{})
Whenever this code gets executed I get this error on the stacktrace:
appengine\ext\webapp__init__.py", line 511, in call
handler.get(*groups)
TypeError: get() takes exactly 2 arguments (1 given)
I have done some debugging, but this kind of debugging exceeds my level of debugging. When I remove the slug from def get(self,slug) everything runs fine.
This is the basehandler:
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
class BaseHandler(webapp.RequestHandler):
def __init__(self,**kw):
webapp.RequestHandler.__init__(BaseHandler, **kw)
def render_template(self, template_file, data=None, **kw):
path = os.path.join(os.path.dirname(__file__), template_file)
self.response.out.write(template.render(path, data))
If somebody could point me in the right direction it would be great! Thank you! It's the first time for me to use stackoverflow to post a question, normally I only read it to fix the problems I have.
You are getting this error because ProgramViewHandler.get() is being called without the slug parameter.
Most likely, you need to fix the URL mappings in your main.py file. Your URL mapping should probably look something like this:
application = webapp.WSGIApplication([(r'/(.*)', ProgramViewHandler)])
The parenthesis indicate a regular expression grouping. These matched groups are passed to your handler as arguments. So in the above example, everything in the URL following the initial "/" will be passed to ProgramViewHandler.get()'s slug parameter.
Learn more about URL mappings in webapp here.
If you do this:
obj = MyClass()
obj.foo(3)
The foo method on MyClass is called with two arguments:
def foo(self, number)
The object on which it is called is passed as the first parameter.
Maybe you are calling get() statically (i.e. doing ProgramViewHandler.get() instead of myViewHandlerVariable.get()), or you are missing a parameter.

Categories

Resources