-1

I know it is generally a bad idea but I think for my task it should be ok. I have to deal with multiple Facebook pages, each has its own access token. Depending on user's choice I call Facebook's graph to get insights for that particular page.

My code:

#User's input
date_since = request.form['since']
date_until = request.form['until']     
page_name = request.form['page_name']
#Call Facebook Graph
r = requests.get('https://graph.facebook.com/v2.8/'+page_name+'/insights/metric/day?since='+since+'&until='+until+'&access_token='+token+'')

I store all the tokens in a separate file to keep them secret:

token_pagename1 = 'TOKEN1'
token_pagename2 = 'TOKEN2'

What I want to do is to pass token_pagename1 into my requests.get if the user chooses "pagename1" from a preset list of names.

I construct a new string based on the user's input:

page_token = 'token' + '_' + page_name

But now I need to convert this string into a variable name token. I tried to use vars()[page_token] instead of token but I get a KeyError from requests.get.

Could anyone suggest an elegant solution to my problem? Thanks!

aviss
  • 2,179
  • 7
  • 29
  • 52

2 Answers2

1

Convert your list of named tokens:

token_pagename1
token_pagename2

to a dictionary:

tokens = {}
tokens['pagename1']
tokens['pagename2']

Then it's easy to find the token you're looking for:

tokens[page_requested]
TemporalWolf
  • 7,727
  • 1
  • 30
  • 50
0

Create a dictionary

tokens = {
   'pagename1': 'TOKEN1'
   'pagename2': 'TOKEN2'
}

Now you can access the page token via

tokens['pagename']
Arun Ghosh
  • 7,634
  • 1
  • 26
  • 38