Ken I.
Ken I.

Reputation: 450

Properly creating OAuth2Service with Rauth and Django

I am using rauth to authentication against stripe connect. In doing so I am needing to instantiate a OAuth2Service for use in multiple views. Right now my views file looks a lot like this (and works), but this just feels wrong:

from rauth.service import Oauth2Service

service = OAuth2Service(
    name = 'stripe',
    client_id = 'my_client_id',
    client_secret = 'my_secret',
    authorize_url = 'auth_url',
    access_token_url = 'stripe_access_token_url',
    base_url = 'stripe_api_url',
)

def stripe_auth(request):
    params = {'response_type': 'code'}
    url = service.get_authorize_url(**params)
    return HttpResponseRedirect(url)

def stripe_callback(request):
    code = request.GET['code']
    data = {
        'grant_type': 'authorization_code',
        'code': code
    }
    resp = service.get_raw_access_token(method='POST', data=data)
    ... rest of view code ...

My problem is that I feel that placing the "service" variable outside of the views is somehow wrong, but I am not sure the way I really should handle this. Should I split it out into a separate module, place it in the settings file, create a decorator? I am not real sure.

Any advice is greatly appreciated.

Upvotes: 2

Views: 969

Answers (1)

David K. Hess
David K. Hess

Reputation: 17246

I usually add it as an attribute to the Flask Application object like this:

app = Flask(....)
app.stripe = OAuth2Service(
    name = 'stripe',
    client_id = 'my_client_id',
    client_secret = 'my_secret',
    authorize_url = 'auth_url',
    access_token_url = 'stripe_access_token_url',
    base_url = 'stripe_api_url',
)

That makes it easily accessible.

Upvotes: 1

Related Questions