-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
44 lines (37 loc) · 1.27 KB
/
server.py
File metadata and controls
44 lines (37 loc) · 1.27 KB
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
import sqlite3
import time
from flask import Flask, request, g, render_template, redirect #import the flask class
app = Flask(__name__) #create an instance of the class.
DATABASE = 'cheeps.db'
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
def db_read_cheeps():
cur = get_db().cursor()
cur.execute("SELECT * FROM cheeps")
return cur.fetchall()
def db_add_cheep(name, cheep):
cur = get_db().cursor()
t = str(time.time())
cheep_info = (name, t, cheep)
cur.execute("INSERT INTO cheeps VALUES (?, ?, ?)", cheep_info)
get_db().commit()
@app.route("/") #the route decorator. Binds a function to a url
def hello():
cheeps = db_read_cheeps()
print(cheeps)
return render_template('index.html', cheeps=cheeps)
@app.route("/api/cheep", methods=["POST"])
def receive_cheep():
print(request.form) #data sent by the form to make sure it works
db_add_cheep(request.form['name'], request.form['cheep'])
return redirect("/")
if __name__ == "__main__":
app.run(debug=True) #server will reload itself on code changes