Search code examples
pythonhtmlmongodbflask

How to convert binary data from mongodb to string in Python properly


I have an image that is saved in mongodb as a series of bytes (see screenshot 1). enter image description here As you can this string contains an apostrophe as the first symbol and the same apostrophe at the end of the string.

Then I retrieve this field in Python and encode it via base64:

@app.route("/personal_account", methods=['GET'])
def personal_account():
    # get avatar field from database
    user = list(db.users.find({"user_id": session.get("user_id")}))[0]
    return render_template("personal_account.html",
                           username = user.get("user_name"),
                           email = user.get("email"),
                           avatar = base64.b64encode(user.get("avatar")))

Then for some reason after encoding I see that first and last apostrophes have been encoded too (see screenshot 2, b'): enter image description here

So I cannot parse the image into my html form because of this couple of apostrophes.

The question is: how can I get rid of this apostrophes in order to parse the image in binary format properly? Thank you in advance!


Solution

  • Finally I found the decision. I needed to encode bytes from mongodb to base64 first and then decode the bytestring to string.

    Thanks @Carcigenicate and @0x00 for help!

    Also this topic was very helpful in my case.

    @app.route("/personal_account", methods=['GET'])
    def personal_account():
        # get avatar field from database
        user = list(db.users.find({"user_id": session.get("user_id")}))[0]
        img_from_mongo = user.get("avatar") # <class 'bytes'>, bytestring from mongodb
        base64_bytes = base64.b64encode(img_from_mongo) # bytestring encoded in base64
        base64_str = base64_bytes.decode("utf-8") # string that is decoded from bytes object
        return render_template("personal_account.html",
                               username = user.get("user_name"),
                               email = user.get("email"),
                               bytes_line = user.get("avatar"),
                               avatar = base64_str)