Using non python files with Anvil

Hi,
I am trying to get my head around how some things work in Anvil and hope that some kind soul can help me.

I have some fairly large JSON objects which my server code uses as templates when posting data to another service - parts of the JSON object are replaced by data pulled from Anvil data tables.

This works fine when I have the JSON object defined as a string within my server code but it makes that code very long and difficult to read.

Is it possible to store these files as templates within Anvil?

Thanks

James

By the way I am currently using the free plan - is this something that requires a paid version?

No, there are two ways to store files in an Anvil app, and neither one requires a paid plan.

  1. In the app’s Assets folder. This is appropriate when the files are few, and do not change very often. See Adding your own asset files.
  2. In a database table. This is appropriate when files are many, or they change frequently, and automated updates are important. See Column types. Text is good for text of any form. SimpleObject is specialized for storing JSON, and converts values to and from native Python values (dicts, lists, strs, etc.) Media is best for binary data.
1 Like

Thank you. I had noticed the Assets feature but assumed it was limited to html/css/javascript.

The files are going to be pretty static so this seems easier than the database option.

I will try them both and see how I get on. Thanks for taking the time to look at my question :smiley:

“Assets” has built-in editors for the common web file formats. But they’ve been used for other file types.

Hi,
I have added a text file to the app’s Assets but cannot seem to access it from my server code.

Some sample code is shown below.

import anvil.server

@anvil.server.http_endpoint("/users/:id")
def get_user(id):
  ip = anvil.server.request.remote_address
 
  with open('/theme/list.txt','r') as file:
     listStr = file.read()
  print(listStr)
  
  return f"You requested user {id} from IP {ip}"

I have tried everything I can think of for the path to the list.txt file but cannot seem to load it.

Can assets be access in server code? The Files in Server Modules section of Anvil Docs | Files, Media Objects and Binary Data says:

You can read and write to/from the filesystem in Server Modules just as you would in any Python environment. Your filesystem is your own; other users do not have access to it.

Writing to the filesystem requires an Individual Plan or higher.

Sorry I can see that I was not specific about wanting to access files from server code in my original query.

This refers to a separate, temporary file system that exists during execution of a server-side function.

Judging from examples found elsewhere on the Forum, try /_/theme/list.txt . That, or things like it, work in Client code, and may also work Server-side.