Based on the answer from @nneonneo, here is a function that emulates the to_bytes API:
def to_bytes(n, length, endianess="big"):
h="%x" % n
s = ('0'*(len(h) % 2) + h).zfill(length*2).decode('hex')
return s if endianess == 'big' else s[::-1]