How to get refresh tokens on Facebook using Python? - python

I am currently using the following code for accessing the refresh tokens. Bare in mind that the config variable is frequently updated with the new access_token value after it is set.
refresh_token_url = config['facebook']['domain'] + \
'oauth/access_token?' + \
'grant_type=fb_exchange_token&' + \
'client_id=' + config['facebook']['client_id'] + '&' + \
'client_secret=' + config['facebook']['client_secret'] + '&' + \
'fb_exchange_token=' + config['facebook']['access_token']
new_access_token_obj = requests.get(refresh_token_url)
config['facebook']['access_token'] = json.loads(new_access_token_obj.text)['access_token']
But that I have noticed is that the new_access_token_obj has an expiry time that is lower than the old access_token but the two access tokens are different.
So, I am hoping that someone could tell me how to fix this code with a new access token which has a higher ['expires_in'] field.
PS :
Please note that I am aware that long lived tokens can be obtained using a web-app but I am looking to get it through a script (through some work-around).

Related

Search for files with ' in them with the Google Drive Python API

I'm using this code to find a file in My Drive with the Google Drive Python API:
results = service.files().list(q="name='"+finalfile+"'" fields="files(id)").execute()`
However, I get an error 400 whenever the file name has " ' " in it (I guess that it messes up the request). How can I search for a file with the apostrophe in it without crashing the program?
When your script is run, an error like invalid syntax occurs, because of no , between q="name='"+finalfile+"'" and fields="files(id)". But in your question, you say I get an error 400 whenever the file name has " ' " in it. From this situation, I guessed that you might have miscopied your script.
About your error of I get an error 400 whenever the file name has " ' " in it, in your situation, please escape ' like name='sample\'sample' and test it again. I thought that the reason for your current error might be due to this. In the case of your script, how about the following modification?
Modified script:
results = service.files().list(q="name='" + finalfile.replace("'", "\\'") + "'", fields="files(id)").execute()
By this modification, when the value of finalfile is sample'sample, this file can be retrieved.
Reference:
Files: list
You are missing a comma between your q parameter and your fields parameter
results = service.files().list(
pageSize=10,
q = "name='" + file_title + "'",
fields="nextPageToken, files(id, name)").execute()

How to get the latest cloudwatch log stream URL using Python Lambda?

I'm deploying some lambda functions and at the end, I need to print the complete URL of the latest CloudWatch log stream. So that other users can view the log directly by clicking the URL.
I've tried the below, but I need to print the complete URL.
print("CloudWatch log stream name:", context.log_stream_name)
I believe this can be done by using describe_log_streams along with some tweaks. But I'm helpless where to start.
I tried the below code and its working as expected, please comment for any improvement.
def multiple_replace(text, adict):
rx = re.compile('|'.join(map(re.escape, adict)))
def one_xlat(match):
return adict[match.group(0)]
return rx.sub(one_xlat, text)
def main(event, context):
region = context.invoked_function_arn.split(':')[3]
replace_map = {}
replace_map['/']='$252F'
replace_map['[']='$255B'
replace_map['$']='$2524'
replace_map[']']='$255D'
cw_logs = 'https://' + region + '.console.aws.amazon.com/cloudwatch/home?region=' + region + '#logsV2:log-groups/log-group/' + context.log_group_name.replace('/', '%252F') + '/log-events/' + multiple_replace(context.log_stream_name,replace_map)

How to make a hard-coded HTTP processing script dynamic?

I have a Jython 2.7 script that receives a URL and uses the parameters/values in the URL to create or update records.
Example URL: http://server:host/maximo/oslc/script/CREATEWO?&wonum=WO0001&description=Legacy&classstructureid=1666&wopriority=1&worktype=CM
Details:
Receive the URL and put the parameters/values in variables:
from psdi.server import MXServer
from psdi.mbo import MboSet
resp = {}
wonum = request.getQueryParam("wonum")
description = request.getQueryParam("description")
classstructureid = request.getQueryParam("classstructureid")
wopriority = request.getQueryParam("wopriority")
worktype = request.getQueryParam("worktype")
Some lines that aren't relevant to the question:
woset = MXServer.getMXServer().getMboSet("workorder",request.getUserInfo())
whereClause = "wonum= '" + wonum + "'"
woset.setWhere(whereClause)
woset.reset()
woMbo = woset.moveFirst()
Then use the values to either create a new record or update an existing record:
#If workorder already exists, update it:
if woMbo is not None:
woMbo.setValue("description", description)
woMbo.setValue("classstructureid", classstructureid)
woMbo.setValue("wopriority", wopriority)
woMbo.setValue("worktype", worktype)
woset.save()
woset.clear()
woset.close()
resp[0]='Updated workorder ' + wonum
#Else, create a new workorder
else:
woMbo=woset.add()
woMbo.setValue("wonum",wonum)
woMbo.setValue("description", description)
woMbo.setValue("classstructureid", classstructureid)
woMbo.setValue("wopriority", wopriority)
woMbo.setValue("worktype", worktype)
woset.save()
woset.clear()
woset.close()
resp[0]='Created workorder ' + wonum
responseBody =resp[0]
Question:
Unfortunately, the field names/values are hardcoded in 3 different places in the script.
I would like to enhance the script so that it is dynamic -- not hardcoded.
In other words, it would be great if the script could accept a list of parameters/values and simply loop through them to update or create a record in the respective fields.
Is it possible to do this?
You're using the Maximo Next Gen. REST API to execute an automation script that accepts an HTTP request with parameters and creates or updates a Work Order in the system. You want to make your script more generic (presumably to accept more paramaters for the created/updated work order) and/or other mbo's.
This can be achieved without developing automation scripts and just using the Next Gen. API you're already using to execute the script. The API already accepts create & update requests on the mxwo object structure with the ability to use all the fields, child objects, etc.
https://developer.ibm.com/static/site-id/155/maximodev/restguide/Maximo_Nextgen_REST_API.html#_creating_and_updating_resources
Assuming you are working always with the same query parameters, rather than define variables, loop through a list of strings and put them as key-value pairs
To populate
items = ["wonum", "description"]
resp = {k: request.getQueryParam(k) for k in items}
Then to set
for i in items:
woMbo.setValue(i, resp[i])
Otherwise, you are looking for URL parsing and the getQuery method, followed by a split("="), giving you ["wonum", "WO0001", "description", "Legacy"], for example, and you can loop over every other element to get you dynamic entries
l = ["wonum", "WO0001", "description", "Legacy"]
for i in range(0, len(l)-1, 2):
print(f'key:{l[i]}\tvalue:{l[i+1]}')
key:wonum value:WO0001
key:description value:Legacy
Note: This is subject to SQL injection attacks, and should be fixed
whereClause = "wonum= '" + wonum + "'"

generating oauth_signature for ETrade API using Python

The E*Trade API allows you to use RESTful to log on to the site and manipulate an account or retrieve quote information. Though I am having trouble generating an oauth_signature that matches their "practice problem" located toward the bottom of
https://us.etrade.com/ctnt/dev-portal/getContent?contentId=306a9d46-58c2-4cac-85f6-7717aea056bd
The simple HMAC-SMA1 algorithm has been coded below and reproduces the oauth core 1.0a signature value from here https://oauth.net/core/1.0a/#sig_base_example. Though I cannot get E*Trade signature value to reproduce.
def generate_oauth_signature():
from urllib.parse import quote_plus
from hashlib import sha1
import binascii
import hmac
key = quote_plus('7d30246211192cda43ede3abd9b393b9') + \
'&' + \
quote_plus('XCF9RzyQr4UEPloA+WlC06BnTfYC1P0Fwr3GUw/B0Es=')
key = key.encode()
raw = quote_plus('GET') + '&' + \
quote_plus('https://etws.etrade.com/accounts/rest/accountlist') + '&' + \
quote_plus('oauth_consumer_key=c5bb4dcb7bd6826c7c4340df3f791188&oauth_nonce=0bba225a40d1bbac2430aa0c6163ce44&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1344885636&oauth_token=VbiNYl63EejjlKdQM6FeENzcnrLACrZ2JYD6NQROfVI=')
raw = raw.encode()
hashed = hmac.new(key, raw, sha1)
sig = hashed.digest()
oauth_signature = quote_plus(binascii.b2a_base64(hashed.digest())[:-1])
The function is supposed to yield "%2FXiv96DzZabnUG2bzPZIH2RARHM%3D", but I'm not there yet. Has anyone worked out the hashing for the E*Trade API?
I am aware of the etradepy.py, which is a nice package, but is a little outdated and does not match the current E*Trade website.
One problem is that the oauth_token needs to be encoded in the parameter string (it will end up being double encoded). Mine is the following:
oauth_consumer_key=c5bb4dcb7bd6826c7c4340df3f791188&oauth_nonce=0bba225a40d1bbac2430aa0c6163ce44&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1344885636&oauth_token=VbiNYl63EejjlKdQM6FeENzcnrLACrZ2JYD6NQROfVI%3D

python generate_signed_query_string blob return wrong query string

I am trying to share a blob in a private Azure blob storage container using Python SDK, below is the code:
try:
accss_plcy = AccessPolicy()
accss_plcy.start = '2013-03-12'
accss_plcy.expiry = '2013-03-13'
accss_plcy.permission = 'r'
signed_identifier = 'YWJjZGVmZw=='
sap = SharedAccessPolicy(accss_plcy, signed_identifier)
qry_str = sas.generate_signed_query_string('picture/xxx.jpg','blob', sap)
except Exception as ex:
abort(400, 'Download blob fail %s'%ex)
return sas._convert_query_string(qry_str)
Below is the query string return :
st=2013-03-12&se=2013-03-13&sp=r&resource=blob&sig=FI88prUINf58Seg5Nwo6Uj5RP9FxXGZBBSKi7pybmeQ=&
You may notice that resource=blob, but it should return sr=b.
How should I solve the problem?
It looks like a bug in the SDK. Since the code for Azure SDK is open source, you could possibly download the code and make change to this file: https://github.com/WindowsAzure/azure-sdk-for-python/blob/master/src/azure/storage/sharedaccesssignature.py. Looking at the source code in that file, you would need to change the following line of code (line 129):
convert_str += SIGNED_RESOURCE_TYPE + '=' + query_string[SIGNED_RESOURCE] + '&'
to
convert_str += SIGNED_RESOURCE + '=' + query_string[SIGNED_RESOURCE] + '&'
Also I noticed that you're passing blob as the resource type in your code above:
qry_str = sas.generate_signed_query_string('picture/xxx.jpg','blob', sap)
You would need to pass 'b' instead of 'blob'
qry_str = sas.generate_signed_query_string('picture/xxx.jpg','b', sap)
I think that should do the trick. Also please ensure that you submit a bug on Github so that the team responsible for maintaining the code can fix it.

Categories