Connection error to MongoDB: object has no attribute 'getitem' - python

When trying to connect to MongoDB , I'm experiencing an error
How can I solve this?
Traceback (most recent call last):
File "D:/MongoDB-U/Python/Codes/Try.py", line 17, in
print (item['name'])
TypeError: 'NoneType' object has no attribute 'getitem'
Code:
import pymongo
from pymongo import MongoClient
connection = MongoClient('localhost',27017)
db = connection.test
names = db.things
item = things.find_one()
print (item['name'])

You're creating a names collection variable but then using a things collection variable in your find_one call. It should be:
db = connection.test
things = db.things
item = things.find_one()
print (item['name'])

Related

How to solve attribute error: 'Cursor' object has no attribute 'noCursorTimeout' in pymongo?

I'm trying to set noCursorTimeout in the session following this instruction from MongoDB docs.
But I'm getting the error: AttributeError: 'Cursor' object has no attribute 'noCursorTimeout'
I can't wonder why I'm getting this.
from pymongo import MongoClient as Connection
from datetime import datetime
conn = Connection(get_uri())
with conn as conn:
collection = conn['db_name']['my_collection']
documents_cursor = collection.find(query).noCursorTimeout() # same with .maxTimeMS()
According to the document, you should use it like this:
cursor = collection.find({"a": 1}, no_cursor_timeout=True)
Reference: https://api.mongodb.com/python/current/migrate-to-pymongo3.html#timeout-replaced-by-no-cursor-timeout

Can't seem to get Python, Peewee, pymysql & MySql database to work no 'returning_clause' error

I am pretty new to Python and trying to use a very simple one table DB.
I'm using python 3, peewee and pymysql. The database is MySQL, local on my Windows 10 PC (wampserver) and the code is;
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import peewee
from peewee import *
db = MySQLdb.connect(user='xxxxx', passwd='xxxxx',
host='localhost', port=3306, db='xxxxx')
class SearchUrl(peewee.Model):
id = peewee.AutoField()
url = peewee.TextField()
page_title = peewee.TextField()
date_found = peewee.DateField()
date_last_changed = peewee.DateField()
article_status = peewee.CharField()
description = peewee.TextField()
class Meta:
database = db
newUrl = SearchUrl.create(url='http://cropnosis.co.uk', page_title="Cropnosis Ltd.",
date_found='2018-04-13', status='new', description='Cropnosis website')
newUrl.save()
for url in SearchUrl.filter(url='http://cropnosis.co.uk'):
print(url.description)
db.close()
Whenever I run this I get the following error in the "SearchUrl.create" line. I have searched for the 'returning_clause' attribute but have found little or no mention of it esp. with regard to MySQL.
Any help or relevant links greatly appreciated.
Traceback (most recent call last):
File "researcherDb.py", line 26, in <module>
date_found='2018-04-13', status='new', description='Cropnosis website')
File "C:\.dev\Client\Cropnosis\Researcher\lib\site-packages\peewee.py", line 5161, in create
inst.save(force_insert=True)
File "C:\.dev\Client\Cropnosis\Researcher\lib\site-packages\peewee.py", line 5284, in save
pk_from_cursor = self.insert(**field_dict).execute()
File "C:\.dev\Client\Cropnosis\Researcher\lib\site-packages\peewee.py", line 5128, in insert
return ModelInsert(cls, cls._normalize_data(__data, insert))
File "C:\.dev\Client\Cropnosis\Researcher\lib\site-packages\peewee.py", line 5868, in __init__
if self.model._meta.database.returning_clause:
AttributeError: 'Connection' object has no attribute 'returning_clause'
You want this:
from peewee import *
# this is peewee.MySQLDatabase, not pymysql's connection class.
db = MySQLDatabase('the_db_name', user='xxxxx', passwd='xxxxx')

applying function on rdd.foreach pyspark

I am trying to apply send_active_mq on each row of an rdd.
def send_to_active_mq(json_string) :
k = str(json_string)
conn.send(body=k,destination='dwEmailsQueue2')
json_rdd_to_send.foreach(send_to_active_mq)
I applied the same way as suggested in the spark documentation
http://spark.apache.org/docs/1.1.1/api/python/pyspark.rdd.RDD-class.html#foreach
But I am getting the following error.
AttributeError: 'builtin_function_or_method' object has no attribute '__code__'
Is there something fundamentally wrong I am doing here.
This is probably connected to conn object. Try:
def send_to_active_mq(json_strings):
conn = ... # Initalize connection
for json_string in json_strings:
conn.send(body=str(json_string) ,destination='dwEmailsQueue2')
json_rdd_to_send.foreachPartition(send_to_active_mq)

can't use find() in collection instance in pymongo

I have a class:
import sys
import os
import pymongo
from pymongo import MongoClient
class Collection():
def __init__(self, db, collection_name):
self.db = db
self.collection_name = collection_name
if not hasattr(self.__class__, 'client'):
self.__class__.client = MongoClient()
self.data_base = getattr(self.client, self.db)
self.collection = getattr(self.data_base, self.collection_name)
I created class instances as follows:
def getCollections(self):
collections_dict = {}
for i in range(len(self.db_collection_names)):
collections_dict[self.db_collection_names[i]] = Collection(self.database_name, self.db_collection_names[i])
return collections_dict
db_collection_names contains email_logs. I created an emails instance as follows:
emails = collections_dict['email_logs']
print emails yields <collection.Collection instance at 0x105ce6248>
print emails.find() yields:
Traceback (most recent call last):
File "main.py", line 75, in <module>
program.runProgram()
File "main.py", line 63, in runProgram
print emails.find
AttributeError: Collection instance has no attribute 'find'
Why the error?
Not sure why you're bothering to redefine the Pymongo Collection class.
from pymongo import MongoClient
db = MongoClient().my_database # create an instance of pymongo Database
emails = db.emails # create an instance of pymongo Collection
emails.find() # yeilds a pymongo Cursor (containing the query results)
I was missing the collection before the find() method
emails.collection.find()

How do you save models in Elixir

I've got a database created using Django models which I'm now accessing using SQLAlchemy and Elixir. The querying works and I can pull items out of the database perfectly happily but when I edit them and try to save them it throws the following exception:
>>> p = Problem.query.first()
>>> p
<Problem('Test Problem', 'This is a test problem so the database has something in it', 'SBMT')>
>>> p.name
u'Test Problem'
>>> p.name = "Test_Problem"
>>> p.save()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/elixir/entity.py", line 1116, in save
return self._global_session.save(self, *args, **kwargs)
AttributeError: 'Session' object has no attribute 'save'
What am I doing wrong? Have I missed a crucial part of the set up that is preventing me from saving things to the database or is it a problem with my versions of elixir and SQLAlchemy?
I've already run setup_all() and the metadata.bind is all set, hence I can query the database.
I'm no Elixir expert, but from the documentation it looks like it uses something called a global session.
To save the changes to the database, you do a session.commit(), there's no save() method like in Django.

Categories

Resources