Create init.py file inside a folder with name quizApp and then initialize and configure our application such as creating instance of Flask, SQLAlchemy, LoginManager classes and configure them and finally importing routes from routes.py as shown below.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
app = Flask(__name__)
app.config['SECRET_KEY'] = ''
app.config['SQLALCHEMY_DATABASE_URI'] = ''
db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'index'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
from quizApp import routes
Create routes.py in the same folder and create all the routes required for our Application. Here in this example we can see only 2 routes but there are total 10 routes in this application including the following given routes.
- index route :
@app.route('/', methods = ['GET', 'POST'])
@app.route('/index', methods = ['GET', 'POST'])
def index():
if current_user.is_authenticated:
return redirect(url_for('scoreBoard', _UID = current_user.userID))
#..
if form.validate_on_submit():
#..
return redirect(url_for('questionType'))
return render_template('index.html', form = form)
- questionType route :
@app.route('/questionType', methods = ['GET', 'POST'])
@login_required
def questionType():
form1 = SubmitOwn()
form2 = SubmitReady()
if bool(Q_A.query.filter_by(user_ID = current_user.userID).first()):
return redirect(url_for('scoreBoard', _UID = current_user.userID))
if form1.submitOwn.data:
return redirect(url_for('ownQue'))
if form2.submitReady.data:
return redirect(url_for('readyMadeQue'))
return render_template('questionType.html', form1 = form1, form2 = form2)
There are other routes such as ownQue, readyMadeQue, shareQuiz, playQuiz, scoreBoard, player and logout routes in this application. Create template and static folders which will include html and css files for our application.
Now let’s create WTForms for our Applications so that we can take user inputs and store it in our database. For creating WTForms lets first create form.py inside the same directory as init.py and routes.py file as shown in Project Tree. Inside of form.py lets create all the forms classes by inheriting the FlaskForm class form flask_wtf module and make instance of wtforms classes as field for our forms.
class RegisterName(FlaskForm):
username = StringField('Enter Your Name', validators=[DataRequired(), Length(min=2, max=20)])
submit = SubmitField('Create Quiz')
class SubmitOwn(FlaskForm):
submitOwn = SubmitField('Create your own questions')
class SubmitReady(FlaskForm):
submitReady = SubmitField('Ready-made questions')
class ReadymadeForm(FlaskForm):
#..
class OwnMade(FlaskForm):
#..
class PlayQuiz(FlaskForm):
nxt = SubmitField('SUBMIT')
class PlayerForm(FlaskForm):
#..
After creating all the templates, routes and forms for our application lets create the sqlite database for our application by creating a model.py file which will include all the tables and their columns as classes which inherits db.Model and UserMixin classes. model.py file will also include login_manager which will handel login sessions of user for the database.
@login_manager.user_loader
def laod_user(userID):
return Users.query.get(int(userID))
class Users(db.Model, UserMixin):
__tablename__ = 'Users'
userID = db.Column(db.Integer, nullable = False, primary_key = True, autoincrement = True)
name = db.Column(db.String, nullable = False)
QAs = db.relationship('Q_A', backref = 'U_ID', lazy = 'dynamic')
def get_id(self):
return (self.userID)
def __repr__(self):
return f'User("{self.userID}", "{self.name}")'
class Q_A(db.Model, UserMixin):
__tablename__ = 'Q_A'
#..
class Player(db.Model, UserMixin):
__tablename__ = 'Player'
#..
class Scoreboard(db.Model, UserMixin):
__tablename__ = 'Scoreboard'
#..
class Readymade(db.Model, UserMixin):
#..
At last lets create run.py file which only when executed will run and initialize our entire project in the parent directory of the project folder as shown in Project Tree.
from quizApp import app
if __name__ == '__main__':
app.run(debug = False)
But before running the Application with run.pyfile first create and initialize the site.db database to store the data in it. To create the database and initialize it open the terminal or Command prompt in the project directory and run the python interpreter inside it.
E:\Flask Website>python
Python 3.8.2 ..
>>> from quizApp import db
>>> db.create_all()
>>>
After starting the python interpreter import the db instance from our init.py through quizApp folder, you may get some warning but it’s just some deprecation warning. After importing db which is our SQLAlchemy class instance call the create_all() method from it which will create site.db database for our project. After successfully creating our database file now we are ready to run our Application on localhost by running the run.py file which will start host a local server at a particular port which will shown with address of localhost. You can now enter that address of localhost at which your application is running inside your URL field of browser. I have also hosted this application online you can check it by visiting below link of our Web Application.