Skip to content

Instantly share code, notes, and snippets.

@nvdarekar
Created April 13, 2016 07:59
Show Gist options
  • Select an option

  • Save nvdarekar/1f933893b2bdd809cab7a9c0d45a9d5e to your computer and use it in GitHub Desktop.

Select an option

Save nvdarekar/1f933893b2bdd809cab7a9c0d45a9d5e to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import transaction
from pprint import pprint
from xamcheck_utils.excel import get_worksheet_by_name_from_file
from xamcheck_utils.text import unicodify
from xamcheck_content.models.subjects import (
Class,
Subject,
ConceptTree
)
from xamcheck_content.models.meta import DBSession
from sqlalchemy import func
def get_subject_ids_for_class(subject_name, class_name):
subject_name_pattern = "%" + subject_name + "%"
try:
subjects = DBSession.query(
Subject.id
).join(
Class
).filter(
Subject.name.ilike(subject_name_pattern),
func.lower(Class.name) == class_name.lower()
).all()
except:
raise Exception("Subject not found")
subject_ids = [subject[0] for subject in subjects]
return subject_ids
def import_content_from_excel(
excel_file_contents,
ws_name,
subject_id):
min_columns = 4
min_rows = 2
chapter_name_col = 3
subtopic_name_col = 5
skill_name_col = 6
ws = get_worksheet_by_name_from_file(
excel_file_contents,
ws_name,
min_columns,
min_rows
)
for row_index in xrange(min_rows - 1, ws.nrows):
chapter_name = unicodify(
ws.cell_value(row_index, chapter_name_col))
subtopic_name = unicodify(
ws.cell_value(row_index, subtopic_name_col))
skill_name = unicodify(
ws.cell_value(row_index, skill_name_col))
chapter = ConceptTree.get_or_create(
name=chapter_name,
subject_id=subject_id,
parent_id=None)
subtopic = ConceptTree.get_or_create(
name=subtopic_name,
subject_id=subject_id,
parent_id=chapter.id)
ConceptTree.get_or_create(
name=skill_name,
subject_id=subject_id,
parent_id=subtopic.id)
if __name__ == '__main__':
subject_name = "math%NCERT"
class_name = "CLASS 7"
excel_file_path = "/tmp/maths7_8.xlsx"
ws_name = "7 maths"
subject_ids = get_subject_ids_for_class(subject_name, class_name)
if len(subject_ids) > 1:
raise Exception("More than one subject found")
subject_id = subject_ids[0]
filepath = os.path.expanduser(excel_file_path)
with open(filepath, "rb") as f:
excel_file_contents = f.read()
with transaction.manager:
import_content_from_excel(
excel_file_contents,
ws_name,
subject_id)
pprint(Subject.get_by_id(subject_id).get_nodes_as_trees(json=True))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment