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


Python Session.add方法代码示例

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


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

示例1: update_volume_with_email_passwd

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import add [as 别名]
def update_volume_with_email_passwd(models, email=None, passwd=None):
    session = Session()
    #kwdict = getvolume(models, email, passwd)
    if not hasattr(update_volume_with_email_passwd, 'ks'):
        setattr(update_volume_with_email_passwd, 'ks', KeywordSearch())
    ks = update_volume_with_email_passwd.ks
    kwdict = ks.search(models)

    for k, v in kwdict.items():
        print k, v
        m = session.query(Model).filter_by(model=k).first()
        if m:
            m.global_volume = volume2int(v[0])
            m.local_volume = volume2int(v[1])
            m.updated_at = datetime.utcnow()
            session.add(m)

    session.commit()
    session.close()
    sleep = 3
    while sleep>0:
        import time
        print 'sleeping', sleep
        time.sleep(1)
        sleep -= 1
开发者ID:mobishift2011,项目名称:amzn,代码行数:27,代码来源:volume.py

示例2: post

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import add [as 别名]
    def post(self):
        username = self.get_argument('username')
        game_id = self.get_argument('game_id')
        dispute_id = self.get_argument('dispute_id')
        shot_upheld = self.get_argument('dispute_upheld')
        gm_decision_reason = self.get_argument('gm_decision_reason')

        session = Session()
        try:
            dispute = session.query(Dispute).filter_by(id=dispute_id).one()
            shot = session.query(Shot).filter_by(id=dispute.shot_id).one()
            resolving_user = get_user(username=username)
            game = get_game(game_id)
            mission = get_mission(game_id=game_id, assassin_id=shot.assassin_id, target_id=shot.target_id, completed_timestamp=None)
            if resolving_user in game.game_masters:
                if shot_upheld == 'True':
                    game.mission_completed(mission)
                    dispute.shot_upheld = True
                else:
                    dispute.shot_upheld = False
                    target_usergame = get_usergame(shot.target_id, game.id)
                    if target_usergame.alive == None:
                        target_usergame.alive = True
                        session.add(target_usergame)
                dispute.gm_decision_reason = gm_decision_reason
                session.add(dispute)
                session.flush()
                session.commit()
                response_dict = get_response_dict(True)
                
            else:
                response_dict = get_response_dict(False, 'Only the game master can resolve a dispute')
        except Exception, e:
            session.rollback()
            response_dict = get_response_dict(False, e.message)
开发者ID:sosso,项目名称:Assassins-Server,代码行数:37,代码来源:game_action_handlers.py

示例3: signin

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import add [as 别名]
def signin():
    if 'username' not in request.form or 'secret' not in request.form or 'openport' not in request.form:
        return "\"POST request must contain 'openport', 'username' and 'secret' fields\""
    session = Session()
    username = request.form['username']
    secret = request.form['secret']
    openport = int(request.form['openport'])
    users = session.query(User).filter(User.id == username).all()
    if (len(users) == 0):
        now = datetime.datetime.now()
        user = User(id=username, secret = secret, lastping = now, lastip=request.remote_addr, lastport = openport)
        session.add(user)
        session.commit()
        session.close()
        return json.dumps("True")
    else:
        if users[0].secret == secret:
            users[0].lastip = request.remote_addr
            users[0].lastport = openport
            users[0].lastping = datetime.datetime.now()
            session.add(users[0])
            for ownership in session.query(Owner).filter(Owner.owner == username).all():
                session.delete(ownership)
            session.commit()
            session.close()
            return json.dumps(True)
        else:
            return json.dumps(False)
开发者ID:ndm25,项目名称:sp2p,代码行数:30,代码来源:privclient.py

示例4: makefriend

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import add [as 别名]
def makefriend(request):
	login = authenticated_userid(request)		
	if(login!= None):
		parsed = urlparse.urlparse(request.referer)
		friendid = int(urlparse.parse_qs(parsed.query)['id'][0])
		
		DBSession = Session(bind=engine)
		user = DBSession.query(User).filter(User.login == login).one()

		friendrequest = DBSession.query(Friendrequest).filter(and_(Friendrequest.user_to_id == user.id,Friendrequest.user_from_id == friendid)).all()
			
		#принимаем заявку в друзья
		if (len(friendrequest) > 0):							

			messageFile = "{0}-{1}.txt".format(user.id, friendid)
			messageLocPath =  "socialnetwork/static/" +messageFile
			with open(messageLocPath,'w') as f:
				f.write('')
			
			friendship = Friendship(user_from_id = friendid, user_to_id = user.id, dialogLocPath = messageLocPath)
			DBSession.add(friendship)				
			DBSession.delete(friendrequest[0])
			DBSession.commit()			
		
		else:	
			#запрос от текущего аккаунта выбранному пользователю			
			friendrequest = DBSession.query(Friendrequest).filter(and_(Friendrequest.user_to_id == friendid,Friendrequest.user_from_id == user.id)).all()				
			#добавление, если нет еще запроса
			if (len(friendrequest) == 0 ):
				friendrequest = Friendrequest(user_from_id = user.id, user_to_id = friendid)
				DBSession.add(friendrequest)	
				DBSession.commit()
		
		return HTTPFound(location=request.referer)
    	return HTTPFound(location='/')
开发者ID:Dizrax,项目名称:SocialNetwork,代码行数:37,代码来源:views.py

示例5: register

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import add [as 别名]
def register():
    if 'username' not in request.form or 'filename' not in request.form or 'hash' not in request.form or 'size' not in request.form:
        return "\"POST request must contain 'username', 'filename', 'size', and 'hash'.\""
    session = Session()
    username = request.form['username']
    filename = request.form['filename']
    md5 = request.form['hash']
    size = request.form['size']
    files = session.query(File).filter(File.filename == filename).filter(File.md5 == md5)
    files = files.all()
    if len(files) == 0:
        f = File(filename= filename, md5 = md5, filesize = size)
        session.add(f)
        session.commit()
    else:
        f = files[0]
    fileid = f.id
    if 'path' in request.form:
        loc = request.form['path']
    else:
        loc = filename

    print username, filename, md5, loc
    if not session.query(Owner).filter(Owner.owner == username).filter(Owner.dirpath == loc).filter(Owner.fileid == fileid).all():
        session.add(Owner(owner = username, dirpath = loc, fileid = fileid))
    session.commit()
    session.close()
    return json.dumps(True)
开发者ID:ndm25,项目名称:sp2p,代码行数:30,代码来源:privclient.py

示例6: add_feed_to_db

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import add [as 别名]
def add_feed_to_db():
    feed_url = request.args["feed_url"]
    feed = RSSFeed(current_user.id, feed_url)
    session = Session()
    session.add(feed)
    session.commit()
    return redirect(url_for('dashboard'))
开发者ID:ndm25,项目名称:notifyable,代码行数:9,代码来源:main.py

示例7: Post

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import add [as 别名]
class Post(bourbon.ModelInterface):
    @staticmethod
    def all():
        sess = Session()
        return [post.id for post in sess.query(PostModel).all()]
    
    @staticmethod
    def open(identifier):
        self = Post()
        self.sess = Session()
        self.post = self.sess.query(PostModel).filter_by(id=identifier).scalar()
        if self.post is None:
           self.post = PostModel()
        return self

    @staticmethod
    def stat(identifier):
        post = Post.open(identifier)
        return bourbon.Stat.as_file(len(post.read())).as_dict()

    def close(self):
        self.sess.add(self.post)
        self.sess.commit()
        del self.sess
        del self.post
        return True
    
    def read(self):
        return self.post.text

    def write(self, data):
        self.post.text = data
        
    def getattr(self):
        return bourbon.FILE
开发者ID:dpaola2,项目名称:Bourbon,代码行数:37,代码来源:example.py

示例8: buildUrl

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import add [as 别名]
def buildUrl():
    "生成短网址"
    
    url = request.form.get("url",None)
    token=hashlib.md5(url).hexdigest()
    
    dbSession=Session()
    query=dbSession.query(UrlModel)
    obj=query.filter(UrlModel.token == token).first()
    
    if obj == None:
        obj = UrlModel(token,url)
        dbSession.add(obj)
        dbSession.commit()
        key = obj.id 
    else:
        key = obj.id    
    dbSession.close()
    
    key=str(hex(key))[2:]
    key=key[:len(key)-1]
    key="http://"+request.headers['host']+"/shortUrl/s/"+key
    
    response = make_response(json.dumps({"key":key}))
    response.headers['Content-Type']="application/json"
    return response
开发者ID:wangjun,项目名称:shortUrl-1,代码行数:28,代码来源:app.py

示例9: post

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import add [as 别名]
    def post(self):
        username = self.get_argument('username')
        item_id = self.get_argument('item_id')
        try: file1 = self.request.files['file'][0]
        except: file1 = None
        final_string = ''
        session = Session()
        try:
            user = dbutils.get_or_create(session, User, username=username)
            item = dbutils.get_or_create(session, Item, item_id=item_id)
            item_completion = dbutils.get_or_create(session, ItemCompletion, item_id=item.id, user_id=user.id)

            if file1 is not None:
                original_fname = file1['filename']

                extension = os.path.splitext(original_fname)[1]
                final_filename = item_id + extension
                if not os.path.exists("./uploads"):
                    os.makedirs("./uploads")
                if not os.path.exists("./uploads/%s" % username):
                    os.makedirs("./uploads/%s" % username)
                output_file = open("./uploads/" + username + "/" + final_filename, 'wb')
                output_file.write(file1['body'])
                item_completion.file_path = "uploads/" + username + "/" + final_filename

            session.add(item_completion)
            session.commit()
            final_string = "You have crossed item " + item_id + " off your bucket list!"
        except Exception, e:
            session.rollback()
            logger.exception(e)
            final_string = "Oops!  Something went wrong.  Please try again"
开发者ID:sosso,项目名称:eashl_stats2,代码行数:34,代码来源:modelhandlers.py

示例10: update_likes

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import add [as 别名]
def update_likes(campaign_id, api):
    kill_firefox_and_xvfb()
    session = Session()
    campaign = session.query(Campaign).get(campaign_id)
    user = session.query(User).get(campaign.user.id)
    downloaded_results = downloads(session, campaign, api)
    prospect_array = []
    prospects = ProspectProfile.get_unliked_requests(session, campaign.id, 50)
    for prospect in prospects:
        prospect.done = True
        session.commit()
        prospect_array.append(prospect.prospect.username)
    ig = InstagramBot(
            username=user.username,
            password=user.password,
            prospects=prospect_array)
    result = ig.like()
    for k, v in result.iteritems():
        prospect = session.query(Prospect).filter_by(username=k).first()
	if prospect:
	    user_like = UserLike(user=user, prospect=prospect, media_id=v)
	    session.add(user_like)
	    session.commit()

    campaign.generate_stats(session, total_likes=ig.completed)
    campaign = session.query(Campaign).get(campaign_id)
    if campaign.job_id:
        result = update_likes.apply_async(countdown=1000, args=(campaign.id, api,))
        print "old", campaign.job_id
        campaign.job_id=result.id
        session.commit()
        print "new", campaign.job_id
    else:
        print "no longer doing this"
    return True
开发者ID:jamesjohnson,项目名称:instabot,代码行数:37,代码来源:tasks.py

示例11: run_image

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import add [as 别名]
def run_image(app_image_id):
    db = Session()
    app_image = db.query(AppImage).get(app_image_id)
    f = app_image.app.app_type()
    container_id = f.run(app_image.app.id, app_image.docker_image_id)
    instance = AppInstance(app_image=app_image, container_id=container_id)
    db.add(instance)
    db.commit()
开发者ID:mr-tim,项目名称:sandpit,代码行数:10,代码来源:tasks.py

示例12: add_github_repo_to_db

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import add [as 别名]
def add_github_repo_to_db():
    gh_user = request.args["github_user"]
    gh_url = request.args["github_url"]
    repo = GithubRepo(current_user.id, gh_user, gh_url)
    session = Session()
    session.add(repo)
    session.commit()
    return redirect(url_for('dashboard'))
开发者ID:ndm25,项目名称:notifyable,代码行数:10,代码来源:main.py

示例13: create_tables

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import add [as 别名]
def create_tables():
    Base.metadata.create_all(engine)
    session = Session()

    for agency in agencies:
        a = Agency(abbreviation=agency, full_name=agencies[agency])
        session.add(a)
        session.commit()
开发者ID:tbuckley,项目名称:playbook,代码行数:10,代码来源:server.py

示例14: create_question

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import add [as 别名]
def create_question():
  data = flask.request.json

  s = Session()
  question = Question(quiz_id = data['quiz_id'], title = data['title'])
  s.add(question)
  s.commit()

  return flask.jsonify({'quiz_id': data['quiz_id'], 'title': data['title']})
开发者ID:carlsednaoui,项目名称:ouiquiz,代码行数:11,代码来源:app.py

示例15: load_fixtures

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import add [as 别名]
def load_fixtures():
    session = Session()
    try:
        for model, items in fixtures.items():
            for item in items:
                session.add(model(**item))
        session.commit()
    except:
        session.rollback()
开发者ID:junkafarian,项目名称:super-granny-geek,代码行数:11,代码来源:app.py


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