Skip to main content
Question

Anybody have tips to update my python code to python 3?

  • November 9, 2018
  • 3 replies
  • 366 views

johnglick
Contributor
Forum|alt.badge.img+1

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_MacroValues['API']

host = feature.getAttribute('host')

method = feature.getAttribute('method')

shared_secret = FME_MacroValues['SharedSecret']

timestamp = feature.getAttribute('timestamp')

#timestamp = datetime.datetime.utcnow()

url = feature.getAttribute('url')

# set access_key

#access_key = FME_MacroValues['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))

3 replies

Forum|alt.badge.img+2

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


takashi
Influencer
  • November 10, 2018

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')

 


johnglick
Contributor
Forum|alt.badge.img+1
  • Author
  • Contributor
  • November 11, 2018
takashi wrote:

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!


Cookie policy

We use cookies to enhance and personalize your experience. If you accept you agree to our full cookie policy. Learn more about our cookies.

 
Cookie settings