import csv, random from bottle import route, run, response """ Read questions from .csv file and keep in memory """ file_name = "Fragen.csv" with open(file_name, newline='') as csvfile: q_reader = csv.reader(csvfile) lines = list(q_reader) header, questions = lines[0], lines[1:] print(header) print(questions) @route('/question') def question(): """json/dict: Return random question. dict return value is automatically converted to JSON. """ response.set_header('Access-Control-Allow-Origin', '*') response.set_header('Access-Control-Allow-Methods', 'GET,POST') response.set_header('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin,Content-Type' num_q = len(questions) rand_id = random.randint(1, num_q) # id vs. index question = questions[rand_id-1] q_with_headers = {} for k, v in zip(header, question): q_with_headers[k] = v return q_with_headers @route('/question/') def question(id): response.set_header('Access-Control-Allow-Origin', '*') response.set_header('Access-Control-Allow-Methods', 'GET,POST') response.set_header('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin,Content-Type' question = questions[id-1] q_with_headers = {} for k, v in zip(header, question): q_with_headers[k] = v return q_with_headers if __name__ == '__main__': run(host='localhost', port=8090, reloader=True, debug=True)