Ejemplo n.º 1
0
 def index(self):
     "Show processors that have updated in the last hour"
     c.processors = (
         Session.query(model.Processor)
         .filter(model.Processor.when_updated > datetime.datetime.utcnow() - datetime.timedelta(days=1))
         .order_by(model.Processor.when_updated.desc())
         .all()
     )
     return render("/processors/index.mako")
Ejemplo n.º 2
0
 def index(self, format="html"):
     "GET /: Show landing page if not logged in"
     # Initialize
     personID = h.getPersonID()
     # If not logged in,
     if not personID:
         return render("/landing/index.mako")
     # Take them to the scenarios,
     else:
         return redirect(url("scenario_index"))
Ejemplo n.º 3
0
 def index(self, format='html'):
     'GET /scenarios: Show all items in the collection'
     # Initialize
     personID = h.getPersonID()
     refresh = request.GET.get('refresh', 0)
     scope = request.GET.get('scope', str(model.scopePrivate))
     # Load
     scenarioQuery = Session.query(model.Scenario)
     if not personID:
         scenarioQuery = scenarioQuery.filter_by(scope=model.scopePublic)
     elif scope == '-':
         scenarioQuery = scenarioQuery.filter_by(owner_id=personID)
     elif scope == '*':
         scenarioQuery = scenarioQuery.filter(model.getScopeFilter(personID))
     else:
         scenarioQuery = scenarioQuery.filter_by(owner_id=personID).filter_by(scope=model.scopePrivate)
     c.scenarios = scenarioQuery.options(orm.eagerload(model.Scenario.owner)).order_by(model.Scenario.when_created.desc()).all()
     # If this is not a refresh request,
     if not refresh:
         return render('/scenarios/index.mako')
     # If this is a refresh request,
     else:
         return render('/scenarios/scenarios.mako')
Ejemplo n.º 4
0
 def update(self):
     'Show account update page'
     # Load
     personID = h.getPersonID()
     # If the person is not logged in,
     if not personID:
         # Return
         return redirect(url('person_login', targetURL=h.encodeURL('/')))
     # Render
     c.isNew = False
     person = Session.query(model.Person).get(personID)
     # Return
     return formencode.htmlfill.render(render('/people/change.mako'), {
         'username': person.username,
         'nickname': person.nickname,
         'email': person.email,
         'email_sms': person.email_sms,
     })
Ejemplo n.º 5
0
 def clone(self, scenarioID):
     'Show form to create a new item based on datasets and parameters from existing scenario'
     # Make sure the user is logged in
     personID = h.getPersonID()
     if not personID:
         return redirect(url('person_login', targetURL=h.encodeURL(request.path)))
     # Make sure the user has access to the scenario
     scenario = Session.query(model.Scenario).filter(model.getScopeFilter(personID)).filter(model.Scenario.id==scenarioID).first()
     if not scenario:
         return redirect(url('new_scenario'))
     # Load
     scenarioInput = scenario.input
     # Prepare
     c.scenario = scenario
     c.metricModel = metric.getModel(request.GET.get('metricModel', scenarioInput['metric model name']))
     c.metricConfiguration = scenarioInput['metric configuration']
     c.networkModel = network.getModel(request.GET.get('networkModel', scenarioInput['network model name']))
     c.networkConfiguration = scenarioInput['network configuration']
     # Return
     return render('/scenarios/new.mako')
Ejemplo n.º 6
0
 def update(self):
     "Show account update page"
     # Load
     personID = h.getPersonID()
     # If the person is not logged in,
     if not personID:
         # Return
         return redirect(url("person_login", targetURL=h.encodeURL("/")))
     # Render
     c.isNew = False
     person = Session.query(model.Person).get(personID)
     # Return
     return formencode.htmlfill.render(
         render("/people/change.mako"),
         {
             "username": person.username,
             "nickname": person.nickname,
             "email": person.email,
             "email_sms": person.email_sms,
         },
     )
Ejemplo n.º 7
0
 def new(self, format='html'):
     'GET /scenarios/new: Show form to create a new item'
     # If the user is not logged in,
     if not h.isPerson():
         # Redirect to login
         return redirect(url('person_login', targetURL=h.encodeURL(h.url('new_scenario'))))
     # Make sure that the requested metric model exists
     metricModelNames = metric.getModelNames()
     metricModelName = request.GET.get('metricModel')
     if metricModelName not in metricModelNames:
         metricModelName = metricModelNames[0]
     c.metricModel = metric.getModel(metricModelName)
     c.metricConfiguration = {}
     # Make sure that the requested network model exists
     networkModelNames = network.getModelNames()
     networkModelName = request.GET.get('networkModel')
     if networkModelName not in networkModelNames:
         networkModelName = networkModelNames[0]
     c.networkModel = network.getModel(networkModelName)
     c.networkConfiguration = {}
     # Render form
     c.scenario = None
     return render('/scenarios/new.mako')
Ejemplo n.º 8
0
 def show(self, id, format='html'):
     'GET /scenarios/id: Show a specific item'
     # If the output format is not supported, 
     if format not in ['html', 'zip', 'geojson', 'json']: 
         return 'Unsupported output format: ' + format 
     try:
         id = int(id)
     except ValueError:
         return redirect(url('scenarios'))
     # Load
     personID = h.getPersonID()
     c.scenario = Session.query(model.Scenario).filter(model.Scenario.id==id).filter(model.getScopeFilter(personID)).first()
     # If user does not have access to the scenario,
     if not c.scenario:
         c.status = model.statusFailed
         if format == 'html':
             return render('/scenarios/show.mako')
         elif format == 'zip':
             return ''
         elif format == 'geojson':
             return geojson.dumps(geojson.FeatureCollection([]))
         elif format == 'json':
             return cjson.encode({})
     # If the scenario has an error,
     if c.scenario.status == model.statusFailed:
         c.traceback = c.scenario.output['traceback']
         c.status = model.statusFailed
         if format == 'html':
             return render('/scenarios/show.mako')
         elif format == 'zip':
             return forward(FileApp(c.scenario.getFolder() + '.zip'))
         elif format == 'geojson':
             return geojson.dumps(geojson.FeatureCollection([]))
         elif format == 'json':
             return c.scenario.exportJSON()
     # If the scenario has not been processed,
     if c.scenario.isQueued():
         c.status = model.statusPending
         if format == 'html':
             return render('/scenarios/show.mako')
         elif format == 'zip':
             return forward(FileApp(c.scenario.getFolder() + '.zip'))
         elif format == 'geojson':
             return geojson.dumps(geojson.FeatureCollection([]))
         elif format == 'json':
             return c.scenario.exportJSON()
     # Prepare
     c.status = model.statusDone
     c.scenarioInput = c.scenario.input
     c.scenarioOutput = c.scenario.output
     transform_point = geometry_store.get_transform_point(geometry_store.proj4LL, geometry_store.proj4SM)
     # If the user wants HTML,
     if format == 'html':
         # Render scenario
         c.metricModel = metric.getModel(c.scenarioInput['metric model name'])
         scenarioStatistics = c.scenarioOutput['statistics']
         nodeStatistics = scenarioStatistics['node']
         # Prepare map
         centerX, centerY = transform_point(nodeStatistics['mean longitude'], nodeStatistics['mean latitude'])
         box1X, box1Y = transform_point(nodeStatistics['minimum longitude'], nodeStatistics['maximum latitude'])
         box2X, box2Y = transform_point(nodeStatistics['maximum longitude'], nodeStatistics['minimum latitude'])
         # Render map
         datasetStore = c.scenario.getDataset()
         c.mapFeatures = datasetStore.exportGeoJSON(transform_point)
         c.mapCenter = '%s, %s' % (centerX, centerY)
         c.mapBox = '%s, %s, %s, %s' % (box1X, box1Y, box2X, box2Y)
         # Render nodes
         c.nodes = list(datasetStore.cycleNodes())
         c.populationQuartiles = scenarioStatistics['metric']['population quartiles']
         # Render scenarios
         c.scenarios = Session.query(model.Scenario).filter(model.getScopeFilter(personID)).filter(model.Scenario.status==model.statusDone).filter(model.Scenario.id!=c.scenario.id).order_by(model.Scenario.id.desc()).all()
         # Return
         return render('/scenarios/show.mako')
     elif format == 'zip':
         return forward(FileApp(c.scenario.getFolder() + '.zip'))
     elif format == 'geojson':
         return c.scenario.getDataset().exportGeoJSON(transform_point)
     elif format == 'json':
         return c.scenario.exportJSON(request.params.get('nodeID'))
Ejemplo n.º 9
0
 def login(self, targetURL=h.encodeURL("/")):
     "Show login form"
     c.messageCode = request.GET.get("messageCode")
     c.targetURL = h.decodeURL(targetURL)
     c.publicKey = config["safe"]["recaptcha"]["public"]
     return render("/people/login.mako")
Ejemplo n.º 10
0
 def register(self):
     "Show account registration page"
     c.isNew = True
     return render("/people/change.mako")
Ejemplo n.º 11
0
 def index(self):
     "Show information about people registered in the database"
     c.people = Session.query(model.Person).all()
     return render("/people/index.mako")
Ejemplo n.º 12
0
            form["username"], model.hashString(form["password"]), form["nickname"], form["email"], form["email_sms"]
        )
        candidate.person_id = person.id if person else None
        candidate.ticket = store.makeRandomUniqueTicket(parameter.TICKET_LENGTH, Session.query(model.PersonCandidate))
        candidate.when_expired = datetime.datetime.utcnow() + datetime.timedelta(days=parameter.TICKET_LIFESPAN_IN_DAYS)
        Session.add(candidate)
        Session.commit()
        # Prepare recipient
        toByValue = dict(nickname=form["nickname"], email=form["email"])
        # Prepare subject
        subject = "[%s] Confirm %s" % (parameter.SITE_NAME, action)
        # Prepare body
        c.candidate = candidate
        c.username = form["username"]
        c.action = action
        body = render(templatePath)
        # Send
        try:
            smtp.sendMessage(config["safe"]["mail support"], toByValue, subject, body)
        except smtp.SMTPError:
            return dict(isOk=0, errorByID={"status": "Unable to send confirmation; please try again later."})
        # Return
        return dict(isOk=1)


def purgeExpiredPersonCandidates():
    "Delete candidates that have expired"
    Session.execute(
        model.person_candidates_table.delete().where(model.PersonCandidate.when_expired < datetime.datetime.utcnow())
    )
Ejemplo n.º 13
0
 def login(self, targetURL=h.encodeURL('/')):
     'Show login form'
     c.messageCode = request.GET.get('messageCode')
     c.targetURL = h.decodeURL(targetURL)
     c.publicKey = config['safe']['recaptcha']['public']
     return render('/people/login.mako')
Ejemplo n.º 14
0
 def register(self):
     'Show account registration page'
     c.isNew = True
     return render('/people/change.mako')
Ejemplo n.º 15
0
 def show(self, jobID, host):
     'Show the job log'
     c.jobID = jobID
     c.host = host
     return render('/jobs/show.mako')
Ejemplo n.º 16
0
 def index(self):
     'Show 10 most recent jobs'
     c.jobs = Session.query(model.Job).order_by(model.Job.start_time.desc()).limit(10).all()
     return render('/jobs/index.mako')