Reputation: 209
I am new to programing and Python..
Below is my code.
import csv
import json
import urllib
import sys
import time
import re
class FacebookSearch:
def __init__(self,
query = 'https://graph.facebook.com/search.{mode}?{query}&{access_token}'
):
access_token = 'XXXXXX|XXXXX'
def search(self, q, mode='json', **queryargs):
queryargs['q'] = q
query = urllib.urlencode(queryargs)
return query
def write_csv(fname, rows, header=None, append=False, **kwargs):
filemode = 'ab' if append else 'wb'
with open(fname, filemode) as outf:
out_csv = csv.writer(outf, **kwargs)
if header:
out_csv.writerow(header)
out_csv.writerows(rows)
def main():
ts = FacebookSearch()
response, data = ts.search('appliance', type='post') ## here is where I am getting the error.
js = json.loads(data)
messages = ([msg['created_time'], msg['id']] for msg in js.get('data', []))
write_csv('fb_washerdryer.csv', messages, append=True)
if __name__ == '__main__':
main()
Here is the trace back on the error:
Traceback (most recent call last): File "./facebook_washer_dryer1.sh", line 43, in main() File "./facebook_washer_dryer1.sh", line 33, in main response, data = ts.search('appliance', type='post') ValueError: too many values to unpack
Upvotes: 0
Views: 787
Reputation: 365915
Your FacebookSearch.search
method returns a single value, a query string to tack onto a URL.
But when you call it, you're trying to unpack the results to two variables:
response, data = ts.search('appliance', type='post')
And that doesn't work.
So, why does the error say "too many values" instead of "too few"? Well, a string is actually a sequence of single-character strings, so it's trying to unpack that single string into dozens of separate values, one for each character.
However, you've got a much bigger problem here. You clearly expected your search
method to return a response and some data, but it doesn't return anything even remotely like a response and some data, it returns a query string. I think you wanted to actually build a URL with the query string, then download that URL, then return the results of that download.
Unless you write code that actually attempts to do that (which probably means changing __init__
to store self.query
and self.access_token
, using self.query.format
in search
, using urllib2.urlopen
on the resulting string, and a bunch of other changes), the rest of your code isn't going to do anything useful.
If you want to "stub out" FacebookSearch
for now, so you can test the rest of your code, you need to make it return appropriate fake data that the rest of your code can work with. For example, you could do this:
def search(self, q, mode='json', **queryargs):
queryargs['q'] = q
query = urllib.urlencode(queryargs)
# TODO: do the actual query
return 200, '{"Fake": "data"}'
Upvotes: 3