Cannot access server module '/tmp' directory

I’m trying to save some files and then add them to a zip archive. However, I could not write to the ‘/tmp’ directory, even using the Anvil example code below.

FileNotFoundError: [Errno 2] No such file or directory: ‘/tmp/my-file.txt’
The error came on the line to write:

with open("/tmp/my-file.txt", 'w') as f:

I have a free account…is that the reason possibly?

@anvil.server.callable
def write_a_file(my_string='this is a test file.'):
  with open("/tmp/my-file.txt", 'w') as f:
    f.write(my_string)
   
  with open("/tmp/my-file.txt", 'r') as f:
    contents = f.read()
    print(contents)

Any assistance would be appreciated!

Just looking at the docs here it looks as you need

to have ‘w+‘ presumably to create a new file.
This is completely untested but try this:

@anvil.server.callable 
def write_a_file(my_string='this is a test file.'):
  with open("/tmp/my-file.txt", 'w+') as f:
    f.write(my_string)

  with open("/tmp/my-file.txt", 'r') as f:
    contents = f.read() 
    print(contents)

Edit: formatted code snippet

2 Likes

Thanks for your reply. I originally tried “w+” and it didn’t work. Setting the mode to “w” will normally create a new file if it doesn’t exist. Thanks again :slightly_smiling_face:

1 Like

It looks like it’s not available on the free plan.

got the same error in basic Python 3 but no error in full python 3

I would have thought that would raise a different error?

I wonder if the documentation could have an icon added to indicate whether the examples listed work on the Free or Paid plans, or maybe an Exception raised in place of the error with the same info “This feature requires a ‘X’ plan to be used”

Or is it there and I just can’t see the wood for the trees.

2 Likes

Thank you for the confirmation.

Thank you Anvillistas, we will add a notice to the documentation to let people know that you can only access the filesystem from the Full Python environments.

The Basic Python environments are PyPy Sandboxes. That means they politely ask us for permission before making system calls, so we can keep users completely secure from one another on the same machine. It’s the magic tech that lets us provide hosted Python back-ends for free! (And we sponsored the creation of the Python 3 version.) Of course, this all means that Basic back-ends don’t have access to the filesystem. Here’s a 5-minute talk by a very enthusiastic Meredydd about how it all works.

4 Likes

What a great talk! Thanks for sharing - and @meredydd was so enthusiastic!

1 Like

A post was split to a new topic: Accessing python 3