37 lines
1.2 KiB
Python
37 lines
1.2 KiB
Python
from flask import current_app, g
|
|
import boto3
|
|
from boto3.dynamodb.conditions import Key, Attr
|
|
import random
|
|
from dynamodb_json import json_util
|
|
|
|
|
|
def get_table(table_name):
|
|
table = getattr(g, table_name, None)
|
|
if table is None:
|
|
dynamo = boto3.resource("dynamodb", aws_access_key_id=current_app.config["AWS_ACCESS_KEY_ID"],
|
|
aws_secret_access_key=current_app.config["AWS_SECRET_ACCESS_KEY"], region_name=current_app.config["REGION_NAME"])
|
|
setattr(g, table_name, dynamo.Table(table_name))
|
|
return dynamo.Table(table_name)
|
|
return table
|
|
|
|
|
|
def get_question_count():
|
|
table = get_table("BibleQuestions")
|
|
return table.item_count
|
|
|
|
|
|
def get_question(id):
|
|
table = get_table("BibleQuestions")
|
|
response = table.get_item(Key={"id": id})
|
|
return json_util.loads(response["Item"])
|
|
|
|
|
|
def get_questions_of_difficulty(difficulty):
|
|
table = get_table("BibleQuestions")
|
|
return table.scan(FilterExpression=Attr("Difficulty").eq(difficulty))
|
|
|
|
|
|
def get_random_question_difficulty(difficulty):
|
|
questions = get_questions_of_difficulty(difficulty)
|
|
return questions["Items"][random.randint(0, questions["Count"]-1)]
|