0

I got stuck on an error which I didn't have when I've done something similar in python 2.

Here is the code:

def computeSha(self,reqFile):
    filesize_bytes = os.path.getsize(reqFile)

    s = sha1()
    s.update(("blob %u\0" % filesize_bytes).encode('utf-8'))

    with open(reqFile, 'rb') as f:
        s.update(f.read())

    s = s.hexdigest()
    print ("here is the sha: " + s)
    return s

def _sendSha(self, component_id):
    component_path = db_connector.get_design_path(component_id)
    sha = self.computeSha(component_path)

    self.connection.send(self._adjustLength(len(sha)))
    self.connection.sendall(data)

The error appears here: self.connection.send(self._adjustLength(len(sha)))

Here is the code for adjustLength:

def _adjustLength(self, length):
    #max size is 8 bytes long
    length = str(length)
    if DEBUG:
        print("_adjustLength before:" + length)
    while len(length) < 8:
        length = "0"+length
    length = length+"\n"
    if DEBUG:
        print("_adjustLength after:" + length)
    return length
9
  • Where are you setting self.connection? Commented Aug 13, 2015 at 12:54
  • Please include the error you're asking about in the question. By that I mean the full traceback. Commented Aug 13, 2015 at 12:57
  • I think we're going to need the code for self._adjustLength(). Commented Aug 13, 2015 at 12:58
  • 1
    But generally, this looks like a bytes versus unicode issue. Commented Aug 13, 2015 at 12:58
  • 1
    Try replacing self.connection.send(self._adjustLength(len(sha))) with self.connection.send(self._adjustLength(len(sha)).encode()). Commented Aug 13, 2015 at 13:04

1 Answer 1

2

Replace this:

self.connection.send(self._adjustLength(len(sha)))

with this:

self.connection.send(self._adjustLength(len(sha)).encode())

In Python 3, unicode strings are now the default. Sockets expect byte strings, so you have to convert the unicode strings to byte strings. You do that with .encode().

I am glossing over a bit (a lot) that's not directly relevant to the question. Ned Batchelder's Unipain talk is a good resource though.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.