· 8 years ago · Feb 18, 2018, 05:02 AM
1from flask import Flask, render_template, request, Markup
2import sqlite3 as sql
3import os
4
5# seems to be necessary on windows??
6DATABASE = os.path.join(os.path.dirname(__file__), 'db.sqlite')
7
8app = Flask(__name__)
9
10# create db if necessary
11conn = sql.connect(DATABASE)
12conn.execute('CREATE TABLE IF NOT EXISTS conv (input TEXT, output TEXT)')
13conn.close()
14
15# Default / starting msg
16last_message = "Hallo"
17
18teaching_mode = False
19
20# this is to fill in when answer unknown
21error = "Ich weiss nicht was antworten auf: "
22
23
24def get_table():
25 """
26 Create HTML table from database
27 :return: HTML TABLE (str)
28 """
29 c = sql.connect(DATABASE)
30 cur = c.cursor()
31 cur.execute("SELECT * FROM conv")
32 data = cur.fetchall()
33 c.close()
34
35 snippet_list_string = '<table style="width:100%" border= "1">'
36
37 for key, value in data:
38 snippet_list_string += f'<tr><td>{key}</td><td>{value}</td></tr> '
39
40 snippet_list_string += '</table>'
41
42 return snippet_list_string
43
44
45def get_antwort(botschaft):
46 """
47 Search for $botschaft in DB and return response or error
48 :param botschaft:
49 :return:
50 """
51 # DB connection
52 con = sql.connect(DATABASE)
53 cur = con.cursor()
54
55 cur.execute("SELECT output FROM conv WHERE input=?", (botschaft,))
56
57 print('Getting answer')
58
59 antwort = cur.fetchone()
60
61 con.close()
62
63 # antwort is a one-element tuple if $botschaft is in db,
64 # antwort is None otherwise
65
66 if antwort:
67 return antwort[0]
68 else:
69 return error + botschaft
70
71
72def add_antwort(botschaft, bessere_antwort):
73 """
74 Insert new question and its answer to db
75 :param botschaft:
76 :param bessere_antwort:
77 :return:
78 """
79 try:
80 with sql.connect(DATABASE) as con: # insert question and corresponding answer
81 cur = con.cursor()
82 cur.execute("INSERT INTO conv (input,output) VALUES (?,?)", (botschaft, bessere_antwort))
83 con.commit()
84 print("Conversation successfully added")
85 except:
86 con.rollback()
87 print("error in insert operation")
88
89 finally:
90 con.close()
91
92
93@app.route('/')
94def first_call():
95 last_message = "Hallo"
96 return render_template('main.html', log=last_message, function="Antworten", snippet_list=Markup(get_table()))
97
98
99@app.route('/', methods=['POST'])
100def response():
101 response = request.form.get('response')
102 response = response.replace("?", "").replace("!", "").replace(".", "").lower()
103 global last_message
104 global teaching_mode
105
106 # Nachdem die bessere Antwort gegeben wurde
107 if teaching_mode:
108 add_antwort(last_message.replace(error, ""), response) # Zweitletztes Element, da letztes die Fehlermeldung ist
109 last_message = response
110
111 else:
112 last_message = get_antwort(response)
113
114 # Bevor die bessere Antwort gegeben wurde
115 if last_message == error + response:
116 func = "Lehren"
117 teaching_mode = True
118 else:
119 func = "Antworten"
120 teaching_mode = False
121
122 return render_template('main.html', log=Markup('<i>' + last_message + '</i>'), function=func,
123 snippet_list=Markup(get_table()))
124
125
126if __name__ == "__main__":
127 app.run(debug=True, host='0.0.0.0', port=80)
128 # Note: Running on #80 requires root