You can write to and from files in Server Modules using Media objects.
You can also write to and from files using Python’s
To write to a temporary file, use
anvil.media.TempFile(media_object) in a
If you’re using a Python library that wants you to pass it a filename, this can be really useful for
writing some data into a file, then passing the
file_name to the library you’re using.
import anvil.media @anvil.server.callable def write_media_to_file(media_object): with anvil.media.TempFile(media_object) as file_name: # Now there is a file in the filesystem containing the contents of media_object. # The file_name variable is a string of its full path.
The file is written to the filesystem as soon as the
with block begins.
The file will be deleted when the
with block exits.
You can use Python’s
open to write Media Objects to your filesystem, and read them back.
def write_a_media_object(): media_object = anvil.BlobMedia('text/plain', 'Hello, world', name='hello_world.txt') with open('/tmp/hello_world.txt', 'w+') as f: # Write the string contents of the media object to 'tmp/my-file.txt' f.write(media_object.get_bytes().decode())
def read_a_media_object(): with open('/tmp/hello_world.txt', 'r') as f: contents = f.read() print(contents)
To read from an existing file, use
anvil.media.from_file(file_name, [content_type], [name]).
import anvil.media @anvil.server.callable def read_from_file(file_name): media_object = anvil.media.from_file(file_name, [content_type], [name]) return media_object
This creates a Media object with the contents of the file.
You can also use Python’s
open to read and write files as normal. Your
filesystem is your own; other users do not have access to it.
def write_a_file(my_string): with open('/tmp/my-file.txt', 'w+') as f: f.write(my_string)
def read_a_file(): with open('/tmp/my-file.txt', 'r') as f: contents = f.read() print(contents)