python-3.xprawdecouplingpython-decouple

Integrating python-decouple with PRAW?


I've been trying to see if I can use python-decouple to place my bot credentials on a separate .env file.

Auth method is basically right off the praw doc:

    reddit = praw.Reddit(
        client_id=config('CLIENT_ID'),
        client_secret=config('CLIENT_SECRET'),
        password=config('PASSWORD'),
        user_agent=config('USER_AGENT'),        
        username=config('USERNAME')
    )

However, whenever I try it, it seems to return an 403 auth error. I work my way back, replacing the decouple configs with strings of the actual details, but it doesn't seem to follow through, and the errors that occur seem random depending on what and when things I take out.

Is this a problem with how decouple functions?

Thanks.


Solution

  • I've been trying to see if I can use python-decouple to place my bot credentials on a separate .env file.

    Why not use a praw.ini file? This is documented here in PRAW documentation. It's a format for storing Reddit credentials in a separate file from your code. For example, a praw.ini file may look like:

    [bot1]
    client_id=Y4PJOclpDQy3xZ
    client_secret=UkGLTe6oqsMk5nHCJTHLrwgvHpr
    password=pni9ubeht4wd50gk
    username=fakebot1
    
    [bot2]
    client_id=6abrJJdcIqbclb
    client_secret=Kcn6Bj8CClyu4FjVO77MYlTynfj
    password=mi1ky2qzpiq8s59j
    username=fakebot2
    

    You then use specific credentials in your code like so:

    import praw
    
    reddit = praw.Reddit('bot2', user_agent='myBot v0.1')
    print('Logged in as', reddit.user.me())
    

    I think this is the best solution for working with PRAW credentials.


    However, if you really want to do it with python-decouple, here's a working example:

    Contents of file .env:

    username=k8IA
    password=REDACTED
    client_id=REDACTED
    client_secret=REDACTED
    

    Contents of file connect.py:

    import praw
    
    from decouple import config
    
    reddit = praw.Reddit(username=config('username'),
            password=config('password'),
            client_id=config('client_id'),
            client_secret=config('client_secret'),
            user_agent='myBot v0.1')
    
    print('Logged in as', reddit.user.me())
    

    Output when running python3 connect.py:

    Logged in as k8IA