-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
170 lines (138 loc) · 7.32 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# Import Flask modules
from flask import Flask, request, render_template
from flaskext.mysql import MySQL
import os
# Create an object named app
app = Flask(__name__)
# Configure mysql database
app.config['MYSQL_DATABASE_HOST'] = os.getenv('MYSQL_DATABASE_HOST')
app.config['MYSQL_DATABASE_PASSWORD'] = os.getenv('MYSQL_PASSWORD')
app.config['MYSQL_DATABASE_DB'] = os.getenv('MYSQL_DATABASE')
app.config['MYSQL_DATABASE_USER'] = os.getenv('MYSQL_USER')
#app.config['MYSQL_DATABASE_PORT'] = 3306
mysql = MySQL()
mysql.init_app(app)
connection = mysql.connect()
connection.autocommit(True)
cursor = connection.cursor()
# Write a function named `init_todo_db` which initializes the todo db
# Create P table within sqlite db.
def init_phonebook_db():
phonebook_table = """
CREATE TABLE IF NOT EXISTS phonebook.phonebook(
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
number VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
"""
cursor.execute(phonebook_table)
# Write a function named `insert_person` which inserts person into the phonebook table in the db,
# and returns text info about result of the operation
def insert_person(name, number):
query = f"""
SELECT * FROM phonebook WHERE name like '{name.strip().lower()}';
"""
cursor.execute(query)
row = cursor.fetchone()
if row is not None:
return f'Person with name {row[1].title()} already exits.'
insert = f"""
INSERT INTO phonebook (name, number)
VALUES ('{name.strip().lower()}', '{number}');
"""
cursor.execute(insert)
result = cursor.fetchall()
return f'Person {name.strip().title()} added to Phonebook successfully'
# Write a function named `update_person` which updates the person's record in the phonebook table,
# and returns text info about result of the operation
def update_person(name, number):
query = f"""
SELECT * FROM phonebook WHERE name like '{name.strip().lower()}';
"""
cursor.execute(query)
row = cursor.fetchone()
if row is None:
return f'Person with name {name.strip().title()} does not exist.'
update = f"""
UPDATE phonebook
SET name='{row[1]}', number = '{number}'
WHERE id= {row[0]};
"""
cursor.execute(update)
return f'Phone record of {name.strip().title()} is updated successfully'
# Write a function named `delete_person` which deletes person record from the phonebook table in the db,
# and returns returns text info about result of the operation
def delete_person(name):
query = f"""
SELECT * FROM phonebook WHERE name like '{name.strip().lower()}';
"""
cursor.execute(query)
row = cursor.fetchone()
if row is None:
return f'Person with name {name.strip().title()} does not exist, no need to delete.'
delete = f"""
DELETE FROM phonebook
WHERE id= {row[0]};
"""
cursor.execute(delete)
return f'Phone record of {name.strip().title()} is deleted from the phonebook successfully'
# Write a function named `add_record` which inserts new record to the database using `GET` and `POST` methods,
# using template files named `add-update.html` given under `templates` folder
# and assign to the static route of ('add')
@app.route('/add', methods=['GET', 'POST'])
def add_record():
if request.method == 'POST':
name = request.form['username']
if name is None or name.strip() == "":
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')
elif name.isdecimal():
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')
phone_number = request.form['phonenumber']
if phone_number is None or phone_number.strip() == "":
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')
elif not phone_number.isdecimal():
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')
result = insert_person(name, phone_number)
return render_template('add-update.html', show_result=True, result=result, not_valid=False, action_name='save', developer_name='Devenes')
else:
return render_template('add-update.html', show_result=False, not_valid=False, action_name='save', developer_name='Devenes')
# Write a function named `update_record` which updates the record in the db using `GET` and `POST` methods,
# using template files named `add-update.html` given under `templates` folder
# and assign to the static route of ('update')
@app.route('/update', methods=['GET', 'POST'])
def update_record():
if request.method == 'POST':
name = request.form['username']
if name is None or name.strip() == "":
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')
phone_number = request.form['phonenumber']
if phone_number is None or phone_number.strip() == "":
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')
elif not phone_number.isdecimal():
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')
result = update_person(name, phone_number)
return render_template('add-update.html', show_result=True, result=result, not_valid=False, action_name='update', developer_name='Devenes')
else:
return render_template('add-update.html', show_result=False, not_valid=False, action_name='update', developer_name='Devenes')
# Write a function named `delete_record` which updates the record in the db using `GET` and `POST` methods,
# using template files named `delete.html` given under `templates` folder
# and assign to the static route of ('delete')
@app.route('/delete', methods=['GET', 'POST'])
def delete_record():
if request.method == 'POST':
name = request.form['username']
if name is None or name.strip() == "":
return render_template('delete.html', not_valid=True, message='Invalid input: Name can not be empty', show_result=False, developer_name='Devenes')
result = delete_person(name)
return render_template('delete.html', show_result=True, result=result, not_valid=False, developer_name='Devenes')
else:
return render_template('delete.html', show_result=False, not_valid=False, developer_name='Devenes')
@app.route('/', methods=['GET', 'POST'])
def find_records():
return render_template('index.html', show_result=False, developer_name='Devenes')
# Add a statement to run the Flask application which can be reached from any host on port 80.
if __name__ == '__main__':
init_phonebook_db()
# app.run(debug=True)
app.run(host='0.0.0.0', port=80)