当前位置: 首页>>代码示例>>Python>>正文


Python Session.add方法代码示例

本文整理汇总了Python中np.model.Session.add方法的典型用法代码示例。如果您正苦于以下问题:Python Session.add方法的具体用法?Python Session.add怎么用?Python Session.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在np.model.Session的用法示例。


在下文中一共展示了Session.add方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: confirmPersonCandidate

# 需要导入模块: from np.model import Session [as 别名]
# 或者: from np.model.Session import add [as 别名]
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
开发者ID:AlphaStaxLLC,项目名称:networkplanner,代码行数:29,代码来源:people.py

示例2: update

# 需要导入模块: from np.model import Session [as 别名]
# 或者: from np.model.Session import add [as 别名]
 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()
开发者ID:aarabi,项目名称:networkplanner,代码行数:14,代码来源:processors.py

示例3: dict

# 需要导入模块: from np.model import Session [as 别名]
# 或者: from np.model.Session import add [as 别名]
    # shutil.move(databasePath, databaseBackupPath)
    connection = sqlite3.connect('production.db')
    cursor = connection.cursor()
    # Create new database
    Base.metadata.bind = Session.bind
    Base.metadata.reflect()
    Base.metadata.drop_all()
    Base.metadata.create_all()
    # Migrate people
    cursor.execute('SELECT username, password_hash, nickname, email, email_sms, minutes_offset, rejection_count, pickled FROM people')
    for username, password_hash, nickname, email, email_sms, minutes_offset, rejection_count, pickled in cursor.fetchall():
        person = model.Person(username, password_hash, nickname, email, email_sms)
        person.minutes_offset = minutes_offset
        person.rejection_count = rejection_count
        person.pickled = pickled
        Session.add(person)
        Session.commit()
    personByUsername = dict((x.username, x) for x in Session.query(model.Person))
    # Migrate scenarios
    cursor.execute('SELECT scenarios.id, username, name, scope, when_created, input FROM scenarios INNER JOIN people ON scenarios.owner_id=people.id WHERE status=?', [model.statusDone])
    for scenarioID, username, name, scope, when_created, input in cursor.fetchall():
        scenario = model.Scenario(personByUsername[username].id, name, scope)
        scenario.when_created = datetime.datetime.strptime(when_created, '%Y-%m-%d %H:%M:%S.%f')
        scenarioInput = pickle.loads(str(input))

        existingNetworkPath = scenarioInput['network configuration']['network']['existing network path']
        del scenarioInput['network configuration']['network']['existing network path']
        if existingNetworkPath:
            scenarioInput['network configuration']['network']['existing networks'] = u'network/network/existing networks.zip'

        scenario.input = scenarioInput
开发者ID:AlphaStaxLLC,项目名称:networkplanner,代码行数:33,代码来源:migrate.py

示例4: create

# 需要导入模块: from np.model import Session [as 别名]
# 或者: from np.model.Session import add [as 别名]
 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))
开发者ID:fparaggio,项目名称:networkplanner,代码行数:63,代码来源:scenarios.py

示例5: PersonForm

# 需要导入模块: from np.model import Session [as 别名]
# 或者: from np.model.Session import add [as 别名]
 try:
     # Validate form
     form = PersonForm().to_python(valueByName, person)
 except formencode.Invalid, error:
     return dict(isOk=0, errorByID=error.unpack_errors())
 else:
     # Purge expired candidates
     purgeExpiredPersonCandidates()
     # Prepare candidate
     candidate = model.PersonCandidate(
         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."})
开发者ID:fparaggio,项目名称:networkplanner,代码行数:33,代码来源:people.py

示例6: dict

# 需要导入模块: from np.model import Session [as 别名]
# 或者: from np.model.Session import add [as 别名]
 # Loop
 while True:
     # Try to get the next incoming message
     incomingMessage = channel.basic_get(incomingQueue, no_ack=True)
     # If a message does not exist,
     if not incomingMessage:
         # Take a break
         break
     # Unpack scenario from incoming message
     incomingPack = pickle.loads(incomingMessage.body)
     scenarioID, scenarioInput, scenarioData = incomingPack
     print 'Processing scenario %s' % scenarioID
     # Add scenario to local database
     scenario = model.Scenario(None, u'', model.scopePrivate)
     scenario.input = scenarioInput
     Session.add(scenario)
     Session.commit()
     # Unzip
     scenarioFolder = scenario.getFolder()
     store.unzipData(scenarioFolder, scenarioData)
     # Run
     try:
         scenario.run()
         scenario.status = model.statusDone
     except:
         scenario.output = dict(traceback=''.join(traceback.format_exception(*sys.exc_info())))
         scenario.status = model.statusFailed
     finally:
         Session.commit()
     # Pack result into outgoing message
     outgoingPack = scenarioID, scenario.output, open(scenarioFolder + '.zip', 'rb').read() if os.path.exists(scenarioFolder + '.zip') else None, scenario.status
开发者ID:AlphaStaxLLC,项目名称:networkplanner,代码行数:33,代码来源:processor.py


注:本文中的np.model.Session.add方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。