· 5 years ago · Mar 08, 2020, 06:38 PM
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3"""
4Created on Fri Feb 28 19:36:31 2020
5
6@author: yiming
7"""
8import requests
9import sqlite3
10from html import unescape
11results_db = '__HOME__/results.db' # just come up with name of database
12TRIVIA_URL = 'https://opentdb.com/api.php?amount=1&type=boolean'
13
14# Creates database if it doesn't already exist
15def create_database():
16 conn = sqlite3.connect(results_db) # connect to that database (will create if it doesn't already exist)
17 c = conn.cursor() # move cursor into database (allows us to execute commands)
18 c.execute('''CREATE TABLE IF NOT EXISTS data_table (correct int);''') # run a CREATE TABLE command
19 conn.commit() # commit commands
20 conn.close() # close connection to database
21
22# Insert into the database given a value. Note the value should only be 0 (for incorrect) or 1 (for correct)
23def insert_into_database(val):
24 conn = sqlite3.connect(results_db)
25 c = conn.cursor()
26 c.execute('''INSERT into data_table VALUES (?);''', val)
27 conn.commit()
28 conn.close()
29
30# Look through database, return both number correct (1's) and total questions (all entries)
31def lookup_database():
32 conn = sqlite3.connect(results_db)
33 c = conn.cursor()
34 things = c.execute('''SELECT * FROM data_table;''').fetchall()
35 correct = 0
36 total = 0
37 for row in things:
38 if row[0] == 1:
39 correct += 1
40 total += 1
41 conn.commit()
42 conn.close()
43 return (correct, total)
44
45# Request handler for handling get requests from Arduino
46def request_handler(request):
47 if request.get('method') == 'GET':
48 # GET request to get a trivia question
49 if request.get('values').get('get_question'):
50 try:
51 req = requests.get(url = TRIVIA_URL)
52 data = req.json()
53 question = data.get('results')[0].get('question')
54 answer = data.get('results')[0].get('correct_answer')
55 if answer == 'True':
56 if len(question) % 2 == 1:
57 question += ' '
58 return unescape(question)
59 else:
60 if len(question) % 2 == 0:
61 question += ' '
62 return unescape(question)
63 except (ValueError,TypeError):
64 return 'Invalid request'
65 # GET request to update right/wrong record database, and also return cumulative scores
66 else:
67 data = request.get('values').get('correct')
68 if data != str(0) and data != str(1):
69 return 'Invalid request, need data to be 0 or 1'
70 else:
71 create_database()
72 insert_into_database(data)
73 res = lookup_database()
74 return 'Total - ' + 'correct: ' + str(res[0]) + ', wrong: ' + str(res[1]-res[0]) + ', score: ' + str(2*res[0]-res[1])
75 else:
76 return 'Invalid Request'