Skip to content

Commit 1226bae

Browse files
committed
💫 Create Python app
1 parent ec193bd commit 1226bae

File tree

1 file changed

+172
-0
lines changed

1 file changed

+172
-0
lines changed

phonebook-app.py

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
# Import Flask modules
2+
from flask import Flask, request, render_template
3+
from flaskext.mysql import MySQL
4+
5+
# Create an object named app
6+
app = Flask(__name__)
7+
8+
# Configure mysql database
9+
app.config['MYSQL_DATABASE_HOST'] = 'database'
10+
app.config['MYSQL_DATABASE_USER'] = 'admin'
11+
app.config['MYSQL_DATABASE_PASSWORD'] = 'Devenes_123'
12+
app.config['MYSQL_DATABASE_DB'] = 'phonebook_db'
13+
app.config['MYSQL_DATABASE_PORT'] = 3306
14+
mysql = MySQL()
15+
mysql.init_app(app)
16+
connection = mysql.connect()
17+
connection.autocommit(True)
18+
cursor = connection.cursor()
19+
20+
21+
# Write a function named `find_persons` which finds persons' record using the keyword from the phonebook table in the db,
22+
# and returns result as list of dictionary
23+
# `[{'id': 1, 'name':'XXXX', 'number': 'XXXXXX'}]`.
24+
def find_persons(keyword):
25+
query = f"""
26+
SELECT * FROM phonebook WHERE name like '%{keyword.strip().lower()}%';
27+
"""
28+
cursor.execute(query)
29+
result = cursor.fetchall()
30+
persons = [{'id': row[0], 'name':row[1].strip().title(), 'number':row[2]}
31+
for row in result]
32+
if len(persons) == 0:
33+
persons = [{'name': 'No Result', 'number': 'No Result'}]
34+
return persons
35+
36+
37+
# Write a function named `insert_person` which inserts person into the phonebook table in the db,
38+
# and returns text info about result of the operation
39+
def insert_person(name, number):
40+
query = f"""
41+
SELECT * FROM phonebook WHERE name like '{name.strip().lower()}';
42+
"""
43+
cursor.execute(query)
44+
row = cursor.fetchone()
45+
if row is not None:
46+
return f'Person with name {row[1].title()} already exits.'
47+
48+
insert = f"""
49+
INSERT INTO phonebook (name, number)
50+
VALUES ('{name.strip().lower()}', '{number}');
51+
"""
52+
cursor.execute(insert)
53+
result = cursor.fetchall()
54+
return f'Person {name.strip().title()} added to Phonebook successfully'
55+
56+
57+
# Write a function named `update_person` which updates the person's record in the phonebook table,
58+
# and returns text info about result of the operation
59+
def update_person(name, number):
60+
query = f"""
61+
SELECT * FROM phonebook WHERE name like '{name.strip().lower()}';
62+
"""
63+
cursor.execute(query)
64+
row = cursor.fetchone()
65+
if row is None:
66+
return f'Person with name {name.strip().title()} does not exist.'
67+
68+
update = f"""
69+
UPDATE phonebook
70+
SET name='{row[1]}', number = '{number}'
71+
WHERE id= {row[0]};
72+
"""
73+
cursor.execute(update)
74+
75+
return f'Phone record of {name.strip().title()} is updated successfully'
76+
77+
78+
# Write a function named `delete_person` which deletes person record from the phonebook table in the db,
79+
# and returns returns text info about result of the operation
80+
def delete_person(name):
81+
query = f"""
82+
SELECT * FROM phonebook WHERE name like '{name.strip().lower()}';
83+
"""
84+
cursor.execute(query)
85+
row = cursor.fetchone()
86+
if row is None:
87+
return f'Person with name {name.strip().title()} does not exist, no need to delete.'
88+
89+
delete = f"""
90+
DELETE FROM phonebook
91+
WHERE id= {row[0]};
92+
"""
93+
cursor.execute(delete)
94+
return f'Phone record of {name.strip().title()} is deleted from the phonebook successfully'
95+
96+
97+
# Write a function named `find_records` which finds phone records by keyword using `GET` and `POST` methods,
98+
# using template files named `index.html` given under `templates` folder
99+
# and assign to the static route of ('/')
100+
@app.route('/', methods=['GET', 'POST'])
101+
def find_records():
102+
if request.method == 'POST':
103+
keyword = request.form['username']
104+
persons = find_persons(keyword)
105+
return render_template('index.html', persons=persons, keyword=keyword, show_result=True, developer_name='Devenes')
106+
else:
107+
return render_template('index.html', show_result=False, developer_name='Devenes')
108+
109+
110+
# Write a function named `add_record` which inserts new record to the database using `GET` and `POST` methods,
111+
# using template files named `add-update.html` given under `templates` folder
112+
# and assign to the static route of ('add')
113+
@app.route('/add', methods=['GET', 'POST'])
114+
def add_record():
115+
if request.method == 'POST':
116+
name = request.form['username']
117+
if name is None or name.strip() == "":
118+
return render_template('add-update.html', not_valid=True, message='Invalid input: Name can not be empty', show_result=False, action_name='save', developer_name='Devenes')
119+
elif name.isdecimal():
120+
return render_template('add-update.html', not_valid=True, message='Invalid input: Name of person should be text', show_result=False, action_name='save', developer_name='Devenes')
121+
122+
phone_number = request.form['phonenumber']
123+
if phone_number is None or phone_number.strip() == "":
124+
return render_template('add-update.html', not_valid=True, message='Invalid input: Phone number can not be empty', show_result=False, action_name='save', developer_name='Devenes')
125+
elif not phone_number.isdecimal():
126+
return render_template('add-update.html', not_valid=True, message='Invalid input: Phone number should be in numeric format', show_result=False, action_name='save', developer_name='Devenes')
127+
128+
result = insert_person(name, phone_number)
129+
return render_template('add-update.html', show_result=True, result=result, not_valid=False, action_name='save', developer_name='Devenes')
130+
else:
131+
return render_template('add-update.html', show_result=False, not_valid=False, action_name='save', developer_name='Devenes')
132+
133+
134+
# Write a function named `update_record` which updates the record in the db using `GET` and `POST` methods,
135+
# using template files named `add-update.html` given under `templates` folder
136+
# and assign to the static route of ('update')
137+
@app.route('/update', methods=['GET', 'POST'])
138+
def update_record():
139+
if request.method == 'POST':
140+
name = request.form['username']
141+
if name is None or name.strip() == "":
142+
return render_template('add-update.html', not_valid=True, message='Invalid input: Name can not be empty', show_result=False, action_name='update', developer_name='Devenes')
143+
phone_number = request.form['phonenumber']
144+
if phone_number is None or phone_number.strip() == "":
145+
return render_template('add-update.html', not_valid=True, message='Invalid input: Phone number can not be empty', show_result=False, action_name='update', developer_name='Devenes')
146+
elif not phone_number.isdecimal():
147+
return render_template('add-update.html', not_valid=True, message='Invalid input: Phone number should be in numeric format', show_result=False, action_name='update', developer_name='Devenes')
148+
149+
result = update_person(name, phone_number)
150+
return render_template('add-update.html', show_result=True, result=result, not_valid=False, action_name='update', developer_name='Devenes')
151+
else:
152+
return render_template('add-update.html', show_result=False, not_valid=False, action_name='update', developer_name='Devenes')
153+
154+
155+
# Write a function named `delete_record` which updates the record in the db using `GET` and `POST` methods,
156+
# using template files named `delete.html` given under `templates` folder
157+
# and assign to the static route of ('delete')
158+
@app.route('/delete', methods=['GET', 'POST'])
159+
def delete_record():
160+
if request.method == 'POST':
161+
name = request.form['username']
162+
if name is None or name.strip() == "":
163+
return render_template('delete.html', not_valid=True, message='Invalid input: Name can not be empty', show_result=False, developer_name='Devenes')
164+
result = delete_person(name)
165+
return render_template('delete.html', show_result=True, result=result, not_valid=False, developer_name='Devenes')
166+
else:
167+
return render_template('delete.html', show_result=False, not_valid=False, developer_name='Devenes')
168+
169+
170+
# Add a statement to run the Flask application which can be reached from any host on port 80.
171+
if __name__ == '__main__':
172+
app.run(host='0.0.0.0', port=80)

0 commit comments

Comments
 (0)