Using same code client- and server side

Hi,
apologies if this is obvious for experienced python coders, but:

Is there a way to use the same code on both client and server side without copy & pasting?

For example, in my code I will use a translation dictionary between German and English for some terminology that needs to be used by both client- and server-side code.
The dictionary will only be set/changed at design time, so I am not talking about client- and server code making changes to the same data at runtime, I just wonder if there is a way to avoid basically having two separate files which I manually have to keep identical…

Thank you very much for your help!

All your client code is also available to be imported in your server modules.

The portable classes docs have examples of that being used:

2 Likes

@owen.campbell , great thank you!
As I said, in my use case there would be no changes to the contents at runtime, so would this solution ensure that the client code reads the data from the server only once during a session? Obviously I wouldn’t want a German<->English dictionary to be sent forth and back between client and server unnecessarily…
Sorry if this is obvious from the documentation you linked to, but the part about serialization goes a bit over my head at this point, so I just want to make sure I’m not unnecessarily sending data forth and back between client and server…

Btw, thank you so much for your work on anvil extras. I admit that there are some parts that I probably don’t even fully understand fully, but the parts that I get already make my life much easier. In fact, having slider with two handles will allow me to give my user interface some totally new functionality. Thank you!!

Your original question seemed to be asking about using code on both client and server side. The answer to that is yes, you can - if you write that code in a client module, you can import it into a server module.

You now seem to be asking about passing data between server and client, which is a completely different matter.

Glad to hear you like anvil extras!

Yes, you are correct, I was a bit unclear there, sorry! Anyway, I think your answer above has given me ideas for how I could do either. Thanks!

1 Like

Perhaps Owen’s mention of the portable classes confused you.

The answer to your question was his first phrase:

That’s all you need: create a client module, and you can import it both on server and client side.

3 Likes

Thanks, @stefano.menci!