Skip to main content

Hi, my python code below does not work in python 3, I receive a " Unicode-objects must be encoded before hashing" error message. Any tips?

import sys, getopt, hashlib, os

from hashlib import sha1

import hmac

import base64

import time

import requests

import subprocess

import json

import fme

import fmeobjects

import datetime

 

def calculate_signature(feature):

# get input values from feature attributes

api_key = FME_MacroValuess'API']

host = feature.getAttribute('host')

method = feature.getAttribute('method')

shared_secret = FME_MacroValuess'SharedSecret']

timestamp = feature.getAttribute('timestamp')

#timestamp = datetime.datetime.utcnow()

url = feature.getAttribute('url')

# set access_key

#access_key = FME_MacroValuess'AccessKey']

access_key = 'A0F66A0E-0CC9-7ABE-24CC-F8807E2829AB'

# copied code from calcualte_signature

sig_block = "{}\\r\\n{}\\r\\n{}\\r\\n{}\\r\\n{}\\r\\n{}\\r\\n".format(

method.upper(),

host,

url.lower(),

timestamp,

api_key,

access_key)

print("\\n\\n -- sig block -- \\n" + sig_block + "\\n\\n")

decoded_secret = base64.b64decode(shared_secret)

hashed = hmac.new(decoded_secret, sig_block, sha1)

sig = hashed.digest().encode("base64").rstrip('\\n')

# add sig value to feature as attribute

feature.setAttribute('sig',sig)

#feature.setAttribute('timestamp',str(timestamp))

Hi @johnglick,

Perhaps you might find it useful to use 2to3 - a python tool to automate code translation: https://docs.python.org/2/library/2to3.html

Else this doc may also be helpful to you: https://docs.python.org/3/howto/pyporting.html


Probably you will have to modify these two lines.

Python 2.7

hashed = hmac.new(decoded_secret, sig_block, sha1)
sig = hashed.digest().encode("base64").rstrip('\n')

Python 3.x

hashed = hmac.new(decoded_secret, sig_block.encode(), sha1)
sig = base64.b64encode(hashed.digest()).decode('utf-8')

 


Probably you will have to modify these two lines.

Python 2.7

hashed = hmac.new(decoded_secret, sig_block, sha1)
sig = hashed.digest().encode("base64").rstrip('\n')

Python 3.x

hashed = hmac.new(decoded_secret, sig_block.encode(), sha1)
sig = base64.b64encode(hashed.digest()).decode('utf-8')

 

works perfectly thanks!


Reply