def update(self, id): 'PUT /scenarios/id: Update an existing item' # Initialize personID = h.getPersonID() # Load scenario = Session.query(model.Scenario).filter(model.Scenario.id==id).first() # If the scenario doesn't exist, if not scenario: return dict(isOk=0, message='Scenario %s does not exist' % id) # If the user is not the owner, if personID != scenario.owner_id: return dict(isOk=0, message='You are not the owner of scenario %s' % id) # Load scenarioName = request.params.get('scenarioName', '').strip() if not scenarioName: return dict(isOk=0, message='Please enter a scenario name') try: scenarioScope = int(request.params.get('scenarioScope')) except ValueError: return dict(isOk=0, message='Scenario scope must be an integer') if scenarioScope not in [model.scopePrivate, model.scopePublic]: return dict(isOk=0, message='Scenario scope can either be %s=private or %s=public' % (model.scopePrivate, model.scopePublic)) # Update scenario.name = scenarioName scenario.scope = scenarioScope # Commit Session.commit() # Return return dict(isOk=1)
def saveResult(outgoingMessage): 'Save result in local database' # Unpack result from outgoing message outgoingPack = pickle.loads(outgoingMessage.body) scenarioID, scenarioOutput, scenarioData, scenarioStatus = outgoingPack print 'Consuming scenario %s' % scenarioID # Load scenario from local database scenario = Session.query(model.Scenario).get(scenarioID) # If the scenario does not exist, if not scenario: print 'Scenario %s does not exist' % scenarioID return # Get folder scenarioFolder = scenario.getFolder() # Save data if scenarioData: scenarioPath = scenarioFolder + '.zip' open(scenarioPath, 'wb').write(scenarioData) store.unzipData(scenarioFolder, scenarioData) # Save output scenario.output = scenarioOutput scenario.status = scenarioStatus Session.commit() # Post to callback scenario.postCallback()
def confirmPersonCandidate(ticket): 'Move changes from the PersonCandidate table into the Person table' # Query candidate = Session.query(model.PersonCandidate).filter(model.PersonCandidate.ticket==ticket).filter(model.PersonCandidate.when_expired>=datetime.datetime.utcnow()).first() # If the ticket exists, if candidate: # If the person exists, if candidate.person_id: # Update person person = Session.query(model.Person).get(candidate.person_id) person.username = candidate.username person.password_hash = candidate.password_hash person.nickname = candidate.nickname person.email = candidate.email person.email_sms = candidate.email_sms # Reset rejection_count person.rejection_count = 0 # If the person does not exist, else: # Add person Session.add(model.Person(candidate.username, candidate.password_hash, candidate.nickname, candidate.email, candidate.email_sms)) # Delete ticket Session.delete(candidate) # Commit Session.commit() # Return return candidate
def update(self): "Update processor information" # Load ip = h.getRemoteIP() processor = Session.query(model.Processor).filter(model.Processor.ip == ip).first() # If the processor doesn't exist, if not processor: processor = model.Processor(ip) Session.add(processor) # Update processor.when_updated = datetime.datetime.utcnow() Session.commit()
def delete(self, id): 'DELETE /scenarios/id: Delete an existing item' # Initialize personID = h.getPersonID() # Load scenario = Session.query(model.Scenario).filter(model.Scenario.id==id).first() # If the scenario doesn't exist, if not scenario: return dict(isOk=0, message='Scenario %s does not exist' % id) # If the user is not the owner, if personID != scenario.owner_id: return dict(isOk=0, message='You are not the owner of scenario %s' % id) # Delete Session.delete(scenario) Session.commit() # Return return dict(isOk=1)
def login_(self): 'Process login credentials' # Check username username = str(request.POST.get('username', '')) person = Session.query(model.Person).filter_by(username=username).first() # If the username does not exist, if not person: return dict(isOk=0) # Check password password_hash = model.hashString(str(request.POST.get('password', ''))) # If the password is incorrect, if password_hash != StringIO.StringIO(person.password_hash).read(): # Increase and return rejection_count without a requery rejection_count = person.rejection_count = person.rejection_count + 1 Session.commit() return dict(isOk=0, rejection_count=rejection_count) # If there have been too many rejections, if person.rejection_count >= parameter.REJECTION_LIMIT: # Expect recaptcha response recaptchaChallenge = request.POST.get('recaptcha_challenge_field', '') recaptchaResponse = request.POST.get('recaptcha_response_field', '') recaptchaKey = config['safe']['recaptcha']['private'] # Validate result = captcha.submit(recaptchaChallenge, recaptchaResponse, recaptchaKey, h.getRemoteIP()) # If the response is not valid, if not result.is_valid: return dict(isOk=0, rejection_count=person.rejection_count) # Get minutesOffset from UTC minutesOffset = h.getMinutesOffset() # Save session session['minutesOffset'] = minutesOffset session['personID'] = person.id session['nickname'] = person.nickname session['role'] = person.role session.save() # Save person person.minutes_offset = minutesOffset person.rejection_count = 0 Session.commit() # Return return dict(isOk=1)
#!/usr/bin/env python 'Requeue pending scenarios' # Import custom modules import script_process from np import model from np.model import Session # If we are running the command as a script, if __name__ == '__main__': # Connect script_process.connect() # List for processorIP, processorWhen in Session.query(model.Processor.ip, model.Processor.when_updated).order_by(model.Processor.when_updated): print '{}\t{}'.format(processorIP, processorWhen.strftime('%Y%m%d %H:%M')) # Commit Session.commit()
def create(self): 'POST /scenarios: Create a new item' # Initialize personID = h.getPersonID() if not personID: return redirect(url('person_login', targetURL=h.encodeURL(h.url('new_scenario')))) # Load try: demographicDatabase_h = int(request.POST.get('demographicDatabase_h', 0)) except ValueError: demographicDatabase_h = 0 if not demographicDatabase_h and 'demographicDatabase' not in request.POST: return cjson.encode(dict(isOk=0, message='The demographicDatabase field is required')) scenarioName = request.POST.get('scenarioName') or 'Untitled' try: scenarioScope = int(request.POST.get('scenarioScope', model.scopePrivate)) except ValueError: scenarioScope = model.scopePrivate metricModelName = request.POST.get('metricModelName', metric.getModelNames()[0]) networkModelName = request.POST.get('networkModelName', network.getModelNames()[0]) callbackURL = request.POST.get('callbackURL') # Create scenario scenario = model.Scenario(personID, scenarioName, scenarioScope) Session.add(scenario) Session.commit() scenarioFolder = scenario.getFolder() if os.path.exists(scenarioFolder): shutil.rmtree(scenarioFolder) store.makeFolderSafely(scenarioFolder) # If the user is using an existing demographicDatabase, if demographicDatabase_h: # Copy source in case it is deleted sourceScenario = Session.query(model.Scenario).get(demographicDatabase_h) sourceScenarioFolder = sourceScenario.getFolder() demographicFileName = sourceScenario.input['demographic file name'] demographicPath = os.path.join(scenarioFolder, demographicFileName) shutil.copyfile(os.path.join(sourceScenarioFolder, demographicFileName), demographicPath) # If the user is uploading a new demographicDatabase, else: # Save original demographicDatabase in case the user wants it later demographicDatabase = request.POST['demographicDatabase'] demographicFileExtension = os.path.splitext(demographicDatabase.filename)[1] demographicFileName = 'demographics' + demographicFileExtension demographicPath = os.path.join(scenarioFolder, demographicFileName) shutil.copyfileobj(demographicDatabase.file, open(demographicPath, 'wb')) demographicDatabase.file.close() # Store input configurationByName = extractConfigurationByName(request.POST, scenarioFolder) scenario.input = { 'demographic file name': str(demographicFileName), 'metric model name': metricModelName, 'metric configuration': configurationByName.get('metric', {}), 'network model name': networkModelName, 'network configuration': configurationByName.get('network', {}), 'callback url': callbackURL, 'host url': request.host_url, } Session.commit() store.zipFolder(scenarioFolder + '.zip', scenarioFolder) # Redirect redirect(url('scenario', id=scenario.id))