...
 
Commits (2)
from flask import Flask, render_template, redirect, flash, request
from flask_flatpages import FlatPages
import markdown
import random, copy
import os
import glob
from flask_mongoengine import *
from flask_security import Security, MongoEngineUserDatastore, UserMixin, RoleMixin, login_required, current_user
from flask_mail import Mail
from flask_security.forms import RegisterForm, StringField
from wtforms.validators import DataRequired
from pymongo import MongoClient
import os
import glob
import copy
import json
import random
DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.md'
FLATPAGES_MARKDOWN_EXTENSIONS = ['markdown.extensions.extra', 'headerid']
app = Flask(__name__)
#app.config.from_pyfile('mysettings.cfg')
app.config.from_object(__name__)
pages = FlatPages(app)
# Flask Security settings
app.config['SECRET_KEY'] = 'super-secret'
app.config['SECURITY_REGISTERABLE'] = True
......@@ -41,12 +47,6 @@ app.config['MONGODB_PORT'] = 27017
# Create database connection object
db = MongoEngine(app)
# Setup Flask-Security
user_datastore = MongoEngineUserDatastore(db, User, Role )
#security = Security(app, user_datastore)
security = Security(app, user_datastore, register_form=ExtendedRegisterForm)
class Role(db.Document, RoleMixin):
name = db.StringField(max_length=80, unique=True)
description = db.StringField(max_length=255)
......@@ -66,10 +66,12 @@ class ExtendedRegisterForm(RegisterForm):
first_name = StringField('First Name', validators=[DataRequired()])
last_name = StringField('Last Name', validators=[DataRequired()])
app = Flask(__name__)
#app.config.from_pyfile('mysettings.cfg')
app.config.from_object(__name__)
pages = FlatPages(app)
# Setup Flask-Security
user_datastore = MongoEngineUserDatastore(db, User, Role )
#security = Security(app, user_datastore)
security = Security(app, user_datastore, register_form=ExtendedRegisterForm)
@app.route("/")
@app.route("/index")
......@@ -91,6 +93,54 @@ def page(path):
print(page)
return render_template('flatpage.html', page=page)
quiz_dir = 'app/quizzes'
quizzes = {}
for quiz in os.listdir(quiz_dir):
#print('Loading, ' + quiz)
quizzes[quiz] = json.loads(open(os.path.join(quiz_dir, quiz)).read())
@app.route('/quizzes')
def quizs():
quiz_names = zip(quizzes.keys(), map(lambda q: q['name'], quizzes.values()))
returnQuiz_names = list(quiz_names)
print(returnQuiz_names)
return render_template('quizzes.html', quiz_names=returnQuiz_names)
@app.route('/quiz/<id>')
def quiz(id):
if id not in quizzes:
return abort(404)
quiz = copy.deepcopy(quizzes[id])
questions = list(enumerate(quiz["questions"]))
random.shuffle(questions)
quiz["questions"] = map(lambda t: t[1], questions)
ordering = list(map(lambda t: t[0], questions))
return render_template('quiz.html', id=id, quiz=quiz, quiz_ordering=json.dumps(ordering))
@app.route('/check_quiz/<id>', methods=['POST'])
def check_quiz(id):
ordering = json.loads(request.form['ord'])
quiz = copy.deepcopy(quizzes[id])
# print(request.form)
quiz['questions'] = sorted(quiz['questions'], key=lambda q: ordering.index(quiz['questions'].index(q)))
print(quiz['questions'])
answers = dict( (int(k), quiz['questions'][int(k)]['options'][int(v)]) for k, v in request.form.items() if k != 'ord' )
print(answers)
if not len(answers.keys()):
return redirect(url_for('quiz', id=id))
for k in range(len(ordering)):
if k not in answers:
answers[k] = [None, False]
answers_list = [ answers[k] for k in sorted(answers.keys()) ]
number_correct = len(list(filter(lambda t: t[1], answers_list)))
return render_template('check_quiz.html', quiz=quiz, question_answer=zip(quiz['questions'], answers_list), correct=number_correct, total=len(answers_list))
@app.route("/contact")
def contact():
......
{
"name": "Reddiquette Quiz",
"description": "How well versed are you in the rules of Reddit? Quiz yoself before you run afoul!",
"badge": "electronique",
"questions": [
{
"text": "Reddiquette is the ettiquette of which site?",
"options": [
["4chan", false],
["Reddit", true],
["9gag", false],
["iFunny", false]
]
},
{
"text": "Reddiquette suggests that you should",
"options": [
["Dox your enemies in /r/politics arguments", false],
["Spam your own blog for the sweet, sweet money", false],
["Look for original content", true],
["Create a hilarious and quirky name like I_DIDDLE_CATS to whore karma", false]
]
},
{
"text": "You should...",
"options": [
["Ignore the Reddiquette", false],
["Not ignore the Reddiquette", true]
]
},
{
"text": "Do...",
"options": [
["Use the word BREAKING in titles", false],
["Write titles in ALL CAPS", false],
["Use link shorteners", false],
["Linkjack stories to blogspam", false],
["Be a pretty cool guy", true],
["Be a VERY cool guy", true],
["Complain about reposts", false]
]
},
{
"text": "Reddit suggests that you should...",
"options": [
["Do illegal things on the site", false],
["Don't do illegal things", true]
]
}
]
}
{% extends "quiz_base.html" %}
{% block title %} {{quiz['name']}} {% endblock %}
{% block content %}
{{quiz['name']}} - Checking ({{correct}} / {{total}})
{{ super() }}
<style type="text/css">
.question-correct:after {
content: "✓";
font-size: 30px;
color: green;
padding-left: 10px;
}
.question-incorrect:after {
content: "✗";
font-size: 30px;
color: red;
padding-left: 10px;
}
</style>
{% for question, choice in question_answer %}
<div>
<h4 {% if choice[1] %} class="question-correct" {% else %} class="question-incorrect" {% endif %}>{{question['text']|safe}}</h4>
{% for answer in question['options'] %}
<p {% if answer[1] %} class="question-correct" {% elif not answer[1] %} class="question-incorrect" {% endif %}>
{{answer[0]|safe}} {% if answer == choice %} - <strong> Chosen </strong> {% endif %}
</p>
{% endfor %}
</div>
{% if loop.revindex0 > 0 %}
<hr />
{% endif %}
{% endfor %}
{% endblock %}
{% if current_user.is_authenticated %}
<h1>Quiz !</h1>
<div class="tutoWrapper">
<div class="container">
<form action='/learn/check' method='POST'>
<ol>
{% for i in q %}
<li>Where is <u>{{i}}</u> located?</li>
{% for j in o[i] %}
<input type='radio' value='{{j}}' name='{{i}}' />{{j}}
{% endfor %}
{% endfor %}
</ol>
<input type="submit" value="voir mon resultat" />
</form>
</div>
</div>
{% else %}
<h1> Un quiz est disponible pour ce contenu, mais il vous faut <a href="/login">etre logge dans le systeme</a> afin de le suivre.</h1>
{% endif %}
{% extends "quiz_base.html" %}
{% block content %}
<form method="post" action="/check_quiz/{{id}}">
<input type="hidden" name="ord" value="{{quiz_ordering}}" />
{% for question in quiz['questions'] %}
{% set outer_loop = loop %}
<p>
<h4>{{question['text']|safe}}</h4>
{% for answer in question['options'] %}
<p><label><input type="radio" name="{{outer_loop.index0}}" value="{{loop.index0}}" /> {{answer[0]|safe}}</label></p>
{% endfor %}
</p>
{% endfor %}
<input type="submit" value="Submit Your Quiz">
</form>
{% endblock %}
{% extends "base.html" %}
{% block title %} {{quiz['name']}} {% endblock %}
{% block body %}
<div id='content'>
<span id='title'>{% block page_title %} {% endblock %}</span>
<p>{{quiz['description']|safe}}</p>
{% block questions %} {% endblock %}
</div>
{% endblock %}
\ No newline at end of file
{% extends "base.html" %}
{% block title %} Quiz Website - All Quizzes {% endblock %}
{% block content %}
<div id='content'>
<span id='title'>All Quizzes</span>
<ul>
{{quiz_names}}
{% for id, name in quiz_names %}
<li><a href="{{url_for('quiz', id=id)}}">{{name}}</a></li>
{% endfor %}
</ul>
</div>
{% endblock %}