This video is available to students only

Adding another blueprint

Our application is pretty functional at this point, but there's no real way to navigate from within the application, you have to directly change the URL. Let's fix that. A good user experience would be for the home page to have a field that you can type a ticker into (like Google's search page) and once you submit it, it'll take you to the page for that ticker.

Right now, our home page is served from a route directly defined from server.py. Since we'll have to create at least one other route, lets create a new blueprint for the home page. We can follow the same process for creating a blueprint we followed earlier:

  1. Create a Python file to define the blueprint in: blueprints/home.py
  2. Within the file, initialize a Blueprint object with the name of the blueprint and define the routes
from flask import Blueprint, render_template
home = Blueprint('home', __name__)

@home.route('/')
def index():
    return render_template('home/index.html')
  1. Create a folder in the templates folder for the blueprint, move templates
  2. Update any references to the path in url_for with the prefix being the name of the blueprint (home.index)

To support a form, we're going to need to a route that accepts the input and redirects users to the right page. So far we have only been dealing with GET requests (when our browser requests a page). By default, Flask assumes routes you define are responding to GET requests. This route is going to receive a POST request from the HTML form, so we need to explicitly tell Flask to route POST requests to it by passing "POST" into the optional methods argument to the route decorator, like so @home.route('/lookup', methods=['POST'])

Once we have the routing set up, we can access the form data through Flask's request object. The request that we can import from Flask can be used within routes to get information about the current request that Flask is serving. Finally, to issue a redirect to the ticker page, we use the redirect function from Flask and pass in the URL we want to send users to.

stock-app/blueprints/home.py
from flask import Blueprint, render_template, redirect, request, url_for

home = Blueprint('home', __name__)

@home.route('/')
def index():
    return render_template('home/index.html')

@home.route('/lookup', methods=['POST'])
def lookup():
    return redirect(url_for('stock.view_stock', ticker=request.form["ticker"]))

HTTP Concept: Instead of returning a HTTP 200 with data that the browser can render, the redirect returns a HTTP 302 and specifies where to send the user to

Now to add a form on the frontend, we need to add some HTML to the template. Since we are expecting a POST request with a ticker parameter sent to the lookup route (which is defined in the home blueprint) , our form will look like this:

Start a new discussion. All notification go to the author.