using oauth2 library of python in Django to access dropbox - django

I am trying to access dropbox account info using oauth2 library.
I have got hold of access token from dropbox. Then what I am doing is:
parameters = {
'oauth_consumer_key' : DropboxConstants.app_key, #my app key
'oauth_token' : access_token_g,#token that i got [<key>,<secret>]
'oauth_signature_method': oauth.SignatureMethod_HMAC_SHA1.name,
'oauth_timestamp' : oauth.generate_timestamp(),
'oauth_nonce' : oauth.generate_nonce(),
'oauth_version' : DropboxConstants.api_version,
'oauth_signature' : ''
}
#prepare signature
oauth_request= oauth.Request(method="GET",url=DropboxConstants.account_info_url,parameters=parameters)
signature_method_m = oauth.SignatureMethod_HMAC_SHA1()
signature = signature_method_m.signing_base(consumer=consumer,request=oauth_request,token=access_token_g)
parameters['oauth_signature'] = signature[1]
#prepare url for accessing account info
url = "%s?oauth_token=%s&oauth_consumer_key=%s&oauth_signature_method=%s&oauth_timestamp=%s&oauth_nonce=%s&oauth_version=%s&oauth_signature=%s"%\
(DropboxConstants.account_info_url,access_token['oauth_token'],parameters['oauth_consumer_key'],parameters['oauth_signature_method'],parameters['oauth_timestamp'],parameters['oauth_nonce'],parameters['oauth_version'], parameters['oauth_signature'])
return HttpResponseRedirect(url)
now the signature that is getting generated:
GET&https%3A%2F%2Fapi.dropbox.com%2F0%2Faccount%2Finfo&oauth_consumer_key%3Dedw6k7d78hu8q8v%26oauth_nonce%3D39519001%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1314679561%26oauth_token%3Doauth_token_secret%253Dun58fgoc14n9jlv%2526oauth_token%253D2ew2dafg0r40uwq%26oauth_version%3D1.0
error I get is:
{"error": "Invalid signature. Expected signature base string: GET&https%3A%2F%2Fapi.dropbox.com%2F0%2Faccount%2Finfo&https%253A%252F%252Fapi.dropbox.com%252F0%252Faccount%252Finfo%3D%26oauth_consumer_key%3Dedw6k7d78hu8q8v%26oauth_consumer_key%253Dedw6k7d78hu8q8v%2526oauth_nonce%253D39519001%2526oauth_signature_method%253DHMAC-SHA1%2526oauth_timestamp%253D1314679561%2526oauth_token%253Doauth_token_secret%25253Dun58fgoc14n9jlv%252526oauth_token%25253D2ew2dafg0r40uwq%2526oauth_version%253D1.0%3D%26oauth_nonce%3D39519001%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1314679561%26oauth_token%3D2ew2dafg0r40uwq%26oauth_version%3D1.0"}

firstly please use urlencode to escape chars correctly:
from urllib import urlencode
...
parameters['oauth_token'] = access_token_g['oauth_token']
url = "?".join(DropboxConstants.account_info_url, urlencode(parameters))
see if this helps, if not i'll look into the signiature base

Actually i have solved this problem with a bit change in code as:
access_token_g =
oauth.Token(key=access_token['oauth_token'],secret=access_token['oauth_token_secret'])
#prepare signature
oauth_request = oauth.Request(method="GET",url=account_info_url,parameters=parameters)
signature_method_m = oauth.SignatureMethod_HMAC_SHA1()
oauth_request.sign_request(signature_method=signature_method_m,consumer=consumer,token=access_token_g)
resp, content = client.request(oauth_request.to_url())
It gives me correct content..

Related

How to extract the values from the response body in postman

After posting the request, API return response body as string
Response body look like
{ UniqueID = 93243434,birthGender = M,birthDate = 11/1/2018 5:51:18
PM, familyNames = James, givenNames = Test }
when I try to set the environment variable using the below code
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("currentUniqueId", data.UniqueId);
I got the below error on test results
Error message:
There was an error in evaluating the test script: JSONError:
Unexpected token 'U' at 1:3 { UniqueID = 93243434,birthGender =
M,birthDate = 11/1/2018 5:51:18 PM, family ^
my goal is I need to extract the value 93243434 and assign to environment variable.
Hi you are using the correct way but you can try this version
var jsonData = pm.response.json();
pm.environment.set("UNIQUE_ID", jsonData.UniqueID);
The set("UNIQUE_ID" will help you save it in variable and you can name it as you want and jsonData.uniqueID will extract what you want to get from the Json response
If you view my approach I am extracting Access code and company id and saving it in variable and calling it in all next api's
You are using a notation pattern that is deprecated.
Instead of set your variable using:
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("currentUniqueId", data.UniqueId);
Try to set your variable this way:
pm.environment.set('currentUniqueId', pm.response.json().UniqueID);
To get more information, try: https://learning.getpostman.com/docs/postman/scripts/test_examples/

Instagram ?__a=1 not working anymore

I've been using Instagram's undocumented API https://www.instagram.com/<user>/?__a=1 to get a public user feed on a website. Since a while now, this is not working anymore, probably because Facebook removed it. Is there an other way to get the data of an instagram account in a easy way?
I built a small server which does that transformation. You'll receive the instagram data as before with ?__a=1 (as JSON ) - have fun 😊
https://www.instapi.io/u/<username>
https://www.instapi.io/u/appwithus
EDIT 12/2020: Unfortunately the service is no longer available
Edit 15/03 NOT WORKING ANYMORE Seems like instagram changed again their API, now it gives a CORS error.
As of 2 february 2021, I have found a solution
Instead of using https://www.instagram.com/username/?__a=1 which it asks for a login.
Justing adding a /channel seems to make it work, like so:
https://www.instagram.com/username/channel/?__a=1
There is a JSON data in https://www.instagram.com/<user>/.
You can use regexp to find what you need.
Sample
// This regexp gets widest possible dict around "profile_pic_url"
// but inside tag <script type="text/javascript">...</script>
let r = new RegExp('<script type="text\/javascript">' +
'([^{]+?({.*profile_pic_url.*})[^}]+?)' +
'<\/script>');
let source = document.documentElement.outerHTML;
let jsonStr = source.match(r)[2];
let data = JSON.parse(jsonStr);
console.log('data', data);
let oldVariantOfData = data['entry_data']['ProfilePage'][0];
console.log('oldVariantOfData', oldVariantOfData);
The same response is attached in the html response of the profile url, I perform this temporal solution (when I can't use the API) in python:
url_recent_media = 'https://www.instagram.com/%s/' % instagram_id
response = urllib2.urlopen(url_recent_media)
insta_html = response.read()
insta_html_split = insta_html.split('"ProfilePage":[')
if len(insta_html_split) > 1:
insta_html_split_2 = insta_html_split[1].split(']},"gatekeepers"')
if len(insta_html_split_2) > 1:
json_dict = json.loads(insta_html_split_2[0])
I hope this help you.
you can try without using instagram API.
import json, urllib2
img_dicts = []
url = 'https://www.instagram.com/{}/'.format(instagram_username)
try:
r = urllib2.urlopen(url, timeout=10.0)
instagram_html = r.read()
instagram_html_data = instagram_html.split('"ProfilePage":[')
if len(instagram_html_data) > 1:
instagram_html_final_data = instagram_html_data[1].split(']},"gatekeepers"')
if len(instagram_html_final_data) > 1:
json_dict = json.loads(instagram_html_final_data[0])
media = json_dict['graphql']['user']['edge_owner_to_timeline_media']['edges']
for obj in media:
img_dicts.append({
'id': obj['node']['id'],
'caption': obj['node']['edge_media_to_caption']['edges'][0]['node']['text'],
'imgurl_standard': obj['node']['display_url'],
'imgurl_lower': obj['node']['thumbnail_resources'][4]['src'],
'imgurl_thumb': obj['node']['thumbnail_resources'][3]['src']
})
img_dicts will give you images in different quality and caption of instagram post.

Python overwrite config file with variables stored in other file

Suppose I have a file called main_config.py and custom_config.py. They are both in the same module.
What I want to do is have two separate config files, where one of them (main) is version controlled, and the other one (custom) is .gitignore'd to allow different setups have their own configs with the main file used as a template.
The code belows used to work properly on Python 3.5, but I was forced to revert to 2.7 and it is no longer working as expected. What am I doing wrong? I'm getting KeyError: 'client2' exception on the line with exec.
Contents of main_config.py:
class MainConfig(object):
clients = {
"client1" = {
"IP" = "127.0.0.1",
"User" = "admin"
}
}
try:
with(open(__file__.replace("main_config.py", "custom_config.py")) as source_file:
exec(source_file.read())
except IOError, e:
print("No custom config detected")
Contents of custom_config.py:
from (...).main_config import MainConfig
MainConfig.clients["client2"]["IP"] = "0.0.0.0"
MainConfig.clients["client2"]["User"] = "root"
I see you use dictionary and = sign instead of :.
Aside from that, you cannot assign IP without client2 assigned before it so your code could look like this:
main_config.py
class MainConfig(object):
clients = {
"client1" : {
"IP" : "127.0.0.1",
"User" : "admin"
}
}
try:
with(open(__file__.replace("main_config.py", "custom_config.py")) as source_file:
exec(source_file.read())
except IOError, e:
print("No custom config detected")
custom_config.py
from (...).main_config import MainConfig
if 'client2' not in MainConfig.clients.keys():
MainConfig.clients["client2"] = {}
MainConfig.clients["client2"]["IP"] = "0.0.0.0"
MainConfig.clients["client2"]["User"] = "root"
I'm not explaining how to solve the specific error you encounter (other answers already do that), but I'd like
to point out there are more suitable config languages for your use case. Specifically, Figura
natively supports this sort of overrideability.
Here's an example:
# main_config.py
class MainConfig:
class clients:
class client1:
IP = "127.0.0.1"
User = "admin"
# custom_config.py
class CustomConfig:
# declare this config is meant to be applied as an override to another
__override__ = True
class client2:
IP = "0.0.0.0"
User = "root"
And combining them in your code:
from figura import build_config
full_config = build_config('main_config.MainConfig', 'custom_config.CustomConfig')
The flexible build_config function treats the first arg as the base config, and the rest as overrides to apply to it.
Full disclosure: I am the author of figura.

how to display absolute url of a websevice in play framework

I am new to play framework. I am having a web service url. To that url I am appending some parameters. I want display that url after appending the values to that url.
Here is my code:
public JsonNode getCustomerDetails(CustomerDto customerDto){
String feedUrl = Constants.ERP_CUSTOMER_URL;
WSRequestHolder wsHolder = null;
wsHolder = WS.url(feedUrl);
wsHolder.setAuth(Constants.ERPUSERNAME, Constants.ERPPASSWORD,Realm.AuthScheme.BASIC);
whereClause.append("mobileno='").append(customerDto.getMobile()).append("'")
.append(ORDER_BY_UPDATED_ASC);
wsHolder.setQueryParameter(_WHERE, whereClause.toString());``
F.Promise<WS.Response> response = wsHolder.get();
json = response.get().asJson();
}
Constants.ERP_CUSTOMER_URL is my webservice url to that I am appending mobileno. I want to display the absolute url of my webservice after appending the values to it. I tried to display wsHolder but it is displaying as play.libs.WS$WSRequestHolder#6afe06a7
You can see it with getUri() on the WS.Response object like:
response.get().map((Function) response -> {
System.out.println(response.getUri());
}
);

How to get Expiration Date of access token in Facebook SDK for Unity

I am using parse sdk for backend management for my game. For user signup/login parse api ask for parameter tokenExpiration. I have no idea how to get it from facebook unity sdk.
https://www.parse.com/docs/unity_guide#fbusers-signup
Task<ParseUser> logInTask = ParseFacebookUtils.LogInAsync(accessToken, userId, tokenExpiration);
Got this problem solved by myself using debug_token. Here is the right code on how to do it.
FB.API("/debug_token?input_token="+FB.AccessToken+"&access_token="+FB.AccessToken,Facebook.HttpMethod.GET, AccessTokenCallback);
function AccessTokenCallback(response:String){
Debug.Log(response);
var access = JSON.Parse(response);
Debug.Log("Token Expiration is: "+access["data"]["expires_at"].Value);
}
If you will print the response it will give you a JSON with all information about the access token and you can take whatever info you need about an access token.
Open FacebookAccessTokenEditor.cs and replace original line 81:
formData["batch"] = "[{\"method\":\"GET\", \"relative_url\":\"me?fields=id\"},{\"method\":\"GET\", \"relative_url\":\"app?fields=id\"}]";
by these two:
string getExpiresAt = ",{\"method\":\"GET\", \"relative_url\":\"debug_token?input_token="+accessToken+"\"}";
formData["batch"] = "[{\"method\":\"GET\", \"relative_url\":\"me?fields=id\"},{\"method\":\"GET\", \"relative_url\":\"app?fields=id\"}"+getExpiresAt+"]";
Then open FacebookEditor.cs and in method MockLoginCallback, just before line 220:
isLoggedIn = true;
insert the following lines:
var tokenData = (Dictionary<string, object>)MiniJSON.Json.Deserialize(responses[2]);
var expiresAt = (long)((Dictionary<string, object>)tokenData["data"])["expires_at"];
accessTokenExpiresAt = FromTimestamp((int)expiresAt);
also, add the missing function FromTimestamp which you can copy from AndroidFacebook.cs or IOSFacebook.cs or jus copy from here:
private DateTime FromTimestamp(int timestamp)
{
return new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(timestamp);
}
Finally, you can call the parse method like you do on IOS or Android or Web:
Task<ParseUser> logInTask = ParseFacebookUtils.LogInAsync(FB.UserId, FB.AccessToken, FB.AccessTokenExpiresAt);
Note: As I have worked on the code, I am not sure of the original line numbers, but I think they are correct. Also, this does not reflect the best coding practices, but since it is used only in a debug context, they're good enough for me.