Example updated for Python 3

Added by Dmytro about 2 years ago

The existing Python example is for Python 2.
Here is updated example which works with Python 3, please add it to examples.


Replies (4)

RE: Example updated for Python 3 - Added by Dmytro about 2 years ago

#!/usr/bin/env python3
import time
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import http.client
import json
from urllib.parse import urlencode, quote_plus

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'
URL = 'api.test.nordnet.se'
API_VERSION = '2'

def get_hash(username, password):
    timestamp = int(round(time.time() * 1000))
    timestamp = str(timestamp).encode('ascii')

    username_b64 = base64.b64encode(username.encode('ascii'))
    password_b64 = base64.b64encode(password.encode('ascii'))
    timestamp_b64 = base64.b64encode(timestamp)

    auth_val = username_b64 + b':' + password_b64 + b':' + timestamp_b64
    rsa_key = RSA.importKey(open('NEXTAPI_TEST_public.pem').read())
    cipher_rsa = PKCS1_v1_5.new(rsa_key)
    encrypted_hash = cipher_rsa.encrypt(auth_val)
    encoded_hash = base64.b64encode(encrypted_hash)

    print(auth_val, encoded_hash)
    return encoded_hash

def main():
    auth_hash = get_hash(USERNAME, PASSWORD)

    headers = {"Accept": "application/json"}
    conn = http.client.HTTPSConnection(URL)

    # GET server status
    conn.request('GET', '/next/' + API_VERSION + '/', '', headers)
    r = conn.getresponse()
    response = r.read().decode('utf-8')
    j = json.loads(response)
    print_json(j)

    # POST login
    params = urlencode({'service': 'NEXTAPI', 'auth': auth_hash})
    conn.request('POST', '/next/' + API_VERSION + '/login', params, headers)
    r = conn.getresponse()
    response = r.read().decode('utf-8')
    j = json.loads(response)
    print_json(j)

if __name__ == "__main__":
    main()

RE: Example updated for Python 3 - Added by Nordnet Aleksandar about 2 years ago

HI,

We will definitely do that. Thank you for the contribution!

br
Aleks

RE: Example updated for Python 3 - Added by APIna almost 2 years ago

This solution was not added to the code examples page, i had to look in the forums for a replacement that did not rely on python 2 m2crypto.

RE: Example updated for Python 3 - Added by Nils over 1 year ago

Nice work Dmytro. Have spent some hours on trying to get this up and running. Please, add this to the examples, would have saved quite some hours for me.

(1-4/4)