Search code examples
pythonfacebookpython-3.xpython-module

Module import fails unless in current directory - Python3


I have written a small Facebook OAUTH function that I want to use as a module whenever I need to generate a token to post to my FB feed or page. The problem is unless I'm in the directory that fb_auth is in I can't call the module.

Here's my code:

#!/usr/bin/env python3

''' Facebook authorization module'''

import requests
import os

def get_token(app_id, app_secret):
    payload = {'grant_type': 'client_credentials', 'client_id': app_id, 'client_secret': app_secret}
    response = requests.post('https://graph.facebook.com/oauth/access_token?', params=payload)
    result = eval(response.text)
    token = result['access_token']
    return token


if __name__ == '__main__':

    get_token()

So when i'm in the working directory (/home/scripts/python/fb_auth/)the module will import and function as it's supposed to:

>>> from fb_auth import get_token
>>> import os
>>> home = os.environ['HOME']
>>> work = home + '/scripts/python/'
>>> keys = work + 'apikeys'
>>> with open (keys, 'r') as f:
...    keys = eval(f.read())
... 
>>> app_id = keys['fb_keys']['riverwarn']['app_id']
>>> app_secret = keys['fb_keys']['riverwarn']['app_secret']
>>> get_token(app_id, app_secret)
'194XXXXXXXXXXXXXXXXXXXXXXXXXXXY_OM'

However, if I'm not in the working directory (/home/scripts/python/) I get nothing:

>>> import fb_auth
>>> fb_auth.get_token(app_id, app_secret)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'fb_auth' has no attribute 'get_token'

>>> from fb_auth import get_token

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'get_token'

Do I need to put this in the main Python modules folder to make this work correctly?


Solution

  • It wouldn't find it because it doesn't appear in the sys.path. You can add it to the sys.path by installing it. See full documentation here: https://docs.python.org/2/install/#how-installation-works