Skip to content

Instantly share code, notes, and snippets.

@paj28
Created August 13, 2017 05:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paj28/bf0f7718c64c3ff9de195c59e2ae3754 to your computer and use it in GitHub Desktop.
Save paj28/bf0f7718c64c3ff9de195c59e2ae3754 to your computer and use it in GitHub Desktop.
import flask, pymysql, threading, html
app = flask.Flask(__name__)
application=app
pool = {}
def get_connection():
id = threading.current_thread()
if id not in pool:
pool[id] = pymysql.connect(host='localhost', user='user', password='letmein', db='ctf', charset='utf8')
return pool[id]
def rank2risk(rank):
if rank > 20000:
return 'low', 1
elif rank > 1000:
return 'medium', 2
else:
return 'high', 3
@app.route("/")
def login():
print('x')
return flask.send_file('templates/index.html')
@app.route("/risk")
def risk():
print('y')
return flask.send_file('templates/risk.html')
@app.route("/quote", methods=['GET'])
def get_quote():
return flask.render_template('form.html', errors={})
@app.route("/quote", methods=['POST'])
def post_quote():
try:
errors = {}
value = flask.request.form.get('value', '')
try:
value_int = int(value)
except ValueError:
value_int = 0
if not(1000 <= value_int <= 100000):
errors['value'] = 'Must be a number between 1000 and 100000'
crime_rank = None
postcode = flask.request.form.get('postcode', '')
postcode_norm = postcode.upper().replace(' ', '')
with get_connection().cursor() as cursor:
cursor.execute("select crime_rank from lsoa_crime_rank join postcode_lsoa using(lsoa) where postcode=%s", postcode_norm)
results = cursor.fetchall()
if not results:
errors['postcode'] = 'Must be a residential postcode in England'
else:
crime_rank = results[0][0]
risk = None
if crime_rank:
risk, premium_percent = rank2risk(crime_rank)
alarm = flask.request.form.get('alarm')
if risk == 'high' and not alarm:
errors['alarm'] = 'Not answered'
if errors:
return flask.render_template('form.html', **locals())
conditions = ''
if risk == 'high':
if alarm != 'yes':
premium_percent += 1
with get_connection().cursor() as cursor:
cursor.execute("select conditions from alarm_conditions where status='%s'" % alarm)
for row in cursor.fetchall():
conditions += row[0] + ' '
premium = value_int * premium_percent / 100
return flask.render_template('quote.html', **locals())
except Exception as e:
return html.escape(str(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment