Python - Converting urllib to requests - python

I'm writing code to access the MS365 API and the Python code example uses urllib. I want to instead use requests but I'm not sure how urllib translates into requests as my attempts of doing so have failed.
The code example can be found here:
https://learn.microsoft.com/en-us/microsoft-365/security/defender-endpoint/run-advanced-query-sample-python?view=o365-worldwide#get-token
import json
import urllib.request
import urllib.parse
tenantId = '00000000-0000-0000-0000-000000000000' # Paste your own tenant ID here
appId = '11111111-1111-1111-1111-111111111111' # Paste your own app ID here
appSecret = '22222222-2222-2222-2222-222222222222' # Paste your own app secret here
url = "https://login.microsoftonline.com/%s/oauth2/token" % (tenantId)
resourceAppIdUri = 'https://api.securitycenter.microsoft.com'
body = {
'resource' : resourceAppIdUri,
'client_id' : appId,
'client_secret' : appSecret,
'grant_type' : 'client_credentials'
}
data = urllib.parse.urlencode(body).encode("utf-8")
req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)
jsonResponse = json.loads(response.read())
aadToken = jsonResponse["access_token"]

IIUC, this should work the same:
import requests
tenantId = '00000000-0000-0000-0000-000000000000' # Paste your own tenant ID here
appId = '11111111-1111-1111-1111-111111111111' # Paste your own app ID here
appSecret = '22222222-2222-2222-2222-222222222222' # Paste your own app secret here
url = "https://login.microsoftonline.com/%s/oauth2/token" % (tenantId)
resourceAppIdUri = 'https://api.securitycenter.microsoft.com'
params = {
'resource' : resourceAppIdUri,
'client_id' : appId,
'client_secret' : appSecret,
'grant_type' : 'client_credentials'
}
response = requests.get(url, params)
jsonResponse = response.json()
aadToken = jsonResponse["access_token"]

Modifying #BeRT2me's answer has made this work.
import requests
tenantId = '00000000-0000-0000-0000-000000000000' # Paste your own tenant ID here
appId = '11111111-1111-1111-1111-111111111111' # Paste your own app ID here
appSecret = '22222222-2222-2222-2222-222222222222' # Paste your own app secret here
url = "https://login.microsoftonline.com/%s/oauth2/token" % (tenantId)
resourceAppIdUri = 'https://api.securitycenter.microsoft.com'
data = {
'resource' : resourceAppIdUri,
'client_id' : appId,
'client_secret' : appSecret,
'grant_type' : 'client_credentials'
}
response = requests.post(url=url, data=data)
jsonResponse = response.json()
aadToken = jsonResponse["access_token"]

Related

Gravity form API with python

The documentation of the API is here, and I try to implement this line in python
//retrieve entries created on a specific day (use the date_created field)
//this example returns entries created on September 10, 2019
https://localhost/wp-json/gf/v2/entries?search={"field_filters": [{"key":"date_created","value":"09/10/2019","operator":"is"}]}
But when I try to do with python in the following code, I got an error:
import json
import oauthlib
from requests_oauthlib import OAuth1Session
consumer_key = ""
client_secret = ""
session = OAuth1Session(consumer_key,
client_secret=client_secret,signature_type=oauthlib.oauth1.SIGNATURE_TYPE_QUERY)
url = 'https://localhost/wp-json/gf/v2/entries?search={"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}'
r = session.get(url)
print(r.content)
The error message is :
ValueError: Error trying to decode a non urlencoded string. Found invalid characters: {']', '['} in the string: 'search=%7B%22field_filters%22:%20[%7B%22key%22:%22date_created%22,%22value%22:%2209/01/2023%22,%22operator%22:%22is%22%7D]%7D'. Please ensure the request/response body is x-www-form-urlencoded.
One solution is to parameterize the url:
import requests
import json
url = 'https://localhost/wp-json/gf/v2/entries'
params = {
"search": {"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}
}
headers = {'Content-type': 'application/json'}
response = session.get(url, params=params, headers=headers)
print(response.json())
But in the retrieved entries, the data is not filtered with the specified date.
In the official documentation, they gave a date in this format "09/01/2023", but in my dataset, the format is: "2023-01-10 19:16:59"
Do I have to transform the format ? I tried a different format for the date
date_created = "09/01/2023"
date_created = datetime.strptime(date_created, "%d/%m/%Y").strftime("%Y-%m-%d %H:%M:%S")
What alternative solutions can I test ?
What if you use urllib.parse.urlencode function, so your code would looks like:
import json
import oauthlib
from requests_oauthlib import OAuth1Session
import urllib.parse
consumer_key = ""
client_secret = ""
session = OAuth1Session(consumer_key,
client_secret=client_secret,signature_type=oauthlib.oauth1.SIGNATURE_TYPE_QUERY)
params = {
"search": {"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}
}
encoded_params = urllib.parse.urlencode(params)
url = f'https://localhost/wp-json/gf/v2/entries?{encoded_params}'
r = session.get(url)
print(r.content)
hope that helps
I had the same problem and found a solution with this code:
params = {
'search': json.dumps({
'field_filters': [
{ 'key': 'date_created', 'value': '2023-01-01', 'operator': 'is' }
],
'mode': 'all'
})
}
encoded_params = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
url = 'http://localhost/depot_git/wp-json/gf/v2/forms/1/entries?' + encoded_params + '&paging[page_size]=999999999' # nombre de réponses par page forcé manuellement
I'm not really sure what permitted it to work as I'm an absolute beginner with Python, but I found that you need double quotes in the URL ( " ) instead of simple quotes ( ' ), so the solution by William Castrillon wasn't enough.
As for the date format, Gravity Forms seems to understand DD/MM/YYYY. It doesn't need a time either.

Generating Accèss Token- OAuth2.0

I am working with the Spotify API. I am trying to generate an access token. I followed along https://www.youtube.com/watch?v=xdq6Gz33khQ this video to generate the token.
I am getting an error
{'error': 'invalid_client'}
The code I have written is:
import base64
from wsgiref import headers
import requests
import json
client_id = "09e0b9beeba74aee986546f496823d60"
client_secret = "be1c93f2a446477e8416235b2a3f442c"
# searching for token which will help in authorization
client_creds = f"{client_id} : {client_secret}"
client_creds_b64 = base64.b64encode(client_creds.encode())
token_url = "https://accounts.spotify.com/api/token"
method = "POST"
token_data = {
"grant_type": "client_credentials"
}
token_header = {
"Authorization" : f"Basic {client_creds}" # <base64 encoded client_id:client_secret>
}
r = requests.post(token_url, data=token_data, headers=token_header)
print(r.json())
Not sure why I get this error. It could be the link I am using for the token url but can't find what to replace it with.
change
client_creds = f"{client_id} : {client_secret}"
to
client_creds = f"{client_id}:{client_secret}"
change
"Authorization" : f"Basic {client_creds}" # <base64 encoded client_id:client_secret>
to
"Authorization": f"Basic {client_creds_b64.decode()}"

Logging in to Magento account from Python script

I'm trying to login to Magento account from Python script using requests module, the relevant code I made looks as below:
s = requests.session()
main_url = '<redacted.tld>/en/index.html'
html_data = s.get('https://'+main_url, headers=headers, timeout=(30, 30), verify=dst_verify_ssl)
web_user = 'test#test.com'
web_pass = '123test321'
form_key = soup.find('input', {'name':'form_key'})['value']
l_url = 'https://<redacted.tld>/'
l_route = 'en/customer/account/loginPost/'
login_payload = {
'form_key':form_key,
'login[username]':web_user,
'login[password]':web_pass
}
login_req = s.post(l_url + l_route, headers=headers, data=login_payload)
But it's not getting me logged in so I was wondering if someone could tell me what does it take to login via Python to the Magento account?
Thanks.
I gave this one a go on a public demo instance and I can see the data on the Magento 2 dashboard just fine:
import requests
from bs4 import BeautifulSoup
web_user = 'youremail#example.com'
web_pass = 'yourpassword'
s = requests.session()
main_url = 'https://magento2demo/'
html_data = s.get(main_url)
form_soup = BeautifulSoup(html_data.content, 'html.parser')
form_key = form_soup.find('input', {'name':'form_key'})['value']
login_route = 'https://magento2demo/customer/account/loginPost/'
login_payload = {
'form_key': form_key,
'login[username]': web_user,
'login[password]': web_pass
}
login_req = s.post(login_route, data=login_payload)
account_url = "https://magento2demo/customer/account/"
html_account = s.get(account_url)
account_soup = BeautifulSoup(html_account.content, 'html.parser')
info = account_soup.find('div', {'class':'box-information'}).find('div', {'class':'box-content'})
assert web_user in str(info)
"beautifulsoup4": { "version": "==4.9.3"
"requests": { "version": "==2.26.0"
What's the response code on the POST? Anything peculiar in your headers?
Might wanna add more reproducible data if the above doesn't help.

getting 404 when trying to add songs to using spotify api

I'm making a project which will add songs from your youtube playlist to spotify playlist. everything works fine except the add_item() method. I'm getting 404 : not found response from the requests object.
Yes, i checked if the song actually exists. It does and even printed the id of the song.So it exists.
I'm following the official documentation
here is my code -
import json
from requests_oauthlib import OAuth2Session
import requests
import base64
import urllib.parse as urlparse
from urllib.parse import parse_qs
client_id = #id
client_secret = #secret
redirect_uri = 'https://www.spotify.com'
scope = "playlist-modify-public user-read-email user-read-private playlist-modify-private"
req = f'{client_id}:{client_secret}'
encoded = base64.b64encode(req.encode())
class sp :
def __init__(self) :
self.get_token()
self.get_id()
self.uri_list = []
def get_token(self) :
url = 'https://accounts.spotify.com/authorize'
oauth = OAuth2Session(client_id, redirect_uri = redirect_uri, scope = scope)
authorization_url, state = oauth.authorization_url(url)
print(authorization_url)
authorization_response = input('paste here : ')
parsed = urlparse.urlparse(authorization_response)
authorization_code = parse_qs(parsed.query)['code'][0]
# to get auth token
headers = {
'Authorization' : f'Basic {encoded.decode()}'
}
data = {
'grant_type' : 'authorization_code',
'redirect_uri' : redirect_uri,
'code' : authorization_code
}
access = requests.post('https://accounts.spotify.com/api/token', data = data, headers = headers)
response = json.loads(access.text)
self.access_token = response['access_token']
def get_id(self) :
headers = {
'Authorization' : f'Bearer {self.access_token}'
}
user_info = requests.get('https://api.spotify.com/v1/me', headers = headers)
user_info.raise_for_status()
user_info = json.loads(user_info.text)
self.user_id = user_info['id']
def search(self) :
search_url = 'https://api.spotify.com/v1/search'
headers = {
'Authorization': f'Bearer {self.access_token}'
}
params = {
'q' : 'track:Memories artist:Maroon 5',
'type' : 'track',
'limit' : 1,
}
search_response = requests.get(search_url, headers = headers, params = params)
search_response.raise_for_status()
json_response = search_response.json()
song_uri = json_response['tracks']['items'][0]['uri']
self.uri_list.append(song_uri)
def create_playlist(self) :
create_playlist_url = f'https://api.spotify.com/v1/users/{self.user_id}/playlists'
headers = {
'Authorization' : f'Bearer {self.access_token}',
'Content-Type' : 'application/json'
}
data = json.dumps({
'name' : 'new playlist'
})
response = requests.post(create_playlist_url, headers = headers, data = data)
print(response)
self.playlist_id = response.json()['uri']
def add_items(self) :
add_items_url = f'https://api.spotify.com/v1/playlists/{self.playlist_id}/tracks'
headers = {
'Authorization' : f'Bearer {self.access_token}',
'Content-Type' : 'application/json'
}
print(self.uri_list)
data = {
'uris' : json.dumps(self.uri_list)
}
res = requests.post(add_items_url, headers = headers, data = data)
print(res)
user = sp()
user.create_playlist()
user.search()
user.add_items()
Any help is appreciated. Thanks
You have this line of code for playlist creation:
self.playlist_id = response.json()['uri']
and then in items addition logic you have:
add_items_url = f'https://api.spotify.com/v1/playlists/{self.playlist_id}/tracks'
are you sure that you want to use playlist uri as playlist id?
Could you update your question with more info:
response.json() value after playlist is created
print add_items_url after f-string was declared
UPDATE
https://developer.spotify.com/documentation/web-api/reference/playlists/create-playlist/ as I can see here - the response after creation of the playlist include id field
So you should just change this line
self.playlist_id = response.json()['uri']
to
self.playlist_id = response.json()['id']

Dailymotion API get refresh token by request.post python

I want to get refresh token from Dailymotion API by this code
def get_refresh_token(code):
platform = Platform.objects.get(name='Dailymotion')
secret_key = platform.secret_key
api_key = platform.api_key
redirect_uri = platform.callback_url
params = {
'code' : code,
'client_id' : api_key,
'client_secret' : secret_key,
'grant_type':'authorization_code',
'redirect_uri':redirect_uri
}
r = requests.post('https://api.dailymotion.com/oauth/token',data=params)
print (r.json())
print(code)
print(r.data)
refresh_token = r.json().get('refresh_token')
return refresh_token
but it's not working. the error is : {'error_description': 'Invalid authorization code.', 'error': 'invalid_grant'}
.I tried with the same code,grant_type... post from Chrome extensions and it works. What did i do wrong with python code?
def get_refresh_token(self, code):
args = {
'grant_type': 'refresh_token',
'refresh_token': code,
'client_id': DAILYMOTION_API_KEY,
'client_secret': DAILYMOTION_API_SECRET,
}
url = 'https://api.dailymotion.com/oauth/token'
data = urllib.urlencode(args)
request = urllib2.Request(url, data)
response = urllib2.urlopen(request)
html = response.read()
obj_Response = literal_eval(html)
return obj_Response
while getting AccessToken we get a parameter 'code' here we have to put that value in place of code.

Categories