def create_quiz_thread(title, desc, results, options, user_profile, new_id):
    items = []
    tags = []
    error = None
    searchable = 1
    script_results = {}

    st = time.monotonic()
    try:
        items, tags = process_items(results)
        tags = str(','.join(tags))
        #print(tags)
        email_name = options.get('required', 0x02)
        searchable = options.get('searchable', searchable)
        options = {
            'email': email_name & 0x01,
            'name': email_name & 0x02,
            'show_correct': options.get('show_correct', 0)
        }

        credentials = GoogleCredentials().get_credential()
        params = [title, desc, user_profile, items, options]
        socket.setdefaulttimeout(180)
        script_results = run_app_script(credentials,
                                        function_name='createQuiz',
                                        params=params)
        metadata = script_results.get('metadata', {})
        folder = metadata.get('folder_name')
        form_id = metadata.get('id')
        if form_id and folder:
            params = [form_id, folder]
            run_app_script(credentials,
                           function_name='moveFiles',
                           params=params)
    except Exception as exc:
        logger.error("Quiz creation App Script exception: " + str(exc))
        error = str(exc)

    et = time.monotonic() - st

    # insert/update in DB
    try:
        metadata_quiz = script_results.get('metadata', {})
        metadata_quiz['elapsed'] = et
        if error:
            metadata_quiz['error'] = error
        # user_profile = results.get('user_profile', {})
        values = (new_id, metadata_quiz.get('id'), title, desc,
                  json.dumps(metadata_quiz,
                             indent=4), 1, metadata_quiz.get('count_items'),
                  metadata_quiz.get('total_points'), json.dumps(items,
                                                                indent=4),
                  metadata_quiz.get('published_url'),
                  json.dumps(user_profile,
                             indent=4), user_profile.get('email'), tags,
                  str(searchable))
        # print("****", values)
        connect_and_execute(insert_sqls[2], values)
    except Exception as exc:
        logger.error("error", exc)
def create_quiz_form_db(json_data, sql=None):

    new_id = ''
    try:
        max_id = connect_and_query("select max(id) as max_id from exams")
        new_id = int(max_id[0].get("max_id")) + 1
        title = json_data.get('quiz_name')
        desc = json_data.get('quiz_description', '')
        ids = json_data.get('item_ids')
        user_profile = json_data.get('user_profile', {})
        options = json_data.get('options', {})
        # create exam in DB
        values = (str(new_id), title, desc)
        connect_and_execute(insert_sqls[3], values)

        # get items
        if not sql:
            sql = queries[11].format(','.join(map(str, ids)))
        results = connect_and_query(sql)

        # do actual creation in a thread
        if json_data:
            thread = threading.Thread(target=create_quiz_thread,
                                      args=(title, desc, results, options,
                                            user_profile, new_id))
            thread.start()

        return {"quiz": {'quiz_name': title, 'exam_id': new_id}}

    except Exception as exc:
        logger.error("Quiz creation DB exception: " + str(exc))
        return {"quiz": {}, 'error': str(exc)}
예제 #3
0
def create_quiz(subject='Islam', topic=None):
    q = queries[7]
    sql = q.format(subject)
    if topic:
        sql = queries[8].format(subject, topic)

    results = connect_and_execute(sql)
    # print(json.dumps(results, indent=4))
    items = process_items(results)
    user = json.loads(results[0]['user_profile'])
    pt = "We are compiling the results for 25 Quizzes. " \
         "Please complete any missed ones before the 29th of Ramadan.\n\n" \
         "We are very grateful for your overwhelming response, " \
         "support and feedback to our daily Ramadan quizzes. " \
         "Ramadan will shortly be over but our striving to gain knowledge " \
         "should continue. We will soon be introducing a feature to allow " \
         "you to contribute your own questions and create your own quizzes. " \
         "Please look out for more updates on this soon."

    creds = GoogleCredentials().get_credential()
    params = [
        'Ramadan 2020 Quiz Review 4',
        "All " + topic + " Questions (" + str(len(results)) + "). "
        "See all quizzes here: http://muslimscholars.info/quiz/\n\n" + pt,
        user, items, 0
    ]
    return run_app_script(creds, function_name='createQuiz', params=params)
예제 #4
0
def create_quiz_form_db(json_data):
    title = json_data.get('quiz_name')
    desc = json_data.get('quiz_description')
    ids = json_data.get('item_ids')
    user_profile = json_data.get('user_profile')

    # get items from list of ids
    sql = queries[11].format(','.join(map(str, ids)))
    results = connect_and_execute(sql)
    items = process_items(results)

    creds = GoogleCredentials().get_credential()
    params = [title, desc, user_profile, items, 0]
    results = run_app_script(creds, function_name='createQuiz', params=params)
    # TODO: save in DB

    return {"quiz": results}
예제 #5
0
def get_items_db(json_data):
    subject = json_data.get('subject')
    topic = json_data.get('topic')
    limit = json_data.get('limit', 50)
    sql = queries[9].format(subject, limit)
    if topic:
        sql = queries[10].format(subject, topic, limit)
    results = connect_and_execute(sql)
    for result in results:
        result['choices'] = json.loads(result['choices'])
        try:
            result['topic'] = json.loads(result['topic'])
            result['sub_topics'] = json.loads(result['sub_topics'])
        except:
            pass
        result['answer'] = json.loads(result['answer'])

    return {'items': results, 'total_items': len(results)}
예제 #6
0
def insert_item(item_data):
    sql = insert_sqls[0]
    sql2 = insert_sqls[1]

    tags = item_data.get('tags')
    private = tags.get('privacy', 0)

    # Getting choices and answer
    item_choices = item_data.get('item_choices', [])
    choice_list = []
    answer_list = []
    for i in item_choices:
        choice_list.append(i.get('choice', ''))
        if i.get('correct') == 1:
            answer_list.append(i.get('choice'))
    choices = json.dumps(choice_list, indent=4)
    answers = json.dumps(answer_list, indent=4)

    user_profile = item_data.get('user_profile', {})

    # Getting metadata
    metadata = json.dumps(item_data, indent=4)

    # Getting type info
    item_type = get_type_id(tags.get('item_type'))

    # Getting subject, topic, and hierarchy info
    subject_list = get_subjects()

    paths = tags.get('paths')
    subject = tags.get('subject')
    subject_id = None
    topic = None
    topic_id = None
    sub_topics = None
    sub_ids = None
    if paths is not None:
        topic = {}
        topic_id = {}
        sub_topics = {}
        sub_ids = {}
        for sub in subject_list:
            if sub.get('label') == subject:
                subject_id = sub.get('subject_id')
                break

        index = 0
        for path in paths:
            curr_topic = None
            curr_topic_id = None
            curr_sub_topics = None
            curr_sub_ids = None
            path = path.replace('children.', '')
            split_path = path.split('.')
            del split_path[0]
            if split_path:
                curr_topic_id = int(split_path[len(split_path)-1])
                del split_path[len(split_path)-1]
            if split_path:
                curr_sub_ids = list(map(int, split_path))

            for i in subject_list:
                if i.get('subject_id') == subject_id:
                    if curr_sub_ids:
                        curr_sub_topics = []
                        children = i.get('children')
                        for j in curr_sub_ids:
                            for k in children:
                                if j == children.index(k):
                                    child = children[j]
                                    curr_sub_topics.append(child.get('label'))
                                    children = child.get('children')
                                    break
                        for j in children:
                            if curr_topic_id == children.index(j):
                                curr_topic = j.get('label')
                    elif curr_topic_id:
                        children = i.get('children')
                        for j in children:
                            if curr_topic_id == children.index(j):
                                curr_topic = j.get('label')
                                break
                    break

            topic[index] = curr_topic
            topic_id[index] = curr_topic_id
            sub_topics[index] = curr_sub_topics
            sub_ids[index] = curr_sub_ids
            index += 1

        topic = json.dumps(topic)
        topic_id = json.dumps(topic_id)
        sub_topics = json.dumps(sub_topics)
        sub_ids = json.dumps(sub_ids)

    values = (tags.get('id', ''), tags.get('item_text', ''),
              subject, subject_id, topic,
              topic_id, sub_topics, sub_ids, item_type,
              metadata, choices, answers)

    values2 = (tags.get('id', ''), tags.get('item_text', ''),
               subject, subject_id, topic,
               topic_id, sub_topics, sub_ids, item_type,
               metadata, json.dumps(item_choices, indent=4), answers,
               json.dumps(user_profile, indent=4),
               user_profile.get('email'), private
               )

    resp = connect_and_execute(sql2, values2)
    resp = connect_and_execute(sql, values)
    return {'response': resp}