rbw / pysnow

ServiceNow API Client Library
MIT License
203 stars 89 forks source link

Is there a way to use pysnow with a http proxy and oauth? #151

Closed Turegano closed 4 years ago

Turegano commented 4 years ago

We are using pysnow for several projects but we can't achieve what we did with proxies in requests:

requests.post('https://XXXXXXXXX.service-now.com/oauth_token.do',data={'client_id': 'XXXXXXXX', 'client_secret': 'XXXXXXX','grant_type': 'refresh_token', 'refresh_token': rtoken}, proxies=proxies)

Thank you

Turegano commented 4 years ago

We found a way to do it, using the environment vars:

In [1]: import pysnow, os

In [2]: os.environ["HTTP_PROXY"]="http://ip:3128"

In [3]: os.environ["HTTPS_PROXY"]="http://ip:3128"

In [4]: snow_user = 'snow_user' ...: snow_pwd = 'snow_pwd' ...: store = {'token': None}

In [6]: client_id = 'client_id' ...: client_secret = r'client_secret'

In [13]: # SNOW OAuth Token ...: ...: # Takes care of refreshing the token storage if needed ...: def updater(new_token): ...: print("OAuth token refreshed!") ...: store['token'] = new_token ...: ...: # Create the OAuthClient with the ServiceNow provided client_id and client_secret, and a token_updater ...: # function which takes care of refreshing local token storage. ...: c = pysnow.OAuthClient(client_id=client_id, ...: client_secret=client_secret, ...: token_updater=updater, instance='itconic') ...: ...: if not store['token']: ...: # No previous token exists. Generate new. ...: store['token'] = c.generate_token(snow_user, snow_pwd) ...: ...: # Set the access / refresh tokens ...: c.set_token(store['token'])

In [14]: cmdb_ci = c.resource(api_path='/table/cmdb_ci_server')

In [15]: ci_sys_id = '08ca14953773d7040b1d579543990ea3'

In [16]: # Obtener el os y la compañía del CI. ...: ci_query = ( ...: pysnow.query_builder.QueryBuilder() ...: .field("sys_id").equals(ci_sys_id) ...: ) ...: ...: ci_os = cmdb_ci.get(query=ci_query).all()[0]["os"] ...: ci_company_id = cmdb_ci.get(query=ci_query).all()[0]["company"]["value"]

In [17]: ci_os Out[17]: u'Linux CentOS'

In [18]: ci_company_id Out[18]: u'61f4d11edb3cee00f57cdbd5ae961975'

It might come in handy for someone if it is added into the documentation

Thank you