CoCalc Shared Fileswww / cgi-bin / mfd / discard
Author: William A. Stein
1# Contact information for a person; one of the fields of a source.
2# Represents the following table in PostgreSQL:
3#
4# Column |  Type   |                     Modifiers
5#--------+---------+---------------------------------------------------
6# id     | integer | not null default nextval('"person_id_seq"'::text)
7# name   | text    |
8# email  | text    |
9# url    | text    |
10#   Unique keys: person_id_key, person_name_key
11
12class Person:
13    # load from database or create
14    def __init__(self, name):
15        query = "SELECT * from person WHERE name='%s'";
16        out = db.query(query).dictresult()
17        if len(out) == 0:
18            self.name = name
19            self.email = email
20            self.url = url
21            self.id = -1
22        else:
23            self.name = out[0]["name"]
24            self.email= out[0]["email"]
25            self.url  = out[0]["url"]
26
27    def __repr__(self):
28        return "Person: %s, %s, %s"%(self.name, self.email, self.url)
29
30    # save state of object to database when leaves scope
31    def __del__(self):
32        self.save_to_database()
33
34    def get_id(self):
35        if self.id > -1:
36            return self.id
37        values = (self.name,self.email,self.url)
38        query = "SELECT id FROM person WHERE name='%s' AND email='%s' "+\
39                "and url='%s'"%values
40        out = db.query(query).dictresult()
41        if len(out) == 0:  # create new record in database
42            insert_query = "INSERT INTO person(name, email, url) "+\
43                           "VALUES('%s','%s','%s')"%values
44            db.query(insert_query)
45            out = db.query(query).dictresult()
46        self.id=out[0]['id']
47        return self.id
48
49    def save_to_database(self):
50        id = self.get_id()
51        query = "UPDATE person SET name = '%s' WHERE id = %s;"%(self.name, id) +\
52                "UPDATE person SET email = '%s' WHERE id = %s;"%(self.email, id) +\
53                "UPDATE person SET url = '%s' WHERE id = %s;"%(self.url, id)
54        db.query(query)
55
56    def set_name(self, name):
57        self.name = name
58    def set_email(self, email):
59        self.email = email
60    def set_url(self, url):
61        self.url = url
62
63    def get_name(self):
64        return self.name
65    def get_email(self):
66        return self.email
67    def get_url(self):
68        return self.url
69
70