Views

A view is a Python function, which receives a web request and sends back a web response. The response of a view can be a simple string, web page, the content of a file, or anything. Whenever a Flask application gets a request from the client, it will look for a view function to service it. The view contains the business logic which is necessary to process a request.

In the previous sections, we have created the necessary database models. Now, in this section, we will write the view functions. Let us create view for every resource we mentioned in the previous table, which throws spot light on how we are going to design the URLs. All the views should be created in the file survey/views.py.

List of all questions

This view shows all the surveys that we have created in the database. The Flask application will invoke this view whenever the client requests the root of the application. Add the following code to the survey/views.py file:

from flask import render_template
from survey import app
from survey.models import Question

@app.route('/', methods=['GET'])
def home():
    questions = Question.query.all()
    context = {'questions': questions, 'number_of_questions': len(questions)}
    return render_template('index.html',**context)

The @app.route() decorator maps the path '/' and the view function home(). The home view retrieves all the questions from the database using the SQLAlchemy ORM and renders a template named 'index.html' using the render_template method. The render_template method takes the template name and a sequence of arguments to return a web page.

New survey

This view returns an HTML web form to create a new survey question. This view is called when a user visits the path /questions/new. Add the following code to the survey/views.py file:

. . .
. . .
@app.route('/questions/new', methods=['GET'])
def new_questions():
    return render_template('new.html')

Creating a new survey

This view creates a new survey in the database and shows the list of available questions as a response. This is invoked by the Flask application, when a user submits a request to a URL containing /questions, using the POST method. The data to create a new question can be accessed within a view using the request.form dictionary.

@app.route('/questions', methods=['POST'])
def create_questions():
    if request.form["question_text"].strip() != "":
        new_question = Question(question_text=request.form["question_text"])
        db.session.add(new_question)
        db.session.commit()
        message = "Succefully added a new poll!"
    else:
        message = "Poll question should not be an empty string!"

    context = {'questions': Question.query.all(),'message': message}
    return render_template('index.html',**context)

Displaying a survey

This view shows the requested survey using the question_id argument passed in the URL. This view gets triggered when a user requests the path '/questions/<question_id>' with the HTTP 'GET' verb:

@app.route('/questions/<int:question_id>', methods=['GET'])
def show_questions(question_id):
    context = {'question': Question.query.get(question_id)}
    return render_template('show.html', **context)

Updating a survey

This view is used whenever a user wants to modify an existing question. This is invoked when a user submits the data to modify the Question. We can connect with this resource using HTTP's 'PUT' method at '/questions/<question_id>':

@app.route('/questions/<int:question_id>', methods=['PUT'])
def update_questions(question_id):
    question = Question.query.get(question_id)
    if request.form["question_text"].strip() != "":
        question.question_text = request.form["question_text"]
        db.session.add(question)
        db.session.commit()
        message = "Successfully updated a poll!"
    else:

        message = "Question cannot be empty!"

    context = {'question': question,
               'message': message}

    return render_template('show.html', **context)

Deleting a survey

This view is used to delete a specific survey from the database. The specific survey is identified based on the question_id value passed in the URL. The users can access this web page at '/questions/<question_id>' using the 'DELETE' HTTP verb. Once the question gets deleted from the database, the user will be prompted with a message and a list of available questions.

@app.route('/questions/<int:question_id>', methods=['DELETE'])
def delete_questions(question_id):
    question = Question.query.get(question_id)
    db.session.delete(question)
    db.session.commit()
    context = {'questions': Question.query.all(),
               'message': 'Successfully deleted'}
    return render_template('index.html', **context)

New vote form to caste a vote in a survey

This view returns a web page containing a HTML form to vote a particular choice in a survey. It can be accessed at '/questions/<question_id>/vote'.

@app.route('/questions/<int:question_id>/vote', methods=['GET'])
def new_vote_questions(question_id):
    question = Question.query.get(question_id)
    context = {'question': question}
    return render_template('vote.html', **context)

Casting a vote to a particular choice in a survey

This view is used to cast a new vote to a particular choice in a survey. The user has to submit the specific choice to the resource '/questions/<question_id>/vote' using the 'POST' method. After the successful casting of a vote, the user is redirected to the survey details page.

@app.route('/questions/<int:question_id>/vote', methods=['POST'])
def create_vote_questions(question_id):
    question = Question.query.get(question_id)

    if request.form["vote"] in ["yes", "no", "maybe"]:
        question.vote(request.form["vote"])

    db.session.add(question)
    db.session.commit()
    return redirect("/questions/%d" % question.id)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.22.23