5

I have this small piece of code that basically takes a list and runs a loop, running search queries against twitter, for each item in the list. I want each item in the list to be a collection name but for some reason I can't figure out how to make db<collection_name_variable>.insert(post)> to actually work:

I get an error:

TypeError: unsupported operand type(s) for +: 'Database' and 'str'

I know this is probably very basic but I am just learning.

from twython import Twython
from pymongo import *

conn = Connection('localhost')
db = conn.nosqltweets
twitter = Twython()

types = ['mongodb', 'cassandra', 'couchdb']

for nosql in types:
    search_results = twitter.searchTwitter(q=nosql, rpp="100")
    for tweet in search_results["results"]:
        from_user = tweet['from_user'].encode('utf-8')
        text = tweet['text']
        created_at = tweet['created_at']
        id_str = tweet['id_str']
        post = { 'id_str': id_str, 'from_user': from_user, 'created_at': created_at }
        insert = db + nosql + ".insert(post)"
        insert
3
  • 1
    You are trying to add / concatenate object of type "Database" (db) and "String" (nosql) using "+" operator. Commented Apr 2, 2012 at 17:50
  • Fenikso yep, actually as surprising as it is I did understand the problem just didn't understand how to solve it. Thanks for the comment! Commented Apr 2, 2012 at 19:29
  • @Ajj you can escape inline code by using backtick (`) no need to tweak it. Commented Apr 3, 2012 at 7:10

1 Answer 1

11

Replace:

insert = db + nosql + ".insert(post)"
insert

with:

db[nosql].insert(post)
Sign up to request clarification or add additional context in comments.

4 Comments

Sorry diliop that didn't work, I'd answer my own question but it won't let me here is what I did: I used getattr(db, nosql) collection = getattr(db, nosql) collection.insert(post)
Unless there is something missing from your code above, this should work. db is of type <class 'pymongo.database.Database'> and you can use both dot notation i.e. db.couchdb or dict member accessing i.e. db['couchdb'] to get an instance of <class 'pymongo.collection.Collection'> on which you call insert().
diliop you are right, apparently I didn't try what you posted correctly because I tried it again this evening and it worked! Thanks!!
Got it sorry I'm new to this site!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.