当前位置: 首页>>代码示例>>Python>>正文


Python lib.DB类代码示例

本文整理汇总了Python中oasis.lib.DB的典型用法代码示例。如果您正苦于以下问题:Python DB类的具体用法?Python DB怎么用?Python DB使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了DB类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: remark_exam

def remark_exam(exam, student):
    """Re-mark the exam using the latest marking. """
    qtemplates = Exams.get_qts(exam)
    examtotal = 0.0
    end = Exams.get_mark_time(exam, student)
    for qtemplate in qtemplates:
        question = DB.get_exam_q_by_qt_student(exam, qtemplate, student)
        answers = DB.get_q_guesses_before_time(question, end)
        try:
            marks = mark_q(question, answers)
        except OaMarkerError:
            L.warn("Marker Error, question %d while re-marking exam %s for student %s!" % (question, exam, student))
            marks = {}
        parts = [int(var[1:]) for var in marks.keys() if re.search("^A([0-9]+)$", var) > 0]
        parts.sort()
        total = 0.0
        for part in parts:
            if marks['C%d' % part] == 'Correct':
                marks['C%d' % part] = "<b><font color='darkgreen'>Correct</font></b>"
            try:
                mark = float(marks['M%d' % part])
            except (ValueError, TypeError, KeyError):
                mark = 0
            total += mark
        DB.update_q_score(question, total)
        #        OaDB.setQuestionStatus(question, 3)    # 3 = marked
        examtotal += total
    Exams.save_score(exam, student, examtotal)
    return examtotal
开发者ID:tkanesh,项目名称:oasisqe,代码行数:29,代码来源:General.py

示例2: render_q_html

def render_q_html(q_id, readonly=False):
    """ Fetch the question html and get it ready for display - replacing
        links with appropriate targets and filling in form details."""
    try:
        q_id = int(q_id)
        assert q_id > 0
    except (ValueError, TypeError, AssertionError):
        log(WARN,
            "renderQuestionHTML(%s,%s) called with bad qid?" % (q_id, readonly))
    qt_id = DB.get_q_parent(q_id)
    try:
        qt_id = int(qt_id)
        assert qt_id > 0
    except (ValueError, TypeError, AssertionError):
        log(WARN,
            "renderQuestionHTML(%s,%s), getparent failed? " % (q_id, readonly))
    variation = DB.get_q_variation(q_id)
    version = DB.get_q_version(q_id)
    data = DB.get_q_att(qt_id, "qtemplate.html", variation, version)
    if not data:
        log(WARN,
            "Unable to retrieve qtemplate for q_id: %s" % q_id)
        return "QuestionError"
    try:
        out = unicode(data, "utf-8")
    except UnicodeDecodeError:
        try:
            out = unicode(DB.get_q_att(qt_id, "qtemplate.html", variation, version),
                          "latin-1")
        except UnicodeDecodeError, err:
            log(ERROR,
                "unicode error decoding qtemplate for q_id %s: %s" % (q_id, err))
            raise
开发者ID:jamesdoherty,项目名称:oasisqe,代码行数:33,代码来源:General.py

示例3: exam_edit_submit

def exam_edit_submit(request, user_id, cid, exam_id):
    """ Accept the submitted exam edit/create form.
        If exam_id is not provided, create a new one.
    """

    # TODO: More validation. Currently we trust the client validation,
    # although the user is authenticated staff so probably not too high a
    # risk of shenanigans.

    title = str(request.form['assess_title'])
    atype = int(request.form['assess_type'])
    startdate = request.form['startdate']
    starthour = int(request.form['examstart_hour'])
    startmin = int(request.form['examstart_minute'])
    enddate = request.form['enddate']
    endhour = int(request.form['examend_hour'])
    endmin = int(request.form['examend_minute'])
    duration = int(request.form['duration'])
    code = request.form['assess_code']
    instant = int(request.form['assess_instant'])
    if "instructions" in request.form:
        instructions = request.form['instructions']
    else:
        instructions = ""

    astart = datetime.datetime.strptime(startdate, "%a %d %b %Y")
    astart = astart.replace(hour=starthour, minute=startmin)
    aend = datetime.datetime.strptime(enddate, "%a %d %b %Y")
    aend = aend.replace(hour=endhour, minute=endmin)

    qns = {}
    for k in request.form.keys():

        v = request.form.getlist(k)
        if k.startswith("question_"):
            _, q, p = k.split("_")
            if not q in qns:
                qns[q] = []
            if not v[0] == '---':
                qns[q].append(int(v[0]))

    if not exam_id:
        exam_id = Exams.create(cid, user_id, title, atype, duration, astart,
                               aend, instructions, code=code, instant=instant)
    else:  # update
        Exams.set_title(exam_id, title)
        Exams.set_duration(exam_id, duration)
        Exams.set_type(exam_id, atype)
        Exams.set_description(exam_id, instructions)
        Exams.set_start_time(exam_id, astart)
        Exams.set_end_time(exam_id, aend)
        Exams.set_code(exam_id, code)
        Exams.set_instant(exam_id, instant)

    for pos, qts in qns.iteritems():
        if pos:
            DB.update_exam_qt_in_pos(exam_id, int(pos), qts)

    return exam_id
开发者ID:jamesdoherty,项目名称:oasisqe,代码行数:59,代码来源:CourseAdmin.py

示例4: teardown

def teardown():
    """
        Remove testing configuration file and otherwise clean up.
    """
    with open(os.path.join(OaConfig.homedir, "sql", "eraseexisting.sql")) as f:
        sql = f.read()
    print "Removing tables."
    DB.run_sql(sql)
开发者ID:colincoghill,项目名称:oasisqe,代码行数:8,代码来源:__init__.py

示例5: practice_do_question

def practice_do_question(topic_id, qt_id):
    """ Show them a question and allow them to fill in some answers """
    user_id = session['user_id']
    try:
        course_id = Topics.get_course_id(topic_id)
    except KeyError:
        course_id = None
        abort(404)
    try:
        course = Courses2.get_course(course_id)
    except KeyError:
        course = None
        abort(404)
    topictitle = "UNKNOWN"
    try:
        topictitle = Topics.get_name(topic_id)
    except KeyError:
        abort(404)
    try:
        qtemplate = DB.get_qtemplate(qt_id)
    except KeyError:
        qtemplate = None
        abort(404)
    questions = Practice.get_sorted_questions(course_id, topic_id, user_id)
    q_title = qtemplate['title']
    q_pos = DB.get_qtemplate_topic_pos(qt_id, topic_id)

    blocked = Practice.is_q_blocked(user_id, course_id, topic_id, qt_id)
    if blocked:
        return render_template(
            "practicequestionblocked.html",
            mesg=blocked,
            topictitle=topictitle,
            topic_id=topic_id,
            qt_id=qt_id,
            course=course,
            q_title=q_title,
            questions=questions,
            q_pos=q_pos,
        )

    try:
        q_id = Practice.get_practice_q(qt_id, user_id)
    except (ValueError, TypeError), err:
        log(ERROR,
            "ERROR 1001  (%s,%s) %s" % (qt_id, user_id, err))
        return render_template(
            "practicequestionerror.html",
            mesg="Error generating question.",
            topictitle=topictitle,
            topic_id=topic_id,
            qt_id=qt_id,
            course=course,
            q_title=q_title,
            questions=questions,
            q_pos="?",
        )
开发者ID:jamesdoherty,项目名称:oasisqe,代码行数:57,代码来源:views_practice.py

示例6: practice_mark_question

def practice_mark_question(topic_id, question_id):
    """ Mark the submitted question answersjust wa """
    user_id = session['user_id']

    course_id = Topics.get_course_id(topic_id)
    if not course_id:
        abort(404)

    course = Courses2.get_course(course_id)
    if not course:
        abort(404)

    topictitle = "UNKNOWN"
    try:
        topictitle = Topics.get_name(topic_id)
    except KeyError:
        abort(404)

    qt_id = DB.get_q_parent(question_id)

    q_title = DB.get_qt_name(qt_id)
    questions = Practice.get_sorted_questions(course_id, topic_id, user_id)
    q_pos = DB.get_qtemplate_topic_pos(qt_id, topic_id)

    blocked = Practice.is_q_blocked(user_id, course_id, topic_id, qt_id)
    if blocked:
        return render_template(
            "practicequestionblocked.html",
            mesg=blocked,
            topictitle=topictitle,
            topic_id=topic_id,
            qt_id=qt_id,
            course=course,
            q_title=q_title,
            questions=questions,
            q_pos=q_pos,
        )

    marking = Practice.mark_q(user_id, topic_id, question_id, request)
    prev_id, next_id = Practice.get_next_prev(qt_id, topic_id)

    return render_template(
        "practicemarkquestion.html",
        topictitle=topictitle,
        topic_id=topic_id,
        qt_id=qt_id,
        course=course,
        q_title=q_title,
        questions=questions,
        q_pos=q_pos,
        q_id=question_id,
        marking=marking,
        next_id=next_id,
        prev_id=prev_id
    )
开发者ID:jamesdoherty,项目名称:oasisqe,代码行数:55,代码来源:views_practice.py

示例7: mark_exam

def mark_exam(user_id, exam_id):
    """ Submit the assessment and mark it.
        Returns True if it went well, or False if a problem.
    """
    numquestions = Exams.get_num_questions(exam_id)
    status = Exams.get_user_status(user_id, exam_id)
    L.info("Marking assessment %s for %s, status is %s" % (exam_id, user_id, status))
    examtotal = 0.0
    errors = 0
    for position in range(1, numquestions + 1):
        q_id = General.get_exam_q(exam_id, position, user_id)
        if not q_id:
            L.critical("Unable to retrieve exam question page %s, exam %s, for user %s" % (position, exam_id, user_id
                                                                                           )
                       )
            errors += 1
            continue
        answers = DB.get_q_guesses(q_id)
        # There's a small chance they got here without ever seeing a question,
        # make sure it exists.
        DB.add_exam_q(user_id, exam_id, q_id, position)

        # First, mark the question
        try:
            marks = General.mark_q(q_id, answers)
            DB.set_q_status(q_id, 3)    # 3 = marked
            DB.set_q_marktime(q_id)
        except OaMarkerError:
            L.warn("Marker Error in question %s, exam %s, student %s!" %
                   (q_id, exam_id, user_id))
            return False
        parts = [int(var[1:])
                 for var in marks.keys()
                 if re.search("^A([0-9]+)$", var) > 0]
        parts.sort()

        # Then calculate the mark
        total = 0.0
        for part in parts:
            try:
                mark = float(marks['M%d' % (part,)])
            except (KeyError, ValueError):
                mark = 0
            total += mark
            DB.update_q_score(q_id, total)
        examtotal += total
    if not errors:
        Exams.set_user_status(user_id, exam_id, 5)
        Exams.set_submit_time(user_id, exam_id)
        Exams.save_score(exam_id, user_id, examtotal)
        Exams.touchuserexam(exam_id, user_id)

    if errors:
        return False
    L.info("user %s scored %s total on exam %s" %
           (user_id, examtotal, exam_id))
    return True
开发者ID:colincoghill,项目名称:oasisqe,代码行数:57,代码来源:Assess.py

示例8: gen_q

def gen_q(qtid, student=0, exam=0, position=0):
    """ Given a qtemplate, will generate a question instance.
        If student and/or exam is supplied it will be assigned appropriately.
        If exam is supplied, position must also be supplied.
        Will return the ID of the created instance.
    """
    # Pick a variation randomly
    version = DB.get_qt_version(qtid)
    numvars = DB.get_qt_num_variations(qtid, version)
    if numvars > 0:
        variation = random.randint(1, numvars)
    else:
        L.warn("No question variations (qtid=%d)" % qtid)
        return False
    return gen_q_from_var(qtid, student, exam, position, version, variation)
开发者ID:tkanesh,项目名称:oasisqe,代码行数:15,代码来源:General.py

示例9: render_mark_results

def render_mark_results(qid, marks):
    """Take the marking results and display something for the student
       that tells them what they got right and wrong.
       If the question has an attachment "_rendermarks.py", it will be called,
       otherwise a default HTML table will be returned. _rendermarks.py should
       set variable "resultsHTML" to contain a suitable string for putting
       in an HTML page.
    """
    qtid = DB.get_q_parent(qid)
    renderscript = DB.get_qt_att(qtid, "__results.py")
    if not renderscript:
        resultshtml = render_mark_results_standard(qid, marks)
    else:
        resultshtml = render_mark_results_script(qtid, qid, marks, renderscript)
    return resultshtml
开发者ID:tkanesh,项目名称:oasisqe,代码行数:15,代码来源:General.py

示例10: cadmin_edit_topic

def cadmin_edit_topic(course_id, topic_id):
    """ Present a page to view and edit a topic, including adding/editing
        questions and setting some parameters.
    """
    user_id = session['user_id']

    if not course_id:
        abort(404)

    course = Courses2.get_course(course_id)
    topic = {
        'id': topic_id,
        'position': Topics.get_pos(topic_id),
        'name': Topics.get_name(topic_id)
    }
    questions = [question
                 for question in Topics.get_qts(topic_id).values()]
    for question in questions:
        question['embed_id'] = DB.get_qt_embedid(question['id'])
        if question['embed_id']:
            question['embed_url'] = "%s/embed/question/%s/question.html" % \
                                    (OaConfig.parentURL, question['embed_id'])
        else:
            question['embed_url'] = None
        question['editor'] = DB.get_qt_editor(question['id'])

    all_courses = Courses2.get_course_list()
    all_courses = [crse
                   for crse in all_courses
                   if satisfy_perms(user_id, int(crse['id']),
                                    ("questionedit", "courseadmin",
                                    "sysadmin"))]
    all_courses.sort(lambda f, s: cmp(f['name'], s['name']))

    all_course_topics = []
    for crse in all_courses:
        topics = Courses.get_topics_all(crse['id'], numq=False)
        if topics:
            all_course_topics.append({'course': crse['name'], 'topics': topics})

    questions.sort(key=lambda k: k['position'])
    return render_template(
        "courseadmin_edittopic.html",
        course=course,
        topic=topic,
        questions=questions,
        all_course_topics=all_course_topics
    )
开发者ID:tkanesh,项目名称:oasisqe,代码行数:48,代码来源:views_cadmin.py

示例11: setup

def setup():
    """ Prepare database for testing.
    """
    if not DB.check_safe():
        print "Attempt to erase database with data."
        sys.exit(-1)
    with open(os.path.join(OaConfig.homedir, "sql", "eraseexisting.sql")) as f:
        sql = f.read()
    print "Removing existing tables."
    DB.run_sql(sql)

    with open(os.path.join(OaConfig.homedir, "sql", "emptyschema_396.sql")) as f:
        sql = f.read()

    DB.run_sql(sql)
    print "Installed v3.9.6 table structure."
开发者ID:colincoghill,项目名称:oasisqe,代码行数:16,代码来源:__init__.py

示例12: get_exam_q

def get_exam_q(exam, page, user_id):
    """ Find the appropriate exam question for the user.
        Generate it if there isn't one already.
    """
    qid = DB.get_exam_q_by_pos_student(exam, page, user_id)
    if qid is not False:
        return int(qid)
    qid = int(gen_exam_q(exam, page, user_id))
    try:
        qid = int(qid)
        assert qid > 0
    except (ValueError, TypeError, AssertionError):
        L.warn("generateExamQuestion(%s,%s, %s) Failed (returned %s)" %
            (exam, page, user_id, qid))
    DB.set_q_viewtime(qid)
    return qid
开发者ID:tkanesh,项目名称:oasisqe,代码行数:16,代码来源:General.py

示例13: api_qedit2_get_qtemplate_json

def api_qedit2_get_qtemplate_json(qt_id):
    """ Present a list of qtemplates that are available for use in the exam."""
    if 'user_id' not in session:
        abort(401)
    user_id = session['user_id']
    topic_id = DB.get_topic_for_qtemplate(qt_id)
    course_id = Topics.get_course_id(topic_id)
    if not satisfy_perms(user_id, course_id, ("questionedit",)):
        abort(401)

    # test data while we're building the frontend
    return jsonify(result={
        'type': "qtemplate data",
        'title': "Test QE2 Question",
        'embed_id': "aaaaaaaaa3",
        'maxscore': 3,
        'pre_vars': [
            {'id': 1, 'name': "a", 'type': 'List', 'value': "2,3,4,5,6,7"},
            {'id': 2, 'name': "b", 'type': 'Range', 'value': "1-10"},
            {'id': 3, 'name': "a1", 'type': 'Calculation', 'value': "$a+$b"},
            {'id': 4, 'name': "a2", 'type': 'Calculation', 'value': "$a*$b"},
        ],
        'qtext': "What is $a + $b ? <answer1>\nWhat is $a * $b?  <answer2> ",
        'answers': [
            {'id': 1, 'source': 'Variable', 'value': '$a1', 'tolerance': 0, 'score': 1},
            {'id': 2, 'source': 'Variable', 'value': '$a2', 'tolerance': 0, 'score': 1}
        ]
    })
开发者ID:colincoghill,项目名称:oasisqe,代码行数:28,代码来源:views_api.py

示例14: setUpClass

    def setUpClass(cls):

        cls.app = app
        cls.app.testing = True
        cls.app.config["TESTING"] = True
        cls.adminpass = DB.generate_admin_passwd()
        (fptr, cls.test_question_fname) = tempfile.mkstemp()
        os.close(fptr)
开发者ID:colincoghill,项目名称:oasisqe,代码行数:8,代码来源:test_assess.py

示例15: mark_q

def mark_q(qid, answers):
    """ Mark the question according to the answers given in a dictionary and
        return the result in a dictionary:
        input:    {"A1":"0.345", "A2":"fred", "A3":"-26" }
        return:   {"M1": Mark One, "C1": Comment One, "M2": Mark Two..... }
    """
    qtid = DB.get_q_parent(qid)
    version = DB.get_q_version(qid)
    variation = DB.get_q_variation(qid)
    qvars = DB.get_qt_variation(qtid, variation, version)
    if not qvars:
        qvars = {}
        L.warn("markQuestion(%s, %s) unable to retrieve variables." %
            (qid, answers))
    qvars['OaQID'] = int(qid)
    marktype = DB.get_qt_marker(qtid)
    if marktype == 1:    # standard
        marks = mark_q_standard(qvars, answers)
    else:
        # We want the latest version of the marker, so no version given
        markerscript = DB.get_qt_att(qtid, "__marker.py")
        if not markerscript:
            markerscript = DB.get_qt_att(qtid, "marker.py")
            L.info("'marker.py' should now be called '__marker.py' (qtid=%s)" % qtid)
        if not markerscript:
            L.info("Unable to retrieve marker script for smart marker question (qtid=%s)!" % qtid)
            marks = mark_q_standard(qvars, answers)
        else:
            marks = mark_q_script(qvars, markerscript, answers)
    return marks
开发者ID:tkanesh,项目名称:oasisqe,代码行数:30,代码来源:General.py


注:本文中的oasis.lib.DB类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。