Advertisement
brains1960

Trails.py

Sep 27th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.29 KB | None | 0 0
  1. import bottle
  2. from bottle import route, run, template, Bottle
  3. from bottle import request, post, redirect
  4. import cgitb, csv
  5. import random
  6. from random import choice
  7. import os
  8. from sqlalchemy import create_engine
  9. import MySQLdb
  10.  
  11. THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
  12. cgitb.enable()
  13.  
  14. dbhost='StephenBroomell.mysql.pythonanywhere-services.com'
  15. dbuser='StephenBroomell'
  16. dbpass='L@bW3b31'
  17. dbname='StephenBroomell$trial_vars'
  18.  
  19. #sqlalchemy and mysql setup
  20. mysql_connect_string = 'mysql+mysqldb://%s:%s@%s/%s?charset=utf8' % (dbuser, dbpass, dbhost, dbname)
  21.  
  22. engine = create_engine(mysql_connect_string)
  23. from sqlalchemy.ext.declarative import declarative_base
  24. Base = declarative_base()
  25. Base.metadata.bind = engine
  26. from sqlalchemy import Column, Integer, String, Float, SmallInteger
  27. from sqlalchemy.orm import sessionmaker
  28. DBSession = sessionmaker()
  29. DBSession.bind = engine
  30.  
  31. #sqlalchemy model class for table 'nevek'
  32. class Variable(Base):
  33.     __tablename__ = 'vars'
  34.     # Here we define columns for the table nevek
  35.     id = Column(Integer, primary_key=True)
  36.     name = Column(String(250), nullable=False)
  37.     value = Column(String(250), nullable=False)
  38.  
  39. #get records from table nevek with sqlalchemy
  40. def get_vars_from_db():
  41.     session = DBSession()
  42.     result = session.query(Variable).all()
  43.     session.close()
  44.     return result
  45.  
  46. #get records from table nevek
  47. def get_raw_sql(sql):
  48.     conn = MySQLdb.connect(host=dbhost, user=dbuser,
  49.         passwd=dbpass, db=dbname, charset='utf8')
  50.     cur = conn.cursor()
  51.     cur.execute(sql)
  52.     res = cur.fetchall()
  53.     cur.close()
  54.     conn.close()
  55.     return res
  56.  
  57. def get_var(table, name):
  58.     return table[table[0:][1].index(name)][2]
  59.  
  60. def add_vars(name, value):
  61.     session = DBSession()
  62.     var = Variable(name=name, value=value)
  63.     session.add(var)
  64.     session.commit()
  65.  
  66.  
  67.  
  68. def set_vars_value(name, value):
  69.     conn = MySQLdb.connect(host=dbhost, user=dbuser,
  70.         passwd=dbpass, db=dbname, charset='utf8')
  71.     cursor = conn.cursor()
  72.     cursor.execute ("""
  73.       UPDATE vars
  74.       SET name=%s, value=%s
  75.       WHERE ID=%s
  76.    """, (name, value, vars[0:][1].index(name)))
  77.  
  78. context = {}
  79.  
  80. @route('/location', method=['POST'])
  81. def do_location():
  82.  
  83.     global context
  84.     city = int(request.forms.get('location'))
  85.     unit = request.forms.get('unit')
  86.  
  87.     get_raw_sql('TRUNCATE TABLE vars')
  88.  
  89.     context = {}
  90.  
  91.     add_vars("city",city)
  92.     add_vars("unit",unit)
  93.     add_vars("current_trial",1)
  94.     #add_vars('context',context)
  95.     if (city > 51):
  96.         return template('city_select.html', locErr="Please Select a city from the list", page_name="- Location", **context)
  97.     else:
  98.         redirect('/trials')
  99.  
  100. @route('/trials')
  101. def trials():
  102.  
  103.     global context
  104.     #response.set_cookie("visited", "yes");
  105.     dates = ["na"]*7
  106.     highs = ["na"]*7
  107.     lows = ["na"]*7
  108.  
  109.     vars = get_raw_sql("SELECT *  FROM vars")
  110.     unit = context['unit']
  111.     city = context['city']
  112.     trialsPassed = []
  113.     trialsNum = 1
  114.     trialsLeft = []
  115.  
  116.     file = os.path.join(THIS_FOLDER, 'data/'+str(city)+'_web.csv')
  117.     cityData = list(csv.reader(open(file)))
  118.  
  119.     trialsLeft = range(len(cityData))
  120.     rowNum = random.choice(trialsLeft)
  121.     trialsPassed.append(rowNum)
  122.     trialsLeft.remove(rowNum)
  123.     datefile = os.path.join(THIS_FOLDER,'data/Dates.csv')
  124.     dates = list(csv.reader(open(datefile)))[rowNum]
  125.     highs = cityData[rowNum][0:7]
  126.     lows = cityData[rowNum][7:14]
  127.  
  128.     if (unit == "C"):
  129.         highs = [int((int(x)-32)*(5.0/9)) for x in highs]
  130.         lows = [int((int(x)-32)*(5.0/9)) for x in lows]
  131.  
  132.     colours = ["red", "orange","yellow","green","blue", "indigo","violet"]
  133.  
  134.  
  135.     context = {
  136.  
  137.         "colour":colours[trialsNum/8],
  138.         "page_name":"Trials",
  139.         "current_trial" : trialsNum,
  140.         "city": city,
  141.         "cityData" : cityData,
  142.         "day_1" : dates[0],
  143.         "day_2" : dates[1],
  144.         "day_3" : dates[2],
  145.         "day_4" : dates[3],
  146.         "day_5" : dates[4],
  147.         "day_6" : dates[5],
  148.         "day_7" : dates[6],
  149.         "high_1" : highs[0],
  150.         "high_2" : highs[1],
  151.         "high_3" : highs[2],
  152.         "high_4" : highs[3],
  153.         "high_5" : highs[4],
  154.         "high_6" : highs[5],
  155.         "high_7" : highs[6],
  156.         "low_1" : lows[0],
  157.         "low_2" : lows[1],
  158.         "low_3" : lows[2],
  159.         "low_4" : lows[3],
  160.         "low_5" : lows[4],
  161.         "low_6" : lows[5],
  162.         "low_7" : lows[6],
  163.         "trial_num" : (trialsNum/52*100),
  164.         "trials_passed" : trialsPassed,
  165.         "trials_left" : trialsLeft,
  166.         "unit":unit,
  167.         "week" : rowNum,
  168.         "row" : []
  169.  
  170.     }
  171.  
  172.     return template('trials.html', **context)
  173.  
  174. @route('/trials', method=['POST'])
  175. def do_trials():
  176.  
  177.     normal = request.forms.get('normalcheck')
  178.     confidence = request.forms.get('confidencecheck')
  179.  
  180.     global context
  181.  
  182.     if (get_var(vars,'current_trial') == 52):
  183.         with open('results.csv', 'w+') as resultFile:
  184.             wr = csv.writer(resultFile, dialect='excel')
  185.             id = len(list(csv.reader(resultFile)))+1
  186.             wr.writerow([id, context['city']] + context['row'])
  187.         redirect('/')
  188.     else:
  189.         dates = ["na"]*7
  190.         highs = ["na"]*7
  191.         lows = ["na"]*7
  192.  
  193.         colours = ["red", "orange","yellow","green","blue", "indigo","violet"]
  194.  
  195.         cityData = context['cityData']
  196.         rowNum = choice(context['trials_left'])
  197.         context['trials_passed'].append(rowNum)
  198.         context['trials_left'].remove(rowNum)
  199.         dates = list(csv.reader(open(os.path.join(THIS_FOLDER,'data/Dates.csv'))))[rowNum]
  200.         highs = cityData[rowNum][0:7]
  201.         #print highs
  202.         lows = cityData[rowNum][7:14]
  203.         #print lows
  204.  
  205.         context['current_trial'] += 1
  206.         colours = ["red", "orange","yellow","green","blue", "indigo","violet"]
  207.  
  208.  
  209.         context["colour"] = colours[context['current_trial']/8]
  210.         context["page_name"] = "Trials"
  211.         context["day_1"] = dates[0]
  212.         context["day_2"] = dates[1]
  213.         context["day_3"] = dates[2]
  214.         context["day_4"] = dates[3]
  215.         context["day_5"] = dates[4]
  216.         context["day_6"] = dates[5]
  217.         context["day_7"] = dates[6]
  218.         context["high_1"] = highs[0]
  219.         context["high_2"] = highs[1]
  220.         context["high_3"] = highs[2]
  221.         context["high_4"] = highs[3]
  222.         context["high_5"] = highs[4]
  223.         context["high_6"] = highs[5]
  224.         context["high_7"] = highs[6]
  225.         context["low_1"] = lows[0]
  226.         context["low_2"] = lows[1]
  227.         context["low_3"] = lows[2]
  228.         context["low_4"] = lows[3]
  229.         context["low_5"] = lows[4]
  230.         context["low_6"] = lows[5]
  231.         context["low_7"] = lows[6]
  232.         context["trial_num"] = round(context['current_trial']/52.0*100)
  233.         context["row"] = context['row'] + [rowNum,normal,confidence]
  234.  
  235.  
  236.  
  237.     return template('trials.html', **context)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement