Python3.6.4中Base64编码报错:需类字节对象问题求助
Hey there, let's get this base64 encoding issue sorted out for you! That error you're seeing—TypeError: memory view: a byte like object is required—is super common when working with Python 3, and it all comes down to one key difference from older Python versions: Python 3 strictly separates Unicode strings and byte objects, and all base64 functions require byte input to work correctly.
Let's Break Down Your Original Code
Your original line was:
auth_encoded = base64.encodestring('%s:%s' % (user, password))[:-1]
In Python 3, '%s:%s' % (user, password) creates a Unicode string, not a byte object. base64.encodestring() (which is actually an alias for base64.encodebytes() and is deprecated in favor of b64encode()) expects bytes as input, hence the error you ran into.
Why Your Previous Fixes Didn't Work
Let's walk through each attempt to spot the gaps:
- First fix:
base64.b64encode(base64.b64decode('%s:%s' % (user, password)))
You're passing a Unicode string tob64decode()first, which also requires bytes. This would throw the same type error before even getting to the encode step. - Second fix:
base64.b64encode(bytes('%s:%s' % (user, password)))
Thebytes()constructor in Python 3 needs an encoding parameter when converting a string (e.g.,bytes(auth_str, 'utf-8')). Without it, you'll hit another TypeError because it doesn't know how to translate the Unicode string into bytes. - Third fix:
This is closer—you did convert to bytes! Butauth_s = urllib.parse.unquote(('%s:%s' % (user, password))) auth_bytes = auth_s.encode() encoded_bytes = base64.encodestring(auth_bytes)encodestring()returns a byte object, so if you needed a string output you'd have to decode it. Also,encodestring()is deprecated, so usingb64encode()is better practice for clarity and future compatibility.
The Correct Solution
Here's the clean, Python 3-friendly way to handle this:
import base64 # 1. Create the auth string (Unicode format) auth_string = f"{user}:{password}" # F-strings work perfectly in Python 3.6+ # 2. Convert the string to bytes using UTF-8 encoding auth_bytes = auth_string.encode('utf-8') # 3. Base64 encode the byte object encoded_bytes = base64.b64encode(auth_bytes) # 4. (Optional) Convert back to a string if you need text-format output auth_encoded = encoded_bytes.decode('utf-8')
If you prefer a more concise one-liner:
auth_encoded = base64.b64encode(f"{user}:{password}".encode('utf-8')).decode('utf-8')
Key Takeaway
Always keep this in mind for Python 3: any function dealing with binary data (like base64 encoding, reading/writing binary files, or network requests) requires byte objects, not Unicode strings. Use str.encode('utf-8') to convert strings to bytes, and bytes.decode('utf-8') to convert back when you need a text format.
内容的提问来源于stack exchange,提问作者Talha Khan

