Views

Flask views are Python functions that, when paired with the app controller object and its app.route URL definitions, allows us to write Python code to accept a web request, process it, and return a response. They are the heart of the web application, making it possible to connect web pages and their forms to the database and its tables.

To create views, we will import all of the application components along with a number of Flask functions. The forms and models are imported from their respective scripts, as is the app object:

from application import app
from flask import render_template,jsonify, redirect, url_for, request
from .forms import *
from .models import *

For the Arena application, we have two views defined that create two application URL endpoints. The first view, home, is in place only to redirect requests to the IP address root. Using the Flask functions redirect and url_for, any web requests sent to the root address will be redirected to the arenas view:

@app.route('/', methods=["GET"])
def home():
return redirect(url_for('arenas'))

The second view, arenas, is more complex. It accepts both GET and POST request methods. Depending on the request method, the data processed and returned will be different, though they both rely on the template index.html which is stored in the application/templates folder (where all Flask HTML templates are stored). Here is the complete view:

@app.route('/arenas', methods=["GET","POST"])
def arenas():
form = ArenaForm(request.form)
arenas = session.query(Arena).all()
form.selections.choices = [(arena.id,
arena.name) for arena in arenas]
form.popup = "Select an Arena"
form.latitude = 38.89517
form.longitude = -77.03682
if request.method == "POST":
arena_id = form.selections.data
arena = session.query(Arena).get(arena_id)
form.longitude = round(arena.longitude,4)
form.latitude = round(arena.latitude,4)
county=session.query(County).filter(
County.geom.ST_Contains(arena.geom)).first()
if county != None:
district=session.query(District).filter(
District.geom.ST_Intersects(arena.geom)).first()
state = county.state_ref
form.popup = """The {0} is located at {4}, {5}, which is in
{1} County, {3}, and in {3} Congressional District
{2}.""".format(arena.name,county.name, district.district,
state.name,
form.longitude, form.latitude)

else:
form.popup = """The county, district, and state could
not be located using point in polygon analysis"""

return render_template('index.html',form=form)
return render_template('index.html',form=form)
..................Content has been hidden....................

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