#!/usr/local/bin/python2.7 from flask import Flask, render_template, url_for, request, redirect, flash import math import random app = Flask(__name__) # necessary for flashing app.secret_key = 'now is the winter of our discontent' numRequests = 0 @app.route('/') def welcome(): global numRequests numRequests += 1 exes = [ 'capitals/Paris', 'sqrt/16.0', 'sqrt/17.1', 'print_stmt', 'console_error', 'no_view', 'urls', 'canonical', 'canonical/', 'fragile', 'fragile/', 'form/', 'render/', 'render_styled/', 'login/', 'logged_in/', 'shoo/', 'login_again/' ] links = [ '
Hello World! These are the examples for lecture 2.
Try
There have been {n} requests since this app
started'''.format(n=numRequests,examples=''.join(links))
@app.route('/capitals/ {city} is the capital of {country}'.format(city=city,country=known[city])
else:
return ''' I don't know the country whose capital is {city}'''.format(city=city)
@app.route('/sqrt/ {x} is the square root of {y}'.format(x=math.sqrt(abs(n)),y=n)
@app.route('/print_stmt/')
def print_stmt():
n = random.randint(1,10)
print 'n is ',n
return ' Can you guess your lucky number?'
@app.route('/console_error/')
def console_error():
# this doesn't work
roman = ['x','v','i','c','m','d','l']
s = random.choice(roman)
n = int(s)
print '{roman} converts to {arabic}'.format(roman=s,arabic=n)
@app.route('/no_view/')
def no_view():
n = random.randint(1,10)
if n < 9:
print ' Keep trying, you only scored a {n}'.format(n=n)
else:
return ' Wow, you scored a 10!!'
@app.route('/urls/')
def urls():
hrefs = [ url_for('print_stmt'),
url_for('capitals', city='London'),
url_for('sqrt', n=18)
]
links = [ ' {h}'.format(h=h)
for h in hrefs ]
return ''.join(links)
@app.route('/canonical/')
def canonical():
return ' Well done!'
@app.route('/fragile')
def fragile():
return ' Maybe?'
@app.route('/form/')
def form():
f = ''' Your form was submitted via {meth} and contained
Welcome Admin!'
@app.route('/shoo/')
def shoo():
return ' Wrong password; go away!'
@app.route('/login_again/', methods=['GET','POST'])
def login_again():
if request.method == 'GET':
return render_template('login_flashing.html',script=url_for('login_again'))
else:
if request.form['user'] == 'admin' and request.form['pass'] == 'secret':
return redirect( url_for('logged_in') )
else:
flash("No, sorry; please try again")
return redirect( url_for('login_again') )
if __name__ == '__main__':
app.debug = True
app.run('0.0.0.0',2716)