Python Caching Pattern Issue


#1

With my below code I am trying to write a function get_fb_data that takes as input the string “me" and returns a big dictionary of Facebook data with the last up to 100 posts from that feed. I am trying to use cache data to set this up but clearly I am doing something wrong. When I open the file 506W17_PS9_caching.json I just see an empty dictionary. The error just has to do with the get_fb_data function but I provided most of the rest of my code to give context. I left out the access token and feed ID. The error I am getting is NameError: global name 'fb_data' is not defined, but I defined it.

import unittest
import requests
import json

CACHE_FNAME = "FB_caching.json"
try:
    f = open(CACHE_FNAME, "r")
    fstr = f.read()
    CACHE_DICTION = json.loads(fstr)
    f.close()
except: 
    CACHE_DICTION = {}
def params_unique_combination(baseurl, params_d, private_keys=["api_key"]):
    alphabetized_keys = sorted(params_d.keys())
    res = []
    for k in alphabetized_keys:
        if k not in private_keys:
            res.append("{}-{}".format(k, params_d[k]))
    return baseurl + "_".join(res)
baseurl = "https://graph.facebook.com/v2.3/me/feed"
url_params = {}
url_params["access_token"] = access_token
url_params["limit"] = 100
url_params["fields"] = "comments{comments{like_count,from,message,created_time},like_count,from,message,created_time},likes,message,created_time,from" 

def get_fb_data(me):
fb_id = params_unique_combination(baseurl, url_params)
if fb_id in CACHE_DICTION:
    fb_data = CACHE_DICTION[fb_id]
else:
    fb_req = requests.get(baseurl, params = url_params)
    fb_text = fb_req.text
    fb_data = json.loads(fb_text)
    f = open(CACHE_FNAME, "w")
    dump = json.dumps(CACHE_DICTION)
    f.write(dump)
    f.close()
    CACHE_DICTION[fb_id] = fb_data
return fb_data

#2

Isolate the issue - right now you're talking about http requests, files, python syntax, json - all at once without having narrowed down which the trouble is with

Your indentation isn't valid, you're not invoking your function, the filename isn't what you describe, you mention a pattern in the title but don't expand on what that is, and it doesn't look like it'll raise a name error about fb_data, so surely the code you're running is different from what you posted (aside from the token)