"TypeError: BlobMedia content must be a byte string" when generating BlobMedia csv file

Hi @matt and @alcampopiano,

You’re right that this is a recent change. Media objects contain raw binary data, so in Python 3 the second argument to the BlobMedia() constructor should always have been bytes rather than str. Using a str will cause weird downstream breakage with non-ASCII characters, so we recently added a more helpful up-front error message.

To convert a str to bytes, you can just call .encode() on the content you’d like to create your BlobMedia object with. To take your example, @matt:

@anvil.server.callable
def create_csv():
  df = pd.DataFrame({'a': [1,2,3]})
  df_as_csv = df.to_csv(index=False)
  csv_media = anvil.BlobMedia('text/plain', df_as_csv.encode(), name='my_data.csv')
  return csv_media
3 Likes