'''Returns a list of all rows from a cursor as a column: result dict.
Borrowed from Django documentation'''
desc=cursor.description
return[
dict(zip([col[0]forcolindesc],row))
forrowincursor.fetchall()
]
table=[]
table.append([col[0]forcolindesc])
table=table+cursor.fetchall()
print"Table: "+str(table)
returntable
defSQL_query_to_list(cursor,query_string):
cursor.execute(query_string)
raw_result=dictfetchall(cursor)
printraw_result
returnraw_result
defdashboard(request):
"""
Quick hack to show staff enrollment numbers. This should be
replaced with a real dashboard later. This version is a short-term
bandaid for the next couple weeks.
Slightly less hackish hack to show staff enrollment numbers and other
simple queries.
All queries here should be indexed and simple. Mostly, this means don't
touch courseware_studentmodule, as tempting as it may be.
"""
ifnotrequest.user.is_staff:
raiseHttp404
queries=[]
queries.append("select count(user_id) as students, course_id from student_courseenrollment group by course_id order by students desc;")
queries.append("select count(distinct user_id) as unique_students from student_courseenrollment;")
queries.append("select registrations, count(registrations) from (select count(user_id) as registrations from student_courseenrollment group by user_id) as registrations_per_user group by registrations;")
# results are passed to the template. The template knows how to render
# two types of results: scalars and tables. Scalars should be represented
# as "Visible Title": Value and tables should be lists of lists where each
results["scalars"]["Total Enrollments Across All Courses"]=CourseEnrollment.objects.count()
# establish a direct connection to the database (for executing raw SQL)
fromdjango.dbimportconnection
cursor=connection.cursor()
results=[]
forqueryinqueries:
cursor.execute(query)
results.append(dictfetchall(cursor))
# define the queries that will generate our user-facing tables
# table queries need not take the form of raw SQL, but do in this case since
# the MySQL backend for django isn't very friendly with group by or distinct
table_queries={}
table_queries["course enrollments"]="select count(user_id) as students, course_id from student_courseenrollment group by course_id order by students desc;"
table_queries["number of students in each number of classes"]="select registrations, count(registrations) from (select count(user_id) as registrations from student_courseenrollment group by user_id) as registrations_per_user group by registrations;"
# add the result for each of the table_queries to the results object