2

I have defined this class:

class User():
 def __init__(self, ip, update, priority):
    self.ip = ip
    self.update = update
    self.priority = priority

I work with a Socket and every time one client is connect I create an User object. I would like to save it somewhere and then be able to process its data, meaning read the file where it's saved. I don't know how to do that. I tried using a txt file but with the fields of the class User is to complicated and I would also like to have something more dynamic, like

add(user), isPresent(user), overwrite(user)

What is the best solution for my case?

4
  • either connect to a database or use pickle and put your info in a dictionary that you can save and read to update Commented Nov 19, 2015 at 14:53
  • Do you have any example using a database? Commented Nov 19, 2015 at 14:57
  • not really - that is more complicated but there are example on-line, try google "python database" Commented Nov 19, 2015 at 15:00
  • 1
    There is very complete answer here. Commented Feb 12, 2021 at 13:38

1 Answer 1

1

If your User class is really that simple, you can use Pickle:

(both Python 2 and 3 links included).

 u = User(127.0.0.1, "foo", "bar")
 pickle.dumps(u)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. What does it happen if I save twice the same object? There will be only one or two entities?
@m.ridolfi - as far as I know, Pickle should be idempotent. So saving the same object multiple times will have the same result. Now, of course, you have to pick where to save the object (a text file, to a database, whatever), so if you're asking can you physically save the same object twice, that's entirely up to you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.