'module' object is not subscriptable - python

here is very simplified version of my code , so pleas ignore syntax errors
i have a helper function basically reading a row from database using django orm and doing some validation finally return it using a dictionary
modVerify.py
def verify(request):
try :
req = Request.objects.get(id=request.POST.get('id'))
except :
return({'stat':'er' , 'error':-12})
return({'stat':'ok' , 'req':req})
here is where i get the error when im trying to use this above app
import modVerify.view
def verify(request):
result = modVerify.views.verify(request )
if(result['status'] == 'ok'):
req = modeVerify['req']
else :
print('ERROR !')
here is my error
TypeError at /api/verify
'module' object is not subscriptable
Request Method: POST
Request URL: site.com/api/verify
Django Version: 1.9.7
Exception Type: TypeError
Exception Value:
'module' object is not subscriptable
Exception Location: /home/somedomain/project/api/views.py in verify, line 98
Python Executable: /usr/local/bin/python3
Python Version: 3.4.4
which points to this line
req = modeVerify['req']
so why im getting this and is there a way around it or should i return row id back instead and read it again from database in the caller function ?

It seems like you should be doing
req = result['req']
instead of
req = modeVerify['req']

Related

Python - Error in authorized client request

Create an "authorized_token" Token object and use that to perform Twitter API calls on behalf of user
authorized_token = oauth2.Token(access_token['oauth_token'], access_token['oauth_token_secret'])
authorized_client = oauth2.Client(consumer, authorized_token)
Make Twitter API calls!
response, content = authorized_client.request('https://api.twitter.com/1.1/search/tweets.json?q=computers+filter:images', 'GET')
if response.status != 200:
print("An error occurred when searching!")
print(content.decode('utf-8'))
Error -
Exception has occurred: AttributeError 'list' object has no attribute
'encode'
The error indicates the following code
response, content = authorized_client.request('https://api.twitter.com/1.1/search/tweets.json?q=computers+filter:images', 'GET')
Someone can explain to me why?

python json.loads() works but requests.json does not work, on an odata endpoint that produces 32MB of json

Have been happily using requests.json interchangably with json.loads().... but today I was using an odata endpoint that returns ~ 32MB of json... json.loads() worked fine but when I tried requests.json it raised an error. So there must be differences between the two? Any insights on what these might be... Using python 3.6, requests 2.18.4
# get json from odata endpoint and check for top-level "value" element...
try:
http_response = requests.get( url )
except Exception as errmsg:
sys.exit( "Error on http request ... Msg: " + str(errmsg) )
try:
# jsondata = json.loads( http_response.text ) # works fine
jsondata = http_response.json # doesn't work
except Exception as errmsg:
sys.exit( "Error on json conversion: " + str(errmsg) )
try:
rowset = jsondata["value"]
except Exception as errmsg:
sys.exit( "ERROR .... can't find 'value'. Msg: " + str(errmsg) )
The odata endpoint I need to call returns json that is lengthy (32,113,432 chars) and begins like this:
{"#odata.context":"http://xxx.yyy.org/JAXLIMS/Odata /$metadata#MPDInputs","#odata.count":27775,"value":[{"C_InputInstance_key":19203327,"InputValue":"129","InputName":"Experimenter", ....etc....
The error raised when I use requests.json is:
ERROR .... can't find 'value'. Msg: 'method' object is not subscriptable

Callback from External OAUTH in Django

Alrighty. Setup information - Django 1.8.3, Python 2.7.3, using Goodreads 0.2.4 api handler for Python (slightly modified). I'm at the point where Goodreads does a callback to the app, but the clickjacker middleware is catching it as an error and tossing out a 404. If I disable the clickjacker prevention (which I'd prefer not to do), I get an "argument of type 'type' is not iterable" error.
Relevant Code:
from goodreads import client
grClient = client.GoodreadsClient(<key>,<other_key>)
def goodReadsOAUTH_stage1(request,user):
try:
return HttpResponseRedirect(grClient.authenticate())
# function modified to return the URL rather than open a browser
except keyError:
return Http404
def goodReadsOAUTH_stage2(request):
if request.method == "GET":
if request.GET['authorize'] == 1:
grRecord = goodreadsOAUTHKeys(request.user,request.GET['oauth_token']
grRecord.save()
grClient.session.oauth_finalize()
return HttpResponseRedirect(reverse(request,'workroom:profile',kwargs={'user':request.user.username}))
else:
return Http404
else:
return Http404
And the URLconf for the two:
url(r'^social/(?P<user>[-\w\d]+)/goodreads/OAUTH/$', views.goodReadsOAUTH_stage1, name='goodreads-oauth-one'),
url(r'^social/goodreads/OAUTH/validation/$', views.goodReadsOAUTH_stage2, name='goodreads-oauth-two'),
And the ensuing error message!
type object 'Http404' has no attribute 'get'
Exception Location: /home/.../public/env/local/lib/python2.7/site-packages/django/middleware/clickjacking.py in process_response, line 31
And that line of code from the clickjacking protection:
if response.get('X-Frame-Options', None) is not None:
I'm essentially at a loss here as to how to get the callback to function correctly.
You are using Http404 wrong. Http404 is an Exception, use it like
raise Http404("Poll does not exist")
For the reference see section "Returning Errors"

DJANGO upgrade error: is not JSON serializable

This was my code in django 1.6 ( working good)
I upgraded to django 1.7.
First simplejson is depracated : i changed simplejson to json,But i receive the same error always
is not json serializable.
Any ideas ?
Views:
def request_to_json(request):
post_data = request.body
json_data = simplejson.loads(post_data)
return json_data
def receiver(request):
try:
json_data = request_to_json(request)
user_id=json_data['user_id'];
site_id=json_data['site_id'];
# A variable to return to the app
response = 'Ok'
except:
response = sys.exc_info()[0]
return HttpResponse(simplejson.dumps(response))
Error
TypeError at /views/receiver/
<class 'TypeError'> is not JSON serializable
Request Method: POST
Request URL: http://localhost:8000/views/receiver/
Django Version: 1.7
Exception Type: TypeError
Exception Value:
<class 'TypeError'> is not JSON serializable
Exception Location: C:\Python34\lib\json\encoder.py in default, line 173
Python Executable: C:\Python34\python.EXE
Python Version: 3.4.1
Python Path:
['C:\\workspace-eclipse\\IndoorPositioning',
'C:\\Python34\\lib\\site-packages\\setuptools-5.4.2-py3.4.egg',
'C:\\Windows\\system32\\python34.zip',
'C:\\Python34\\DLLs',
'C:\\Python34\\lib',
'C:\\Python34',
'C:\\Python34\\lib\\site-packages']
Server time: Sat, 13 Sep 2014 12:18:36 +0200
Your exception handler is raising an exception. You are trying to serialise the entire exception object to json to return to the user. Instead get a string representation of the exception and return that:
def receiver(request):
try:
...
except:
response = "%s" % sys.exc_info()[0]
return HttpResponse(simplejson.dumps(response))
(It's not a great idea to be directly returning internal exception messages, you should probably try and specifically catch the exception and return a user-friendly message instead of the actual exception)
If you want to see why you are getting an exception in your code, you need to allow the exception to be raised. Get rid of the try..catch block and you will see the actual exception that is being raised with regards the request_to_json function
By the looks of it, the problem is that you are trying to serialize the entire body of the request:
post_data = request.body
which simplejson doesn't like

Django - getting hostname error

I want to get name of the client that is trying to connect to server via Django, and I am stuck on this:
views.py
def home(request):
ime = request.META('REMOTE_HOST')
return HttpResponse('Welcome, %s.' %ime)
and error is:
Exception Type: TypeError
Exception Value: 'dict' object is not callable
**Traceback**
8. ime = request.META('REMOTE_HOST')
So, I don't get what the problem is.
I am still learning Django, btw.
request.META is a dictionary, so you need to access the REMOTE_HOST value with its key.
Change to:
ime = request.META['REMOTE_HOST'] # Note brackets not parens

Categories

Resources