How do you define a session?

Hey all, I am pretty new to this, so this may seem like a dumb question…

How do I define a session for a new user? My project is a robots.txt builder that is a form where you can fill out and the user agents and other inputs are stored in an app_table. The form then has a repeating panel showing all of the previous inputs (of which you can delete rows – similar to the ‘to-do’ list tutorial). Finally, you can click a button that will generate all of the unique items formatted correctly --example below of an output:


User-agent: Googlebot
Disallow: /
Allow: /images
User-agent: *
Disallow: /folder1/
User-agent: Bingbot
Disallow: /


So, how does someone make it so that it can store data in an app_table but prevent other users from being able to access the same data (I know that the BEST solution is to set up user management and have the user create a password and a login, but the app really wouldn’t warrant that). Is there a way that I can set each new user’s session as if the data tables are blank and that they would not be able to pull the data into the repeatingPanel and generate the text file unless they were the user that created it and it is in a single session?

You have this list predefined variable :

anvil.server.session (see here : Anvil | Reference)

but there is no “session id” built in. So I do this in a server module :

import uuid
...
def get_uuid():
  if "id" not in anvil.server.session:
    anvil.server.session['id']=str(uuid.uuid4())

  return anvil.server.session['id']

and i store that in the data tables (as a text field) when I need to relate data to a session. Every time I need the “session id” I call this function, which either returns it or sets it first.

Does that help?

(edit) - to expand, you would first search the data table for the uuid, updating the row if it exists or possibly creating it if not. You can see it in action in my “captcha” work-in-progress here (look at the generate captcha server function) :

2 Likes

Hi Luke, and welcome to the forum!

If you don’t want to save information between visits, do you even need to use the Data Tables? You could store the information in a local variable on the client, or in anvil.server.session on the server.

A RepeatingPanel doesn’t need database rows. You can just as easily feed it a list of dict objects stored in a variable…

(Of course, if you do want to save information between visits, David’s approach is exactly right.)

1 Like

Thank you for your help – it is working exactly how I needed it to!

1 Like