Data Files are static files you can attach to your app that are available in your Server Modules.
Follow this quickstart to load files into your app, access their contents and properties, and let the user of your app edit the text file’s contents.
Log in to Anvil and click ‘New Blank App’. Choose the Material Design theme.
Click the + button in the Sidebar Menu, and select Data Files:
Upload a text file for your users to edit by clicking the Upload button and selecting a text file.
For this example, I’m using a simple text file that contains the string “Hello, World!”.
Once the file is uploaded, you can rename and delete it in this interface.
Data Files storage
Data Files are stored in your app’s database. When you add the Data Files service to your app, Anvil creates a
Files table where your files are stored as Media objects.
You access your files in code using the
data API in a Server Module. You get the path to the file on disk from
data_files['filename']. That’s a path to the file on disk, where your Server Modules are running. You can get individual files or directories.
from anvil.files import data_files @anvil.server.callable def return_text_from_file(): # Read the contents of a file with open(data_files['test.txt']) as f: text = f.read() return text
@anvil.server.callable decorator means this function can be called from the client code.
Now you have a server function to interact with your file, you can call that function from the client side to return the file’s data to your user. In the App Browser, open one of your app’s forms and select the code view. In the
__init__ method, you can call the server function you created earlier with
anvil.server.call('return_text_from_file'). Then you can print the file’s text.
class Form1(Form1Template): def __init__(self, **properties): # Set Form properties and Data Bindings. self.init_components(**properties) # Any code you write here will run when the form opens. # Call the server function which returns the text from your text file file_text = anvil.server.call('return_text_from_file') # Print what's returned print(file_text)
Finally, run your app. In the app logs, you will see the contents of your text file printed.
Click on the button below to clone a finished version of this app into your account.
Want another quickstart?
Every quickstart is on the Quickstarts page.