def position_handler(request, page_id):
    position_information = get_position('./database/seekers_personal.db',
                                        page_id)
    render(request, "positioninformation.html", {
        'position': position_information,
        "login": check_logged_in(request)
    })
Beispiel #2
0
def suggestatopic(
    request
):  # The handler that loads the page with the suggest topic form on it.
    render(request, 'suggestatopic.html', {
        "error": errormessage,
        "login": check_logged_in(request)
    })  #Renders the page with the form on it.
Beispiel #3
0
def update_profile_handler(
    request, userid
):  #The handler that displays the page with the update profile form on it.
    render(request, 'updateprofile.html', {
        "error": errormessage,
        "login": check_logged_in(request)
    })  #Renders the page with the form.
Beispiel #4
0
def finished_profile_handler(request):  #See the update profile above.
    profile_fields = [
        'fname', 'lname', 'email', 'country', 'bio', 'username', 'password'
    ]
    field = []

    password = request.get_field('password')
    confpass = request.get_field('passwordconf')
    if password != confpass:
        errormessage = "Password does not match"
        render(request, 'createprofile.html', {
            "error": errormessage,
            "login": check_logged_in(request)
        })
    else:
        errormessage = ""
    usernameinuse = get_user_by_username('./database/users.db',
                                         request.get_field('username'))
    if usernameinuse:
        errormessage = "Username already exists"
        render(request, 'createprofile.html', {
            "error": errormessage,
            "login": check_logged_in(request)
        })
    else:
        if confpass == password:
            for f in profile_fields:
                field.append(request.get_field(f))

            user = create_user('./database/users.db', field)
            request.set_secure_cookie('user_id', str(user.id))
            request.redirect('/')
Beispiel #5
0
    def admin_institutions_remove(self, id):
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        if request.method == 'POST':
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = "DELETE FROM institution WHERE institutionid=%s"
            cursor.execute(query, (id, ))
            query = "DELETE FROM course where institutionid = %s"
            cursor.execute(query, (id, ))
            cursor.close()
            cnx.close()

            return templating.render("redirect.html",
                                     STATUS="alert-success",
                                     MESSAGE="Institution deleted...")
        else:
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = "SELECT institution_name FROM institution WHERE institutionid=%s"
            cursor.execute(query, (id, ))
            name = cursor.fetchone()[0]
            cursor.close()
            cnx.close()

            return templating.render(
                "confirm.html",
                TITLE="Are you sure you want to delete " + name + "?",
                MESSAGE=
                "The institution and all it's courses will be permanently removed.",
                CONFIRM_LABLE="DELETE")
Beispiel #6
0
def topicpagel_handler(
        request,
        topicid):  #Same as above but for when a comment has been submitted
    topic = get_topic('./database/topics.db', topicid)
    commentyes = get_comment('./database/comments.db', topicid, 'yes')
    commentno = get_comment('./database/comments.db', topicid, 'no')
    typecomment = ""
    if topic == None:
        render(request, "pagenotfound.html",
               {"login": check_logged_in(request)})
    else:
        if not commentyes:
            if not commentno:
                typecomment = "none"
            else:
                typecomment = "noyes"
        if not commentno:
            if commentyes:
                typecomment = "nono"
        render(
            request, "topicpagel.html", {
                'typecomment': typecomment,
                'commentyes': commentyes,
                'commentno': commentno,
                'topic': topic,
                "login": check_logged_in(request)
            })
Beispiel #7
0
def approve_comment_handler(
    request, pendingcommentid
):  #Takes the pending comment id in. Handler for a approve comment function
    user_id = request.get_secure_cookie(
        'user_id')  # gets the secure cookie id of the user
    if user_id:  #if there is actually information in the variable
        if int(
                user_id.decode("UTF-8")
        ) == 1:  #It gets decoded and compared to 1. If it is equal to 1,
            information = get_newpending_comment(
                './database/pending-comments.db', pendingcommentid
            )  #It gets the pendingcomments information from a function using its id.
            if information:  #If there is actually informaation stored,
                create_comment(
                    './database/comments.db', information[1:]
                )  #It adds the comment using its information to the actually comment db (ignoring the oendingcommentid)
                remove_newpending_comment(
                    './database/pending-comments.db', pendingcommentid
                )  # And removes it from the pending comment db using its id.
                request.redirect(
                    '/approve/')  #It redirects back to the approve page.
            else:  #If not logged in as user 1, displays page not found
                render(request, "pagenotfound.html",
                       {"login": check_logged_in(request)})
    else:  #If not logged in as user 1, displays page not found
        render(request, "pagenotfound.html",
               {"login": check_logged_in(request)})
Beispiel #8
0
def topicpage_handler(
    request, topicid
):  #The handler for the topic page. Pulls a topicid from the url. Set up for the version where no comment has been submitted
    topic = get_topic('./database/topics.db',
                      topicid)  #Gets the topic using the topicid
    commentyes = get_comment(
        './database/comments.db', topicid,
        'yes')  #Gets the comments on the topic with the attribute yes
    commentno = get_comment(
        './database/comments.db', topicid,
        'no')  #Gets the comments on the topic with the attribute no
    typecomment = ""  #Sets the variable to be neutral - it is a error keyword that is used on the page
    if topic == None:  #If there is no topic associated with the id, it will display a page not found page.
        render(request, "pagenotfound.html",
               {"login": check_logged_in(request)})
    else:  #Otherwise the following crazy logic happens.
        if not commentyes:
            if not commentno:  #If there are no yes comments and no no comments it sets the keyword to none (no comments: display on the page "No Comments")
                typecomment = "none"
            else:  #If there are no yes comments but some no comments set the keyword to noyes (display: no comments, "No Yes comments")
                typecomment = "noyes"
        if not commentno:
            if commentyes:  #If no no comments and some yes comments it will set the keyword to nono (display: No no comments, yes comments)
                typecomment = "nono"
        #Renders the page with the type of comments keyword and then all of the comments as assigned above.
        render(
            request, "topicpage.html", {
                'typecomment': typecomment,
                'commentyes': commentyes,
                'commentno': commentno,
                'topic': topic,
                "login": check_logged_in(request)
            })
Beispiel #9
0
def searchresult_handler(request, query, querytype):
    positions = return_all_positions('./database/seekers_personal.db')
    results = []
    for position in positions:
        if (query.lower() in position.positionname.lower() or query.lower() in position.companyname.lower() or query.lower() in position.positionlength.lower() or query.lower() in position.address.lower()) and (querytype.lower() in position.positiontype.lower() or querytype.lower() == 'alltypes'):
            results.append(position)
    render(request, "positionlist.html", {"position": results, "login": check_logged_in(request)})
Beispiel #10
0
    def admin_teacher_revoke(self, id):
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        if request.method == 'POST':
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = "DELETE FROM teacher_info WHERE userid=%s"
            cursor.execute(query, (id, ))
            cursor.close()
            cnx.close()

            return templating.render("redirect.html",
                                     STATUS="alert-success",
                                     MESSAGE="Admin rights revoked...")
        else:
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = "SELECT username FROM whiley_user WHERE userid=%s"
            cursor.execute(query, (id, ))
            name = cursor.fetchone()[0]
            cursor.close()
            cnx.close()

            return templating.render(
                "confirm.html",
                TITLE="Are you sure you want to revoke %s's teaching rights?" %
                name,
                MESSAGE="",
                CONFIRM_LABLE="REVOKE")
Beispiel #11
0
    def admin_course_remove(self, id):
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        if request.method == 'POST':
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = "DELETE FROM course WHERE courseid=%s"
            cursor.execute(query, (id,))
            cursor.close()
            cnx.close()

            return templating.render("redirect.html", STATUS="alert-success", 
                                    MESSAGE="Course deleted...")
        else:
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = """SELECT course.course_name, institution.institution_name FROM course, institution 
                    WHERE course.courseid=%s AND institution.institutionid = course.institutionid"""
            cursor.execute(query, (id,))
            course, institution = cursor.fetchone()
            cursor.close()
            cnx.close()

            return templating.render("confirm.html",
                            TITLE="Are you sure you want to delete %s at %s?" % (course, institution),
                            MESSAGE="This course will be permanently removed.", CONFIRM_LABLE="DELETE")
Beispiel #12
0
    def admin_institutions_remove(self, id):
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        if request.method == 'POST':
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = "DELETE FROM institution WHERE institutionid=%s"
            cursor.execute(query, (id,))
            query = "DELETE FROM course where institutionid = %s"
            cursor.execute(query, (id,))
            cursor.close()
            cnx.close()

            return templating.render("redirect.html", STATUS="alert-success", 
                                    MESSAGE="Institution deleted...")
        else:
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = "SELECT institution_name FROM institution WHERE institutionid=%s"
            cursor.execute(query, (id,))
            name = cursor.fetchone()[0]
            cursor.close()
            cnx.close()

            return templating.render("confirm.html", TITLE="Are you sure you want to delete "+name+"?",
                                MESSAGE="The institution and all it's courses will be permanently removed.",
                                CONFIRM_LABLE="DELETE")
Beispiel #13
0
    def admin_course_add_teacher(self, courseid, username, *args, **kwargs):
        """Adds a teacher to a course."""
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdminOrTeacher(userid)

        allow(['POST'])

        cnx, status = db.connect()
        cursor = cnx.cursor()

        query = """SELECT t.teacherid FROM teacher_info t, whiley_user u 
                    WHERE u.username = %s AND u.userid = t.userid"""
        cursor.execute(query, (username, ))
        teacherid = cursor.fetchone()
        if not teacherid:
            return templating.render("redirect.html",
                                     STATUS="alert-warning",
                                     MESSAGE="No such teacher!")
        teacherid = teacherid[0]

        query = """INSERT INTO teacher_course_link (teacherinfoid, courseid) VALUES (%s, %s)"""
        cursor.execute(query, (teacherid, courseid))
        if not cursor.rowcount:
            return templating.render("redirect.html",
                                     STATUS="alert-warning",
                                     MESSAGE="Failed to add teacher!")
        return templating.render("redirect.html",
                                 STATUS="alert-success",
                                 MESSAGE="Teacher added.")
Beispiel #14
0
    def admin_teacher_revoke(self, id):
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        if request.method == 'POST':
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = "DELETE FROM teacher_info WHERE userid=%s"
            cursor.execute(query, (id,))
            cursor.close()
            cnx.close()

            return templating.render("redirect.html", STATUS="alert-success", 
                                    MESSAGE="Admin rights revoked...")
        else:
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = "SELECT username FROM whiley_user WHERE userid=%s"
            cursor.execute(query, (id,))
            name = cursor.fetchone()[0]
            cursor.close()
            cnx.close()

            return templating.render("confirm.html", 
                                TITLE="Are you sure you want to revoke %s's teaching rights?" % name,
                                MESSAGE="", CONFIRM_LABLE="REVOKE")
Beispiel #15
0
def open_issue(**data):
    # Do not open again if has issue alias
    issue_id = data.get("issue")
    if issue_id:
        issue = serverboards.issues.get(data.get("issue"))
        if issue:
            print("Issue already open, not opening again.")
            return

    from templating import render
    title = render(data.get("title"), data)
    description = render(data.get("description"), data)
    aliases = render(data.get("aliases", ""), data).split()
    if issue_id:
        aliases.append(issue_id)
    aliases = [x for x in aliases if x]  # no empty aliases
    #serverboards.rpc.info(json.dumps(data, indent=2))
    if 'service' in data or 'rule' in data:
        description += "\n\nRelated:\n\n"
        if 'service' in data:
            description += " * Service: [%s](%s/#/services/%s)\n" % (
                data["service"].get("name"), base_url(),
                data["service"].get("uuid"))
        if 'rule' in data:
            description += " * Rule: [%s](%s/#/rules/%s)\n" % (
                data["rule"].get("name"), base_url(), data["rule"].get("uuid"))
        description += "\n"

    issue_id = serverboards.rpc.call("issues.create",
                                     title=title,
                                     description=description,
                                     aliases=aliases)
    return {"issue_id": issue_id}
def open_issue(**data):
    # Do not open again if has issue alias
    issue_id = data.get("issue")
    if issue_id:
        issue = serverboards.issues.get(data.get("issue"))
        if issue:
            print("Issue already open, not opening again.")
            return

    from templating import render
    title = render(data.get("title"), data)
    description = render(data.get("description"), data)
    aliases = render(data.get("aliases", ""), data).split()
    if issue_id:
        aliases.append(issue_id)
    aliases = [x for x in aliases if x]  # no empty aliases
    #serverboards.rpc.info(json.dumps(data, indent=2))
    if 'service' in data or 'rule' in data:
        description += "\n\nRelated:\n\n"
        if 'service' in data:
            description += " * Service: [%s](%s/#/services/%s)\n" % (
                data["service"].get("name"), base_url(), data["service"].get("uuid"))
        if 'rule' in data:
            description += " * Rule: [%s](%s/#/rules/%s)\n" % (data["rule"].get("name"),
                                                               base_url(), data["rule"].get("uuid"))
        description += "\n"

    issue_id = serverboards.rpc.call("issues.create", title=title,
                                     description=description, aliases=aliases)
    return {"issue_id": issue_id}
Beispiel #17
0
    def admin_course_remove(self, id):
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        if request.method == 'POST':
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = "DELETE FROM course WHERE courseid=%s"
            cursor.execute(query, (id, ))
            cursor.close()
            cnx.close()

            return templating.render("redirect.html",
                                     STATUS="alert-success",
                                     MESSAGE="Course deleted...")
        else:
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = """SELECT course.course_name, institution.institution_name FROM course, institution 
                    WHERE course.courseid=%s AND institution.institutionid = course.institutionid"""
            cursor.execute(query, (id, ))
            course, institution = cursor.fetchone()
            cursor.close()
            cnx.close()

            return templating.render(
                "confirm.html",
                TITLE="Are you sure you want to delete %s at %s?" %
                (course, institution),
                MESSAGE="This course will be permanently removed.",
                CONFIRM_LABLE="DELETE")
Beispiel #18
0
def deny_topic_handler(request, pendingtopicid):
    user_id = request.get_secure_cookie('user_id')
    if user_id:
        if int(user_id.decode("UTF-8")) == 1:
            remove_newpending_topic('./database/pending-topics.db',
                                    pendingtopicid)
            request.redirect('/approve/')
    else:
        render(request, "pagenotfound.html",
               {"login": check_logged_in(request)})
def comment_issue(issue=None, **data):
    from templating import render
    issue = render(issue, data)
    comment = render(data.get("comment"), data)
    if not issue:
        serverboards.error("Error trying to close issue, none given")

    try:
        serverboards.rpc.call("issues.update", issue, {"type": "comment", "data": comment})
    except:
        serverboards.error("Error trying to comment on issue, cant update issue %s" % (issue))
Beispiel #20
0
def post_login_handler(request):
    user = get_seeker_by_username('./database/seekers_personal.db', request.get_field('username'))
    if user:
        # check if password is correct
        if user.password == request.get_field('password'):
            request.set_secure_cookie('user_id', str(user.id))
            request.redirect("/")
        else:
            render(request, "login.html", {"error":"Incorrect password", "login": check_logged_in(request)})
    else:
        render(request, "login.html", {"error":"Incorrect username", "login": check_logged_in(request)})
Beispiel #21
0
def profilelistpage_handler(request):
    seekers = get_seekers('./database/seekers_personal.db')
    if not check_logged_in(request):
        render(request, 'profilelistpage.html', {
            "seekers": seekers,
            "login": check_logged_in(request)
        })
    else:
        render(request, "profile.html", {
            "user": check_logged_in(request),
            "login": check_logged_in(request)
        })
Beispiel #22
0
 def edit(self, request, id):
     "Displays a form for editing a film by id"
     if id < 1:
         raise NotFound("Film id must be a positive integer: %s" % id)
     try:
         row = self.relvar.get_one(self.relvar.key_tuple(id))
     except Exception as exc:
         return render('film/edit.html', id=id,
                       errors={None: self.db_error(exc)})
     if not row:
         raise NotFound("Film %d not found " % id)
     return render('film/edit.html', film=row)
Beispiel #23
0
 def edit(self, request, id):
     "Displays a form for editing a film by id"
     if id < 1:
         raise NotFound("Film id must be a positive integer: %s" % id)
     try:
         row = self.relvar.get_one(self.relvar.key_tuple(id))
     except Exception as exc:
         return render('film/edit.html',
                       id=id,
                       errors={None: self.db_error(exc)})
     if not row:
         raise NotFound("Film %d not found " % id)
     return render('film/edit.html', film=row)
Beispiel #24
0
def profile_handler (request, user_id):
    '''
    if user_id == '1':
        with open('profile.html') as p:
            profile_html = p.read()
            profile_html = render(profile_html, {"user": user})
            request.write(profile_html)
    '''
    customer = get_seeker('./database/seekers_personal.db', user_id)
    if customer == None:
        render(request, "pagenotfound.html", {"login": check_logged_in(request)})
    else:
        render(request, "profile.html", {"user": customer, "login": check_logged_in(request)})
Beispiel #25
0
def searchresult_handler(
        request,
        query):  # the handler that deals with the results of the search query
    search_result = search_topic(
        './database/topics.db',
        query)  #Calls the search function - parses it the query statement
    if not search_result:  #If it doesn't match the search query
        render(request, "searchresultnone.html", {
            "login": check_logged_in(request)
        })  #renders the no search results page which has another form on it.
    else:  #Otherwise
        render(request, "searchresults.html", {
            'topics': search_result,
            "login": check_logged_in(request)
        })  #Render the seatrch results page with the search results
Beispiel #26
0
def comment_issue(issue=None, **data):
    from templating import render
    issue = render(issue, data)
    comment = render(data.get("comment"), data)
    if not issue:
        serverboards.error("Error trying to close issue, none given")

    try:
        serverboards.rpc.call("issues.update", issue, {
            "type": "comment",
            "data": comment
        })
    except:
        serverboards.error(
            "Error trying to comment on issue, cant update issue %s" % (issue))
Beispiel #27
0
 def index(self, request):
     "Lists all films"
     errors = {}
     p = int(request.args.get('p', 1))
     qry_args = self.add_args(['title', 'release_year'], request.args)
     maxlines = 10
     try:
         numrows = self.relation.count(qry_args)
         film_list = self.relation.subset(maxlines, (p - 1) * maxlines,
                                          qry_args)
     except KeyError as exc:
         numrows = 0
         film_list = []
         errors = {None: exc}
     except Exception as exc:
         numrows = 0
         film_list = []
         errors = {None: self.db_error(exc)}
     more = 1 if (numrows % maxlines) else 0
     return render('film/list.html',
                   films=film_list,
                   curr_page=p,
                   numrows=numrows,
                   numpages=numrows / maxlines + more,
                   qry_args=qry_args,
                   errors=errors)
Beispiel #28
0
    def admin_course_add_stream(self, courseid, name, *args, **kwargs):
        """Adds a stream to a course."""
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdminOrTeacher(userid)

        allow(['POST'])
        print courseid, name

        cnx, status = db.connect()
        cursor = cnx.cursor()

        query = """INSERT INTO course_stream (stream_name, courseid) VALUES (%s, %s)"""
        cursor.execute(query, (name, courseid))
        if not cursor.rowcount:
            return templating.render("redirect.html", STATUS="alert-warning", MESSAGE="Failed to add course stream!")
        return templating.render("redirect.html", STATUS="alert-success", MESSAGE="Course stream added.")
Beispiel #29
0
    def admin(self, *args, **kwargs):
        """
        The admin homepage should return a template for the admin page.

        >>> authorizeTests()
        >>> self = Admin()
        >>> results = self.admin()
        >>> results.ERROR
        ''
        >>> results.REDIRECT
        'NO'
        >>> results.STATUS
        'DB: Connection ok'
        """
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdminOrTeacher(userid)

        allow(["HEAD", "GET"])
        error = ""
        redirect = "NO"
        status = "DB: Connection ok"
        cnx = db.connect()

        return templating.render("admin.html",
                                 ROOT_URL=config.VIRTUAL_URL,
                                 ERROR=error,
                                 REDIRECT=redirect,
                                 STATUS=status,
                                 IS_ADMIN=isAdmin(userid))
Beispiel #30
0
    def admin_institutions_add(self, institution=None, description=None, contact=None, website=None,
            *args, **kwargs):
        """
        Adds an institution to the database.
        """
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        allow(["HEAD", "GET", "POST"])
        options = " "
        status = ""

        if institution:
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = (
                "insert into institution (institution_name,description,contact,website) values ('" +
                institution + "','" +
                description + "','" +
                contact + "','" +
                website + "')")
            cursor.execute(query)
            status = "New institution has been added"
            cursor.close()
            cnx.close()

        return templating.render("admin_institutions_add.html", ROOT_URL=config.VIRTUAL_URL, ERROR="",
                                REDIRECT="", OPTION=options, STATUS=status, IS_ADMIN=isAdmin(userid))
Beispiel #31
0
    def admin(self, *args, **kwargs):
        """
        The admin homepage should return a template for the admin page.

        >>> authorizeTests()
        >>> self = Admin()
        >>> results = self.admin()
        >>> results.ERROR
        ''
        >>> results.REDIRECT
        'NO'
        >>> results.STATUS
        'DB: Connection ok'
        """
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdminOrTeacher(userid)
        
        allow(["HEAD", "GET"])
        error = ""
        redirect = "NO"
        status = "DB: Connection ok"
        cnx = db.connect()

        return templating.render("admin.html", ROOT_URL=config.VIRTUAL_URL, ERROR=error, REDIRECT=redirect,
                                STATUS=status, IS_ADMIN=isAdmin(userid))
Beispiel #32
0
    def admin_institutions(self, institution="", *args, **kwargs):
        """
        Lists available institutions.

        >>> authorizeTests()
        >>> self = Admin()
        >>> ret = self.admin_institutions()
        >>> ('Victoria University of Wellington', 2) in ret.OPTION
        True
        >>> ret = self.admin_institutions(2)
        >>> ret.INSTITUTION_ID, ret.INSTITUTION, ret.CONTACT, ret.WEBSITE, ret.DESCRIPTION
        (2, 'Victoria University of Wellington', None, None, None)
        """
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        allow(["HEAD", "GET", "POST"])
        redirect = "NO"
        options = []

        if institution:
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = ("SELECT institution_name, institutionid from institution order by institution_name")
            cursor.execute(query)
            options = list(cursor)
            cursor.close()
            cnx.close()
        displayInstitution = ""
        displayContact = ""
        displayWebsite = ""
        displayDescription = ""

        if institution == "":
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = ("SELECT institution_name, institutionid from institution order by institution_name")
            cursor.execute(query)
            institution = ""
            for (institute) in cursor:
                options.append(institute)
                if institution == "":
                    institution = institute[1]

            cursor.close()
            cnx.close()

        cnx, status = db.connect()
        cursor = cnx.cursor()
        query = (
            "SELECT institution_name,description,contact,website from institution where institutionid = '" + str(institution) + "'")
        cursor.execute(query)
        displayInstitution, displayDescription, displayContact, displayWebsite = cursor.fetchone()
        cursor.close()
        cnx.close()

        return templating.render("admin_institutions.html", ROOT_URL=config.VIRTUAL_URL, ERROR="", 
                               REDIRECT=redirect, OPTION=options, INSTITUTION_ID=institution,
                               INSTITUTION=displayInstitution, CONTACT=displayContact, WEBSITE=displayWebsite,
                               DESCRIPTION=displayDescription, IS_ADMIN=isAdmin(userid))
Beispiel #33
0
def render_template(template_name, template_mapping, title):
    base_mapping = {
        'title': title,
        'navigation': render_plain('includes/navigation.html', template_mapping),
        'body': render_plain(template_name, template_mapping),
    }
    return render('base.html', base_mapping)
Beispiel #34
0
def close_issue(**data):
    issue_id = data.get("issue")
    if issue_id:
        issue = serverboards.issues.get(issue_id)
        if not issue or issue["status"] == "closed":
            return {"updated": False}  # nothing to do
    from templating import render
    comment = render(data.get("comment"), data)
    if not issue_id:
        serverboards.error("Error trying to close issue, none given")

    try:
        serverboards.rpc.call("issues.update", issue_id, [{
            "type": "comment",
            "data": comment
        }, {
            "type": "change_status",
            "data": "closed"
        }])
        return {"updated": True}
    except Exception:
        import traceback
        traceback.print_exc()
        serverboards.error(
            "Error trying to close issue, cant update issue %s" % (issue_id))
Beispiel #35
0
def my(environ, start_response):
    current_user = users.user_from_cookie(db, environ)
    if current_user != None:
        content = "<p>Hello World!</p>"
        mapping = {"title": "Welcome to FlowTow", "content": my_content(environ), "navbar": get_navbar(environ)}
        start_response("200 OK", [("content-type", "text/html")])
        return render("index.html", mapping)
    else:
        return index(environ, start_response)
Beispiel #36
0
    def _on_config_changed(self, event):
        peers = self._get_peers_for_context(self.config['peers'])
        if peers is None:
            return

        container = self.unit.get_container(THRUK_SERVICE)
        context = {
            'config': self.config,
            'peers': peers,
        }
        with self.restart_if_changed(container, '/etc/thruk/log4perl.conf',
                                     '/etc/thruk/thruk_local.conf'):
            container.push(
                "/etc/thruk/log4perl.conf",
                templating.render(self.charm_dir, "log4perl.conf", context))
            container.push(
                "/etc/thruk/thruk_local.conf",
                templating.render(self.charm_dir, "thruk_local.conf", context))
Beispiel #37
0
    def user_courses(self, studentinfoid=None, institution="", validationcode="", courseid="", *args, **kwargs):
        """Assign user to select course
        
        """
        if studentinfoid is None:
            raise cherrypy.HTTPRedirect("/")
        allow(["HEAD", "GET", "POST"])
        error = False
        error_msg = " "
        redirect = "NO"
        options = []

        course_list = []
        
        if institution:
            cnx, status = db.connect()
            cursor = cnx.cursor() 
            query = ("SELECT institutionid,institution_name from institution order by institution_name")
            cursor.execute(query) 
            options = list(cursor)
            cursor.close()

        if courseid:
            cnx, status = db.connect()
            cursor = cnx.cursor() 
            error = insertuserdetails(studentinfoid, institution, courseid, validationcode)
            cursor.close()
            if error is False:
                message="User Created, Welcome! Redirecting..."
                template = lookup.get_template("redirect.html")
                return template.render(STATUS="alert-success", MESSAGE=message)
            else:
                error_msg= "Wrong Validation Code"

        if institution == "":          
            cnx, status = db.connect()
            cursor = cnx.cursor() 
            query = ("SELECT institutionid,institution_name from institution order by institution_name")
            cursor.execute(query)
            for (institutionid,institution_name) in cursor:
                options.append((institutionid, institution_name))
                if institution == "":
                    institution = str(institutionid)
            cursor.close()

        ##get courses list
        cnx, status = db.connect()
        cursor = cnx.cursor() 
        query = ("SELECT courseid,code from course where institutionid = '" + institution + "' order by code")
        cursor.execute(query)
        course_list = list(cursor)
        cursor.close()

        return templating.render("user_institutions.html", ERROR=error, ERRORMSG=error_msg, NOTALLOWED=False, 
                                ROOT_URL=config.VIRTUAL_URL, OPTION=options, 
                                COURSE_LIST=course_list, STUDENTINFOID=studentinfoid, INSTITUTION=institution)
Beispiel #38
0
    def admin_course_add(self,
                         course_name=None,
                         course_code=None,
                         course_year=None,
                         course_institution=None,
                         validation_code=None,
                         *args,
                         **kwargs):
        """
        Adds a course to the database. 
        """
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        import random, string
        allow(["HEAD", "GET", "POST"])
        error = ""
        redirect = "NO"
        options = []
        newstatus = ""
        validationCode = ''.join(
            random.choice(string.ascii_uppercase + string.digits)
            for _ in range(4))

        if course_code:
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = (
                "insert into course (course_name,code,year,institutionid,validationcode) values ('"
                + course_name + "','" + course_code.upper() + "','" +
                course_year + "','" + course_institution + "','" +
                validation_code + "')")
            cursor.execute(query)
            newstatus = "New course has been added"
            cursor.close()
            cnx.close()

        cnx, status = db.connect()
        cursor = cnx.cursor()
        query = (
            "SELECT institutionid,institution_name from institution order by institution_name"
        )
        cursor.execute(query)
        options = list(cursor)
        cursor.close()
        cnx.close()

        return templating.render("admin_courses_add.html",
                                 ROOT_URL=config.VIRTUAL_URL,
                                 ERROR=error,
                                 REDIRECT=redirect,
                                 OPTION=options,
                                 NEWSTATUS=newstatus,
                                 VALIDATIONCODE=validationCode,
                                 IS_ADMIN=isAdmin(userid))
Beispiel #39
0
    def admin_courses(self, institution="", *args, **kwargs):
        """
        Lists all available courses. 

        >>> authorizeTests()
        >>> self = Admin()
        >>> ret = self.admin_courses()
        >>> (2, 'Victoria University of Wellington') in ret.OPTION
        True
        >>> ret = self.admin_courses('2')
        >>> (2, 'Victoria University of Wellington') in ret.OPTION
        True
        >>> ret.INSTITUTION
        '2'
        >>> (1, 'SWEN302') in ret.COURSE_LIST
        True
        """
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        allow(["HEAD", "GET", "POST"])
        error = ""
        redirect = "NO"
        options = []

        course_list = []
        
        if institution:
            cnx, status = db.connect()
            cursor = cnx.cursor() 
            query = ("SELECT institutionid,institution_name from institution order by institution_name")
            cursor.execute(query) 
            options = list(cursor)
            cursor.close()
        else:          
            cnx, status = db.connect()
            cursor = cnx.cursor() 
            query = ("SELECT institutionid,institution_name from institution order by institution_name")
            cursor.execute(query)
            for (institutionid,institution_name) in cursor:
                options.append((institutionid, institution_name))
                if institution == "":
                    institution = str(institutionid)
            cursor.close()
                
        cnx, status = db.connect()
        cursor = cnx.cursor() 
        query = ("SELECT courseid,code from course where institutionid = '" + institution + "' order by code")
        cursor.execute(query)
        course_list = list(cursor)
        cursor.close()

        return templating.render("admin_courses.html", ROOT_URL=config.VIRTUAL_URL, ERROR=error,
                                REDIRECT=redirect, OPTION=options, INSTITUTION=institution, 
                                COURSE_LIST=course_list, IS_ADMIN=isAdmin(userid))
Beispiel #40
0
    def admin_course_add_stream(self, courseid, name, *args, **kwargs):
        """Adds a stream to a course."""
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdminOrTeacher(userid)

        allow(['POST'])
        print courseid, name

        cnx, status = db.connect()
        cursor = cnx.cursor()

        query = """INSERT INTO course_stream (stream_name, courseid) VALUES (%s, %s)"""
        cursor.execute(query, (name, courseid))
        if not cursor.rowcount:
            return templating.render("redirect.html",
                                     STATUS="alert-warning",
                                     MESSAGE="Failed to add course stream!")
        return templating.render("redirect.html",
                                 STATUS="alert-success",
                                 MESSAGE="Course stream added.")
Beispiel #41
0
def approval_handler(request):
    user_id = request.get_secure_cookie(
        'user_id')  # gets the secure cookie id of the user
    if user_id:  #if there is actually information in the variable
        user_id = user_id.decode(
            "UTF-8")  #It gets decoded and compared to 1. If it is equal to 1,
        if int(user_id) == int(1):
            pendingcomments = get_allnewpending_comment(
                './database/pending-comments.db'
            )  #Gets all comments in db pending comments and stores them in a variavle that is parsed when rendered to the approve page.
            pendingtopics = get_allnewpending_topics(
                './database/pending-topics.db')
            render(
                request, 'approval.html', {
                    'pendingtopics': pendingtopics,
                    'pendingcomments': pendingcomments,
                    "login": check_logged_in(request)
                })
    else:  #If not logged in as user 1, displays page not found
        render(request, "pagenotfound.html",
               {"login": check_logged_in(request)})
Beispiel #42
0
def post_login_handler(request):  #The POST method handler for the login form.
    user = get_user_by_username(
        './database/users.db', request.get_field(
            'username'))  #Gets the info of the username entered in the form
    if user:  #If the username entered is real and is in the database
        if user.password == request.get_field(
                'password'
        ):  #And if the password of the user (whos username matched) matches the field information
            request.set_secure_cookie('user_id', str(
                user.id))  #If so, it sets the secure cookie to the users id.
            request.redirect("/")  #Redirects to the home page.
        else:  #If the password does not match the users actual password, it renders the page again with the error incorrect password
            render(request, "login.html", {
                "error": "Incorrect password",
                "login": check_logged_in(request)
            })
    else:  #If the username does exist, it renders the page again with the error incorrect username
        render(request, "login.html", {
            "error": "Incorrect username",
            "login": check_logged_in(request)
        })
Beispiel #43
0
 def delete(self, request, id=None):
     "Deletes an existing film by id"
     if id < 1:
         raise NotFound("Film id must be a positive integer: %s" % id)
     keytuple = self.relvar.key_tuple(id)
     try:
         row = self.relvar.get_one(keytuple)
     except Exception as exc:
         return render('film/edit.html', id=id,
                       errors={None: self.db_error(exc)})
     if not row:
         raise NotFound("Film %d not found " % id)
     if request.method != 'POST':
         return render('film/delete.html', id=id, film=film_repr(row))
     try:
         self.relvar.delete_one(keytuple, row)
     except Exception as exc:
         return render('film/delete.html', id=row.id, film=film_repr(row),
                       errors={None: self.db_error(exc)})
     self.db.commit()
     return redirect('/films')
Beispiel #44
0
    def admin_course_details(self, id, *args, **kwargs):
        """
        Retrieves course details.

        >>> authorizeTests()
        >>> self = Admin()
        >>> ret = self.admin_course_details('1')
        >>> ret.COURSENAME, ret.COURSECODE, ret.YEAR
        ('Agile Methods', 'SWEN302', 2014)
        >>> ret.VALIDATIONCODE, ret.INSTITUTION
        (u'aaaa', 'Victoria University of Wellington')
        >>> 'dave, dave' in ret.STUDENTS
        True
        """
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        allow(["HEAD", "GET", "POST"])
        error = ""
        redirect = "NO"
        newstatus = "" 
        students = []
        courseId = id

        cnx, status = db.connect()
        cursor = cnx.cursor() 
       
        query = ("SELECT courseid,course_name,code,year,validationcode,institution_name from course a, institution b where a.institutionid = b.institutionid and a.courseid = %s")
        cursor.execute(query, (id,))
        courseID, courseName, courseCode, year, validationcode, institution = cursor.fetchone()

        sql = "SELECT distinct a.student_info_id,a.givenname,a.surname from student_info a,student_course_link b, course c, course_stream d where c.courseid = %s and  c.courseid = d.courseid and d.coursestreamid =b.coursestreamid and b.studentinfoid = a.student_info_id order by a.surname"

        cursor.execute(sql, (str(courseID),))
        students = [(id, name(givenname, surname)) for id, givenname, surname in cursor]

        sql = """SELECT distinct a.teacherid,a.full_name 
                from teacher_info a, teacher_course_link b
                where b.courseid = %s and b.teacherinfoid = a.teacherid"""
        cursor.execute(sql, (str(courseID),))
        teachers = list(cursor)

        sql = """SELECT stream_name from course_stream where courseid = %s"""
        cursor.execute(sql, (str(courseId),))
        streams = [ret[0] for ret in cursor]

        cursor.close()
        
        return templating.render("admin_course_details.html", ROOT_URL=config.VIRTUAL_URL, ERROR=error, 
            REDIRECT=redirect, TEACHERS=teachers, STREAMS=streams, 
            COURSENAME=courseName, COURSECODE=courseCode, YEAR=year, VALIDATIONCODE=validationcode,
            INSTITUTION=institution, STUDENTS=students, COURSEID=courseId, IS_ADMIN=isAdmin(userid))
Beispiel #45
0
def get_clinical_research(medicament):

    if check_input(medicament) == False:
        return error()

    # Get an alphabet characters list.
    alphabet_list = parse(get_html(BASE_URL))

    # Find a link for transition to the page with a particular letter.
    link_togo = get_first_letter_url(alphabet_list, medicament)

    if check_input(link_togo) == False:
        return error()

    # Get a list of medicaments.
    medicament_list = get_medicament_list(link_togo)

    # Get a list of medicaments that were find.
    medicament_link = find_medicament_matches(medicament_list, medicament)

    if check_input(medicament_link) == False:
        return error()

    # Create a bootstrap table to display data that was found.
    html = "  <table class='table table-hover'><thead class='thead-dark'><tr><th scope='col'>Страница препарата в регистре лекарственных средств России</th><th scope='col'>Информация о клинических исследованиях</th></tr></thead>"

    search_result = ""
    warning = ""

    for i in medicament_link:
        link = "http:" + i['value']
        medicament_page = get_html(link)
        clinical_trials = parse_clinical_trials(medicament_page)

        if clinical_trials == None:
            search_result = 'Не найдена'
            warning = ""
        else:
            search_result = 'Найдена'
            warning = "class='table-primary'"

        html = html + "<tr" + " " + warning + "><td align='left'><a href=" + "'" + link + "'" + " " + "target='_blank' class='text-dark'>" + i[
            'key'] + "<a></td>" + "<td align='center'>" + search_result + "</td></tr>"

    html = html + '</table>'

    mapping = {'page': html}

    body = render("index", mapping)
    return body
Beispiel #46
0
    def admin_course_add_teacher(self, courseid, username, *args, **kwargs):
        """Adds a teacher to a course."""
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdminOrTeacher(userid)

        allow(['POST'])

        cnx, status = db.connect()
        cursor = cnx.cursor()

        query = """SELECT t.teacherid FROM teacher_info t, whiley_user u 
                    WHERE u.username = %s AND u.userid = t.userid"""
        cursor.execute(query, (username,))
        teacherid = cursor.fetchone()
        if not teacherid:
            return templating.render("redirect.html", STATUS="alert-warning", MESSAGE="No such teacher!")
        teacherid = teacherid[0]

        query = """INSERT INTO teacher_course_link (teacherinfoid, courseid) VALUES (%s, %s)"""
        cursor.execute(query, (teacherid, courseid))
        if not cursor.rowcount:
            return templating.render("redirect.html", STATUS="alert-warning", MESSAGE="Failed to add teacher!")
        return templating.render("redirect.html", STATUS="alert-success", MESSAGE="Teacher added.")
Beispiel #47
0
    def admin_teacher_add(self,
                          id,
                          login="",
                          staffid="",
                          full_name="",
                          preferred_name="",
                          *args,
                          **kwargs):
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        if request.method == 'POST' and login and staffid and full_name and preferred_name:
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = "SELECT userid FROM whiley_user WHERE username = %s"
            cursor.execute(query, (id, ))
            id = cursor.fetchone()[0]
            cursor.close()
            cnx.close()

            auth.create_teacher(id, login, staffid, full_name, preferred_name)

            return templating.render("redirect.html",
                                     STATUS="alert-success",
                                     MESSAGE="Teacher rights added...")
        else:
            # prefill login
            if not login:
                login = id

            return templating.render("admin_add_teacher.html",
                                     USERID=id,
                                     LOGIN=login,
                                     STAFFID=staffid,
                                     FULLNAME=full_name,
                                     PREFERRED_NAME=preferred_name,
                                     IS_ADMIN=isAdmin(userid))
Beispiel #48
0
    def admin_teacher_add(self, id, login="", staffid="", full_name="", preferred_name="", *args, **kwargs):
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        if request.method == 'POST' and login and staffid and full_name and preferred_name:
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = "SELECT userid FROM whiley_user WHERE username = %s"
            cursor.execute(query, (id,))
            id = cursor.fetchone()[0]
            cursor.close()
            cnx.close()

            auth.create_teacher(id, login, staffid, full_name, preferred_name)

            return templating.render("redirect.html", STATUS="alert-success", MESSAGE="Teacher rights added...")
        else:
            # prefill login
            if not login:
                login = id

            return templating.render("admin_add_teacher.html", USERID=id, LOGIN=login, STAFFID=staffid,
                                        FULLNAME=full_name, PREFERRED_NAME=preferred_name, 
                                        IS_ADMIN=isAdmin(userid))
Beispiel #49
0
 def create(self, request):
     "Saves the film data submitted from 'new'"
     form = FilmForm(**request.form)
     form.validate()
     errors = form.errors
     if not errors:
         film = self.relvar.tuple(title=form.title,
                                  release_year=int(form.release_year))
         try:
             self.relvar.insert_one(film)
         except Exception as exc:
             errors = {None: self.db_error(exc)}
         self.db.commit()
     if errors:
         return render('film/new.html', film=form,  errors=errors)
     return redirect('/films')
Beispiel #50
0
 def save(self, request, id=None):
     "Saves the film data submitted from 'edit'"
     form = FilmForm(**request.form)
     form.validate()
     errors = form.errors
     if not errors:
         film = self.relvar.tuple(int(id), form.title,
                                  int(form.release_year))
         film._tuple_version = int(form.rowver)
         try:
             self.relvar.update_one(film, self.relvar.key_tuple(int(id)))
         except Exception as exc:
             errors = {None: self.db_error(exc)}
         self.db.commit()
     if errors:
         return render('film/edit.html', id=id, film=film, errors=errors)
     return redirect('/films')
Beispiel #51
0
def login(environ, start_response):
    success = False
    headers = [("content-type", "text/html")]
    formdata = cgi.FieldStorage(environ=environ, fp=environ["wsgi.input"])
    if "password" in formdata:
        email = formdata.getvalue("email", "")
        password = formdata.getvalue("password", "")
        success = users.check_login(db, email, password)
    # login is successful, creates a cookie
    if success:
        cookie = users.generate_session(db, email)
        headers.append(("Set-Cookie", cookie["sessionid"].OutputString()))
        headers.append(("Location", "/"))
        start_response("303 See Other", headers)
        return [redirect_page.encode()]
    else:
        content = "Login problem"
        mapping = {"title": "Login", "content": content, "navbar": get_navbar(environ)}
    start_response("200 OK", headers)
    return render("login.html", mapping)
Beispiel #52
0
 def test_render(self):
     """Test that the templating render works rendering from a file"""
     
     template = ">>$one<< >>$two<< >>${three}<<"
     
     (handle, filepath) = tempfile.mkstemp(dir=templating.TEMPLATE_DIR)
     self.addCleanup(lambda: os.unlink(filepath))
     
     os.write(handle, template.encode())
     os.close(handle)
     
     templatename = os.path.basename(filepath)
     
     # render with all variables
     d = {'one': 1, 'two': 'two', 'three': [3]}
     
     self.assertEqual([b">>1<< >>two<< >>[3]<<"], templating.render(templatename, d))
     # with missing values
     d = {'one': 1}
     
     self.assertEqual([b">>1<< >>$two<< >>${three}<<"], templating.render_from_string(template, d))
Beispiel #53
0
    def admin_course_add(self, course_name=None, course_code=None, course_year=None, 
                        course_institution=None, validation_code=None, *args, **kwargs): 
        """
        Adds a course to the database. 
        """
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        import random, string
        allow(["HEAD", "GET", "POST"]) 
        error = "" 
        redirect = "NO" 
        options = []
        newstatus = "" 
        validationCode = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(4))


        if course_code: 
            cnx, status = db.connect() 
            cursor = cnx.cursor() 
            query = ("insert into course (course_name,code,year,institutionid,validationcode) values ('" + course_name + "','" + course_code.upper() + "','" + 
                         course_year + "','" + course_institution + "','" + validation_code + "')") 
            cursor.execute(query) 
            newstatus = "New course has been added" 
            cursor.close() 
            cnx.close() 


        cnx, status = db.connect() 
        cursor = cnx.cursor() 
        query = ("SELECT institutionid,institution_name from institution order by institution_name") 
        cursor.execute(query) 
        options = list(cursor)
        cursor.close() 
        cnx.close() 

        return templating.render("admin_courses_add.html", ROOT_URL=config.VIRTUAL_URL, ERROR=error,
                                    REDIRECT=redirect, OPTION=options, NEWSTATUS=newstatus, 
                                    VALIDATIONCODE=validationCode, IS_ADMIN=isAdmin(userid))  
def close_issue(**data):
    issue_id = data.get("issue")
    if issue_id:
        issue = serverboards.issues.get(issue_id)
        if not issue or issue["status"] == "closed":
            return {"updated": False}  # nothing to do
    from templating import render
    comment = render(data.get("comment"), data)
    if not issue_id:
        serverboards.error("Error trying to close issue, none given")

    try:
        serverboards.rpc.call("issues.update", issue_id,
                              [
                                  {"type": "comment", "data": comment},
                                  {"type": "change_status", "data": "closed"}
                              ])
        return {"updated": True}
    except Exception:
        import traceback
        traceback.print_exc()
        serverboards.error("Error trying to close issue, cant update issue %s" % (issue_id))
Beispiel #55
0
 def index(self, request):
     "Lists all films"
     errors = {}
     p = int(request.args.get('p', 1))
     qry_args = self.add_args(['title', 'release_year'], request.args)
     maxlines = 10
     try:
         numrows = self.relation.count(qry_args)
         film_list = self.relation.subset(maxlines, (p - 1) * maxlines,
                                          qry_args)
     except KeyError as exc:
         numrows = 0
         film_list = []
         errors = {None: exc}
     except Exception as exc:
         numrows = 0
         film_list = []
         errors = {None: self.db_error(exc)}
     more = 1 if (numrows % maxlines) else 0
     return render('film/list.html', films=film_list, curr_page=p,
                   numrows=numrows, numpages=numrows / maxlines + more,
                   qry_args=qry_args, errors=errors)
Beispiel #56
0
    def admin_students_list(self, id=None, institution="", course=None, *args, **kwargs):
        """
        Lists students under a institution and course. 

        >>> authorizeTests()
        >>> self = Admin().admin_students_list
        >>> ret = self()
        >>> (2, 'Victoria University of Wellington') in ret.OPTION
        True
        >>> ret.STUDENTNAME, ret.STUDENTCOURSES
        ('No student selected', [])

        >>> ret = self(institution='2')
        >>> (2, 'Victoria University of Wellington') in ret.OPTION
        True
        >>> (1, 'SWEN302') in ret.OPTIONCOURSE
        True
        >>> ret.INSTITUTION
        '2'
        >>> ret.STUDENTNAME, ret.STUDENTCOURSES
        ('No student selected', [])

        >>> ret = self(institution='2', course='1')
        >>> (2, 'Victoria University of Wellington') in ret.OPTION
        True
        >>> ret.INSTITUTION
        '2'
        >>> (1, 'SWEN302') in ret.OPTIONCOURSE
        True
        >>> ret.COURSE
        '1'
        >>> (70, 'dave, dave') in ret.OPTIONSTUDENT
        True
        >>> ret.STUDENTNAME, ret.STUDENTCOURSES
        ('No student selected', [])
        
        >>> ret = self(70, '2', '1')
        >>> (2, 'Victoria University of Wellington') in ret.OPTION
        True
        >>> ret.INSTITUTION
        '2'
        >>> (1, 'SWEN302') in ret.OPTIONCOURSE
        True
        >>> ret.COURSE
        '1'
        >>> (70, 'dave, dave') in ret.OPTIONSTUDENT
        True
        >>> ret.STUDENTNAME
        'dave dave'
        >>> ('Agile Methods', 'SWEN302', 2014, 1) in ret.STUDENTCOURSES
        True
        """
        isAdmin, permittedCourses, permittedStudents = getAccessPermissions()

        allow(["HEAD", "GET", "POST"])
        error = ""
        redirect = "NO"
        options = []
        optionsCourse = []
        optionsStudent = []
        studentInstitution = ""

        status, studentName, studentInstitution, studentCourses, studentProjects = \
                studentInfo(id, "No student selected")

        if institution:
            cnx, status = db.connect()
            cursor = cnx.cursor() 
            query = ("SELECT institutionid,institution_name from institution order by institution_name")
            cursor.execute(query) 
            options = list(cursor)
            cursor.close()
        else:
            cnx, status = db.connect()
            cursor = cnx.cursor() 
            query = ("SELECT institutionid,institution_name from institution order by institution_name")
            cursor.execute(query)
            for (institutionid,institution_name) in cursor:
                options.append((institutionid, institution_name))
                if institution == "":
                    institution = str(institutionid)
            cursor.close() 

        if course:
            cnx, status = db.connect()
            cursor = cnx.cursor() 
            sql = "SELECT courseid,code from course where institutionid = %s"
            cursor.execute(sql, institution)
            optionsCourse = [(courseid, code) for courseid, code in cursor 
                                if permittedCourses is None or courseid in permittedCourses]
            cursor.close()   
        else:
            cnx, status = db.connect()
            cursor = cnx.cursor() 
            sql = "SELECT courseid,code from course where institutionid = %s"
            cursor.execute(sql, institution)
            for (courseid,code) in cursor:
                if permittedCourses is None or courseid in permittedCourses:
                    optionsCourse.append((courseid, code))
                    if course == "":
                        course = str(courseid)
            cursor.close()
        
        if course and (permittedCourses is None or course in permittedCourses):
             cnx, status = db.connect()
             cursor = cnx.cursor() 
             sql = "SELECT distinct a.student_info_id,a.givenname,a.surname from student_info a,student_course_link b, course c, course_stream d where c.courseid = %s and  c.courseid = d.courseid and d.coursestreamid =b.coursestreamid and b.studentinfoid = a.student_info_id"
             cursor.execute(sql, (course,))
             for (student_info_id,givenname,surname) in cursor:
                 optionsStudent.append((student_info_id, name(givenname, surname)))
                 if course == "":
                    course = str(courseid)
             cursor.close()
              

        return templating.render("admin_students_list.html", ROOT_URL=config.VIRTUAL_URL, ERROR=error,
                                REDIRECT=redirect, STATUS=status,
                                OPTION=options, INSTITUTION=institution, 
                                STUDENTNAME=studentName, STUDENTINSTITUTION=studentInstitution,
                                STUDENTCOURSES=studentCourses, STUDENTPROJECTS=studentProjects,
                                OPTIONCOURSE=optionsCourse, COURSE=course, OPTIONSTUDENT=optionsStudent, 
                                IS_ADMIN=isAdmin)
Beispiel #57
0
    def admin_students_search(self, searchValue="", id=None, *args, **kwargs):

        """
        Searches students by searchValue, displaying information for student number id. 

        >>> authorizeTests()
        >>> self = Admin()
        >>> ret = self.admin_students_search()
        >>> ret.SEARCHRESULT, ret.SEARCHVALUE
        ([], '')
        >>> ret.STUDENTNAME, ret.INSTITUTIONNAME, ret.STUDENTCOURSES, ret.STUDENTPROJECTS
        ('', '', [], [])

        >>> ret = self.admin_students_search("dav")
        >>> ret.SEARCHVALUE
        'dav'
        >>> (70, 'dave, dave') in ret.SEARCHRESULT
        True
        >>> ret.STUDENTNAME, ret.INSTITUTIONNAME, ret.STUDENTCOURSES, ret.STUDENTPROJECTS
        ('', '', [], [])

        >>> ret = self.admin_students_search("dav", 70)
        >>> ret.SEARCHVALUE
        'dav'
        >>> (70, 'dave, dave') in ret.SEARCHRESULT
        True
        >>> ret.STUDENTNAME, ret.INSTITUTIONNAME
        ('dave dave', 'Victoria University of Wellington')
        >>> ('Agile Methods', 'SWEN302', 2014, 1) in ret.STUDENTCOURSES
        True
        """
        isAdmin, _, permittedStudents = getAccessPermissions()

        allow(["HEAD", "GET", "POST"])
        error = ""
        searchResult = []
        redirect = "NO"
        status = "DB: Connection ok"
        studentCourses = []
        studentProjects = []
        empty = None

        if searchValue:
            cnx, status = db.connect()
            cursor = cnx.cursor()
            join = '%' + searchValue.upper() + '%'
            sql = "select student_info_id,surname,givenname from student_info where UPPER(givenname) like %s or UPPER(surname) like %s order by surname"
            cursor.execute(sql, (join,join))
            searchResult = [(id_, name(givenname, surname)) 
                            for id_, surname, givenname in cursor 
                            if permittedStudents is None or id_ in permittedStudents]
            cursor.close()
            cnx.close()
            if len(searchResult)< 1:
                empty = True
        status, studentName, institutionName, studentCourses, studentProjects = \
                studentInfo(id)
        
        return templating.render("admin_students_search.html", ROOT_URL=config.VIRTUAL_URL, ERROR=error,
                                REDIRECT=redirect, STATUS=status,
                                SEARCHRESULT=searchResult, SEARCHVALUE=searchValue,
                                STUDENTNAME=studentName, INSTITUTIONNAME=institutionName,
                                STUDENTCOURSES=studentCourses, STUDENTPROJECTS=studentProjects,
                                EMPTYRESULT=empty,
                                IS_ADMIN=isAdmin)
Beispiel #58
0
 def index(self, request):
     return render('home.html')
Beispiel #59
0
 def error404(self, msg=''):
     return render('error/404.html', msg=str(msg))
Beispiel #60
0
 def new(self, request):
     "Displays a form to input a new film"
     return render('film/new.html', film=self.relvar.default_tuple())