unicode' object has no attribute 'items' - python

I am updating the document in solr using pysolr python. I am taking one field data from solr document and after updating it i am ingesting it again using
solr.add(dict)
Basically i am ingesting a dictionary in solr again.
However i am getting this error :
File "/usr/local/lib/python2.7/dist-packages/pysolr.py", line 907, in add
el = self._build_doc(doc, boost=boost, fieldUpdates=fieldUpdates)
File "/usr/local/lib/python2.7/dist-packages/pysolr.py", line 822, in _build_doc
for key, value in doc.items():
AttributeError: 'unicode' object has no attribute 'items'

tried solr.add(res[dict]) instead of solr.add(dict) It worked.

Related

Python sqlalchemy core Inspector.get_columns AttributeError: 'Connection' object has no attribute 'contextual_connect'

I am trying to use metadata and inspect with its methods to get the column name of datatable stored in redshift.
As long as I call get_columns it would raise an AttributeError
My code
metadata = MetaData()
inspect_engine = inspect(engine)
inspect_engine.get_schema_names() # This returns a list of schema
inspect_engine.get_table_names(schema="my_schema") # This returns a list of table names
inspect_engine.get_columns(schema="my_schema", table_name="my_table") # This raise an AttributeError
AttributeError: 'Connection' object has no attribute 'contextual_connect'
Summary
inspect_engine.get_schema_names() and inspect_engine.get_table_names(schema="my_schema") works
inspect_engine.get_columns(schema="my_schema", table_name="my_table") not working
I saw my_schema in the list which returns by inspect_engine.get_schema_names(); my_table in the list which returns by inspect_engine.get_table_names(schema="my_schema")
Version: sqlalchemy 1.4.7
Question
If it is the problem of connection why get_schema_names and get_table_names works?
How to makes get_columns works in this case ?

Issues with beautifulsoup.find() in python

I am trying to make a simple web scraper with python to get stock data. My code was working not long ago and I don't believe I changed anything but now I'm getting the following error:
File "tradingProgram.py", line 69, in
dataArr.append(i.find('div',{'class':'tv-screener-table__symbol-right-part'}).find('a').text)
AttributeError: 'NoneType' object has no attribute 'find'
This is the part of the code that handles beautifulsoup:
content = requests.get("https://www.tradingview.com/markets/stocks-usa/market-movers-gainers/")
soup = BeautifulSoup(content.text,'html.parser')
stockData = soup.find_all('tr',{'class':'tv-data-table__row tv-data-table__stroke tv-screener-table__result-row'})
print(len(stockData))
for i in stockData:
print(i)
dataArr.append(i.find('div',{'class':'tv-screener-table__symbol-right-part'}).find('a').text)

Can't get the value from a JSON object using Python

import requests
import json
s = requests.Session()
s.params["key"] = "MY_KEY"
s.params["cx"] = "MY_CX"
s.params["num"] = 1
result = s.get('https://www.googleapis.com/customsearch/v1', params={"q": "Search query"})
Everything is working fine and I do get a result back but it's JSON. What I want is one thing. Since my result only gives 1 search result, I want the link of that search result. From I've understood that link value is under the keys "item" and then "link". I've tried lots of things but I keep getting either one of these errors below.
TypeError: 'Response' object is not subscriptable
NameError: name 'json' is not defined
AttributeError: 'Response' object has no attribute 'read'
TypeError: the JSON object must be str, not 'Response'
What am i doing wrong and what's the solution?

Python - Attribute Error '_io.TextIOWrapper' object has no attribute 'open'

I receive an error
File.open(classname+'.txt','a')
AttributeError: '_io.TextIOWrapper' object has no attribute 'open'
while trying to open a file. I need to open the file and write to the file with the scores.
Here is the code
if Exists==False:
File.open(classname+'.txt','a')
File.write(name+','+surname+','+str(1)+','+str(score)+'/n')
else:
File=open(classname+'.txt','w')
linecount=len(filelines)
for i in range(0,linecount):
File.write(filelines[i])
it should be
File=open(classname+'.txt','a')
File.write(name+','+surname+','+str(1)+','+str(score)+'/n')
File.close()
The problem is that at the beginning you declare
File=open(classname+'.txt','r+')
and then you ask again to open File
File.open(classname+'.txt','a')
but File is already open(classname+'.txt','r+'). Just skip File.open(classname+'.txt','a') and it should work fine.

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