Python Poloniex API Call - python-3.x

I have the following code that I am trying to make an API call to Poloniex according to their instructions
import urllib
import urllib.request
import json
import time
import hashlib
import codecs
import hmac
import time
Key = "whatever your key is"
Sign = "whatever your secret is"
def returnBalances(balances):
nonce = int(round(time.time()-599900000)*10)
parms = {"returnBalances":balances,
"nonce":nonce}
parms = urllib.parse.urlencode(parms)
hashed = hmac.new(b'Sign',digestmod=hashlib.sha512)
signature = hashed.hexdigest()
headers = {"Content-type":"application/x-www-form-urlencoded",
"Key":Key,
"Sign":signature}
conn = urllib.request.urlopen("https://poloniex.com")
conn.request("POST","/tradingApi",parms,headers)
response = conn.getresponse()
print(response.status,response.reason)
returnBalances('balances')
When I run this I get this error message
HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
Can someone please help?

You can catch HTTP errors with urllib.error.HTTPError
POST data should be bytes, so you have to encode parms
urllib.request.urlopen returns a HTTPResponse object, which has no request method.
If you want to set headers and other parameters you should use urllib.request.Request
According to the api docs the post parameters should be 'nonce' and 'command', so i modified your function to accept 'returnBalances' as a parameter and use it in parms["command"]
def api_call(command):
nonce = int(round(time.time()-599900000)*10)
parms = {"command":command, "nonce":nonce}
parms = urllib.parse.urlencode(parms).encode()
hashed = hmac.new(Sign.encode(), parms, digestmod=hashlib.sha512)
signature = hashed.hexdigest()
headers = {"Key":Key, "Sign":signature}
req = urllib.request.Request("https://poloniex.com/tradingApi", headers=headers)
try:
conn = urllib.request.urlopen(req, data=parms)
except urllib.error.HTTPError as e:
conn = e
print(conn.status,conn.reason)
return json.loads(conn.read().decode())
balances = api_call("returnBalances")

Related

Unable to Access API

I am unable to access an API.
This is what I am doing:
import os, re
import requests
import logger
from requests_oauthlib import OAuth1
oauth_consumer_key = "123abc"
oauth_secret = "aaabbbccc"
url = "https://example_testing/v1/<ID_VALUE>/reports?"
oauth = OAuth1(oauth_consumer_key, oauth_secret)
output = requests.get(url,auth=oauth)
I keep getting a 500 error.
What am I doing wrong?
I didn't know this but apparently I needed to set values for headers and the payload. This solved my problem.
headers = {"Content-Type": "application/json"}
payload = json.dumps({
"report_format":"csv",
<other stuff>
}
output = requests.get(url=url, auth=oauth, headers=headers, data=payload)
Problem Solved

Why is django test client throwing away my extra headers

I'm trying to test a view that makes use of some headers. In my test code I have something like this:
headers = {'X-Github-Event': 'pull_request'}
body = {useful stuff}
url = reverse(my_view)
I've tried making requests to my view using all possible combinations of the following clients and post calls:
client = Client(extra=headers)
client = APIClient(headers=headers)
client = APIClient(extra=headers)
response = client.post(url, data=body, format="json", headers=headers)
response = client.post(url, data=body, format="json", extra=headers)
My view effectively looks like this:
#api_view(["POST", "GET"])
def github_webhook(request):
print(request.headers)
My X-Github-Event header is never printed out by my view when it is called from my test code.
If I run runserver and send a request to that endpoint then the headers work perfectlty fine. It's just the test code that is broken.
What am I missing here? How can I set the headers for my tests?
I think that the following snippet will help you:
import json
from django.test import TestCase
from rest_framework.test import APIClient
class FooTestCase(TestCase):
def setUpTestData(cls):
cls.client = APIClient(ACCEPT='application/json')
def test_foo(self):
headers = {"ACCEPT": "application/json", 'HTTP_X_GITHUB_EVENT': 'pull_request'}
url = reverse(my_view)
payload = json.dumps(body)
response = self.client.post(url, data=payload, content_type='application/json', **headers)

How to receive an image from a POST request on Google Cloud Function with Python?

I'm struggling to reassemble an image sent via a POST request to a GCP Cloud Function.
I've looked at advice here about how to package a file with POST request.
I would like the function to reconstruct the image from bytes for further processing, everytime I send the request I get 'Failure' back. Any help would be really appreciated!
### client_side.py
import requests
url = 'https://region-project.cloudfunctions.net/function' # Generic GCP functions URL
files = {'file': ('my_image.jpg', open('my_image.jpg', 'rb').read(), 'application/octet-stream')}
r = requests.post(url, files=files)
### gcp_function.py
from io import BytesIO
def handler(request):
try:
incoming = request.files.get('file')
bytes = BytesIO(incoming)
image = open_image(bytes)
message = 'Success'
except:
message = 'Failure'
return message
Sorted it.
Needed the read method to convert FileStorage Object to bytes.
### gcp_function.py
from io import BytesIO
import logging
def handler(request):
try:
incoming = request.files['file'].read()
bytes = BytesIO(incoming)
image = open_image(bytes)
message = 'Success'
except Exception as e:
message = 'Failure'
logging.critical(str(e))
return message

Problem with Python encrypted request.post

I have a problem with encrypted post requests. The encrypted algorithm is AES/ECB/PKCS5Padding and API settings are here: https://bondevalue.com/app/apiInstructions client_token is working. But I always receive 'Seems you are providing invalid input data. Provide data in valid format.'
import requests
import json
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64
client_token = b'ae3rncr14cngemft'
requestData = b'{\"data\":{\"userToken\":\"[ae3rncr14cngemft]\"},\"bondISINId\":\"[XS1401197253]\", \"fromDate\":\"[2016-12-07]\"}'
cipher1 = AES.new(client_token, AES.MODE_ECB)
requestEncrypted = str(base64.b64encode(cipher1.encrypt(pad(requestData, 16, 'pkcs7'))), 'utf-8')
url = 'https://bondevalue.com/app/bondDetailsHistoryData'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = {'requestData': requestEncrypted}
answer = requests.post(url=url, data=requestEncrypted, headers=headers)
response = answer.json()

Unable to read the buffer from BytesIO in google app engine flex environment

Here is the related code
import logging
logging.getLogger('googleapicliet.discovery_cache').setLevel(logging.ERROR)
import datetime
import json
from flask import Flask, render_template, request
from flask import make_response
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from oauth2client.client import AccessTokenCredentials
...
#app.route('/callback_download')
def userselectioncallback_with_drive_api():
"""
Need to make it a background process
"""
logging.info("In download callback...")
code = request.args.get('code')
fileId = request.args.get('fileId')
logging.info("code %s", code)
logging.info("fileId %s", fileId)
credentials = AccessTokenCredentials(
code,
'flex-env/1.0')
http = httplib2.Http()
http_auth = credentials.authorize(http)
# Exports a Google Doc to the requested MIME type and returns the exported content. Please note that the exported content is limited to 10MB.
# v3 does not work? over quota?
drive_service = build('drive', 'v3', http=http_auth)
drive_request = drive_service.files().export(
fileId=fileId,
mimeType='application/pdf')
b = bytes()
fh = io.BytesIO(b)
downloader = MediaIoBaseDownload(fh, drive_request)
done = False
try:
while done is False:
status, done = downloader.next_chunk()
logging.log("Download %d%%.", int(status.progress() * 100))
except Exception as err:
logging.error(err)
logging.error(err.__class__)
response = make_response(fh.getbuffer())
response.headers['Content-Type'] = 'application/pdf'
response.headers['Content-Disposition'] = \
'inline; filename=%s.pdf' % 'yourfilename'
return response
It is based on some code example of drive api. I am trying to export some files from google drive to pdf format.
The exception comes from the line
response = make_response(fh.getbuffer())
It throws the exception:
TypeError: 'memoryview' object is not callable
How can I retrieve the pdf content properly from the fh? Do I need to further apply some base 64 encoding?
My local runtime is python 3.4.3
I have used an incorrect API. I should do this instead:
response = make_response(fh.getvalue())

Resources