-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
app.py
48 lines (40 loc) · 1.41 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
import os
from flask import Flask, render_template, request, redirect, url_for, jsonify
from flask_mysqldb import MySQL
app = Flask(__name__)
# Configure MySQL from environment variables
app.config['MYSQL_HOST'] = os.environ.get('MYSQL_HOST', 'localhost')
app.config['MYSQL_USER'] = os.environ.get('MYSQL_USER', 'default_user')
app.config['MYSQL_PASSWORD'] = os.environ.get('MYSQL_PASSWORD', 'default_password')
app.config['MYSQL_DB'] = os.environ.get('MYSQL_DB', 'default_db')
# Initialize MySQL
mysql = MySQL(app)
def init_db():
with app.app_context():
cur = mysql.connection.cursor()
cur.execute('''
CREATE TABLE IF NOT EXISTS messages (
id INT AUTO_INCREMENT PRIMARY KEY,
message TEXT
);
''')
mysql.connection.commit()
cur.close()
@app.route('/')
def hello():
cur = mysql.connection.cursor()
cur.execute('SELECT message FROM messages')
messages = cur.fetchall()
cur.close()
return render_template('index.html', messages=messages)
@app.route('/submit', methods=['POST'])
def submit():
new_message = request.form.get('new_message')
cur = mysql.connection.cursor()
cur.execute('INSERT INTO messages (message) VALUES (%s)', [new_message])
mysql.connection.commit()
cur.close()
return jsonify({'message': new_message})
if __name__ == '__main__':
init_db()
app.run(host='0.0.0.0', port=5000, debug=True)