404 Response When fetching Balance accounts Api - python-3.x

import paypalrestsdk
import httpx
class paypal:
def __init__(self):
self.secret_id = 'XXXX'
self.client_id = 'XXXX'
self.token = ''
def getToken(self):
headers = {
'Accept': 'application/json',
'Accept-Language': 'en_US',
}
data = {
'grant_type': 'client_credentials'
}
response = httpx.post(url='https://api.sandbox.paypal.com/v1/oauth2/token', data=data,headers=headers,auth=(self.client_id,self.secret_id))
response_data = response.json()
self.token = response_data['access_token']
def getBalance(self):
print(self.token)
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer '+self.token,
'Accept':'application/x-www-form-urlencoded'
}
response = httpx.post(url='https://api.sandbox.paypal.com/v2/wallet/balance-accounts', headers=headers)
print(response.status_code)
response_data = response.json()
print(response_data)
available = response_data['total_available'][0]['value']
print(response_data)
if __name__ == "__main__":
s = paypal()
s.getToken()
s.getBalance()
I am gettitng 404 code i am doing something bad?
Traceback (most recent call last):
File "C:/Users/localhost/PycharmProjects/Telegram/paypal/Main.py", line 48, in <module>
s.getBalance()
File "C:/Users/localhost/PycharmProjects/Telegram/paypal/Main.py", line 37, in getBalance
response_data = response.json()
File "C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\site-packages\httpx\models.py", line 899, in json
return jsonlib.loads(self.text, **kwargs)
File "C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
404
https://developer.paypal.com/docs/limited-release/balance-accounts/v2/api/
I try also with
"Authorization: Access-Token" But the response is the same, i readed and searched in the docs, i dont found anything and the acces token is fresh so i dont understand, cause the acces token i get is valid.

You are sending a POST request instead of a GET request. Use httpx.get instead of httpx.post.
You can even use httpx_auth to keep your code focusing on what you want to retrieve:
import paypalrestsdk
import httpx
import httpx_auth
class paypal:
def __init__(self):
self.auth = httpx_auth.OAuth2ClientCredentials(
token_url='https://api.sandbox.paypal.com/v1/oauth2/token',
client_id='XXXX',
client_secret='XXXX',
)
def getBalance(self):
response = httpx.get(url='https://api.sandbox.paypal.com/v2/wallet/balance-accounts', auth=self.auth)
print(response.status_code)
response_data = response.json()
print(response_data)
available = response_data['total_available'][0]['value']
print(response_data)
if __name__ == "__main__":
s = paypal()
s.getBalance()

Related

Using pytest and requests.request in dependency-injector

I have
file1.py
def _request_token(self):
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = {
'id': self.id,
}
response = requests.request(
method="POST",
url=self.url,
headers=headers,
data=data
)
self.token_json = response.json()
test_token.py
def test_request_token(test_token):
with patch('mod1.file1.requests.request') as mock_request:
mock_request.return_value = json.loads('{"response": "returned_data"}')
res = test_token._request_token()
assert res.token_json == {"response": "returned_data"}
conftest.py
#pytest.fixture(scope="session")
def test_token(test_container):
return test_container.token_mgr(id="abc")
#pytest.fixture(scope="session")
def test_container():
test_container = initialize(test_yaml_dir)
return test_container
I'm using dependency-injectors, and the traceback I currently see:
AttributeError: 'dict' object has no attribute 'json'
Do I need to fully mock a response, using a different method?

Run Multithread and Asyncio together

i am trying to make a python program that makes http requests and parses the data from the response with asyncio and aiohttp. The program takes as input a list of urls that can reach even more than 300/400 elements and should make requests as fast as possible. Since asyncio runs on only one thread, I was thinking of splitting the list into sublists and starting a thread for each sublist with asyncio and aiohttp, but adding the ThreadPoolExecutor I get coroutine and futures errors. How can I use Thread and asyncio together? I leave the code below.
async def fetch(url, session):
async with session.get(url, ssl=False) as response:
# if response.status == 200:
html_body = await response.json()
url = url.split('/')[-2]
file_name = url if url != 'services' else 'live'
async with aiofiles.open(f'{output_dir}/{file_name}.json', 'w') as f:
await f.write(json.dumps(html_body, indent=4))
return html_body
async def fetch_with_sem(sem, session, url):
async with sem:
return await fetch(url, session)
async def run(url, session, sem):
tasks = [asyncio.create_task(fetch_with_sem(sem, session, url)) for url in url]
page_content = await asyncio.gather(*tasks, return_exceptions=True)
return page_content
async def main(urls):
number = len(urls) // 10 + 1
sem = asyncio.Semaphore(50)
loop = asyncio.get_event_loop()
connector = aiohttp.TCPConnector(limit_per_host=30, limit=50, ttl_dns_cache=100)
headers = {
'user-agent': get_user_agent(),
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': "macOS",
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-origin',
'x-eb-accept-language': 'it_IT',
'x-eb-marketid': '5',
'x-eb-platformid': '1',
}
async with ClientSession(loop=loop, connector=connector, headers=headers) as session:
if isinstance(urls, list):
with ThreadPoolExecutor(max_workers=25) as executor:
page_content = [executor.submit(
run, urls[number * i : number * (i + 1)], session, sem
).result() for i in range(10)
]
else:
tasks = [asyncio.create_task(fetch_with_sem(sem, session, urls))]
page_content = await asyncio.gather(*tasks, return_exceptions=True)
return page_content
the problem is given from executor.submit and got this error:
RuntimeWarning: coroutine 'wait' was never awaited
page_content = [executor.submit(asyncio.wait(run), urls[number * i : number * (i + 1)], session, sem).result() for i in range(10)]
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
File "/Users/federikowsky/Desktop/Python/Scraping/SureBet/prova.py", line 123, in <module>
x = asyncio.run(main(link))
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/Users/federikowsky/Desktop/Python/Scraping/SureBet/prova.py", line 110, in main
page_content = [executor.submit(asyncio.wait(run), urls[number * i : number * (i + 1)], session, sem).result() for i in range(10)]
File "/Users/federikowsky/Desktop/Python/Scraping/SureBet/prova.py", line 110, in <listcomp>
page_content = [executor.submit(asyncio.wait(run), urls[number * i : number * (i + 1)], session, sem).result() for i in range(10)]
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/concurrent/futures/_base.py", line 437, in result
return self.__get_result()
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/concurrent/futures/_base.py", line 389, in __get_result
raise self._exception
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
TypeError: 'coroutine' object is not callable

How to fix error urllib.error.HTTPError: HTTP Error 400: BAD REQUEST?

I have a script(test.py) to test some api, like this:
def get_response(fct, data, method=GET):
"""
Performs the query to the server and returns a string containing the
response.
"""
assert(method in (GET, POST))
url = f'http://{hostname}:{port}/{fct}'
if method == GET:
encode_data = parse.urlencode(data)
response = request.urlopen(f'{url}?{encode_data}')
elif method == POST:
response = request.urlopen(url, parse.urlencode(data).encode('ascii'))
return response.read()
In terminal I call:
python test.py -H 0.0.0.0 -P 5000 --add-data
The traceback:
Traceback (most recent call last):
File "test.py", line 256, in <module>
add_plays()
File "test.py", line 82, in add_plays
get_response("add_channel", {"name": channel}, method=POST)
File "test.py", line 43, in get_response
response = request.urlopen(url, parse.urlencode(data).encode('ascii'))
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 223, in urlopen
return opener.open(url, data, timeout)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 532, in open
response = meth(req, response)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 642, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 570, in error
return self._call_chain(*args)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 504, in _call_chain
result = func(*args)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 650, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: BAD REQUEST
The data is {"name": "Channel1"}. I couldn't understand what is wrong. Please can someone give some tip or show whats's wrong?
When I call using curl, works:
curl -X POST -H "Content-Type: application/json" -d '{"name": "Channel1"}' http://0.0.0.0:5000/add_channel
I solved the problem change the test script:
The api was expected a JSON_MIME_TYPE = 'application/json', so I add a header in a request as follow bellow.
The scrit was using a wrong encode because some text in JSON couldn't be encode in Unicode, Eg:"Omö" encode in ascii launch the exception UnicodeEncodeError: 'ascii' codec can't encode character '\xf6' in position 1: ordinal not in range(128). So I changed to utf8.
Here is the fixed code:
def get_response(fct, data, method=GET):
"""
Performs the query to the server and returns a string containing the
response.
"""
assert(method in (GET, POST))
url = f'http://{hostname}:{port}/{fct}'
if method == GET:
encode_data = parse.urlencode(data)
req = request.Request(f'{url}?{encode_data}'
, headers={'content-type': 'application/json'})
response = request.urlopen(req)
elif method == POST:
params = json.dumps(data)
binary_data = params.encode('utf8')
req = request.Request(url
, data= binary_data
, headers={'content-type': 'application/json'})
response = request.urlopen(req)
x = response.read()
return x

How to upload a video file using python in video indexer api?

I am trying to upload a video in Video Indexer API using Python:
import http.client, urllib.request, urllib.parse, urllib.error, base64
headers = {
# Request headers
'Content-Type': 'multipart/form-data',
'Ocp-Apim-Subscription-Key': '******************',
}
params = urllib.parse.urlencode({
# Request parameters
'name': 'xxxx',
'privacy': 'Private',
'language': 'English',
})
try:
conn = http.client.HTTPSConnection('videobreakdown.azure-api.net')
conn.request("POST", "/Breakdowns/Api/Partner/Breakdowns?%s" % params, "{body}", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
But I am not able to specify how to give the video file in the {body} section.
Kindly help me.
This works for me:
import requests
import urllib.parse
import json
headers = {
'Ocp-Apim-Subscription-Key': 'YOUR-API-KEY',
}
form_data = {'file': open('YOUR-VIDEO.mp4', 'rb')}
params = urllib.parse.urlencode({
'name': 'video.mp4',
'privacy': 'Private',
'language': 'English',
})
try:
url = 'https://videobreakdown.azure-api.net/Breakdowns/Api/Partner/Breakdowns?'
r = requests.post(url, params=params, files=form_data, headers=headers)
print(r.url)
print(json.dumps(r.json(), indent=2))
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))

error message in microsoft emotion api video python3

Im trying to get the emotions from a video
Below is my code,
Always when I run this code i get this error
b'{"error":{"code":"BadArgument","message":"Failed to deserialize JSON request."}}' any idea why?
import http.client, urllib.request, urllib.parse, urllib.error, base64, sys
headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': 'xxxxxxxxxxx',
}
params = urllib.parse.urlencode({
})
body = "{ 'url': 'http://www.dropbox.com/s/zfmaswf8s9c58om/blog2.mp4' }"
try:
conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com')
conn.request("POST", "/emotion/v1.0/recognizeinvideo?%s" % params, "
{body}", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print(e.args)
You forgot to substitute the placeholder {body} with the real thing.
conn.request("POST", "/emotion/v1.0/recognizeinvideo?%s" % params, body, headers)

Resources