Kodexempel Python 3

Added by Edward almost 3 years ago

Eftersom kodexemplet är specifikt för Python 2 (t.ex. så stöds inte i skrivande stund M2Crypto i Python 3) så tänkte jag slänga upp en fungerande version av kodexemplet för Python 3:

import time
import urllib.parse
import json
import requests
from base64 import b64encode
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from cryptography.hazmat.primitives.asymmetric import padding

def print_json(j, prefix=''):
    for key, value in j.items():
        if isinstance(value, dict):
            print('%s%s' % (prefix, key))
            print_json(value, prefix + '  ')
        else:
            print('%s%s:%s' % (prefix, key, value))

username = 'username'
password = 'password'

service = 'NEXTAPI'
utf8 = 'UTF-8'
URL = 'https://api.test.nordnet.se'
API_VERSION = '2'

timestamp = str(int(round(time.time() * 1000)))
usernameBase64 = b64encode(bytes(username, encoding=utf8)).decode(utf8)
passwordBase64 = b64encode(bytes(password, encoding=utf8)).decode(utf8)
timestampBase64 = b64encode(bytes(timestamp, encoding=utf8)).decode(utf8)
authBlob = bytes(usernameBase64 + ':' + passwordBase64 + ':' + timestampBase64, encoding=utf8)

with open("NEXTAPI_TEST_public.pem", "rb") as keyFile:
    pem = keyFile.read()
pemKey = load_pem_public_key(pem, backend=default_backend())
cipher = pemKey.encrypt(authBlob, padding.PKCS1v15())
cipherBase64 = b64encode(cipher).decode(utf8)

headers = {"Accept": "application/json"}
# GET server status
response = requests.get(URL + '/next/' + API_VERSION + '/', headers=headers)
jsonResponse = json.loads(response.text)
print_json(jsonResponse)

# POST login
params = urllib.parse.urlencode({'service': 'NEXTAPI', 'auth': cipherBase64})
response = requests.post(URL + '/next/' + API_VERSION + '/login', params=params, headers=headers)
jsonResponse = json.loads(response.text)
print_json(jsonResponse)