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


Python Session.commit方法代码示例

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


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

示例1: post

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import commit [as 别名]
 def post(self):
     shot_id = self.get_argument('shot_id')
     username = self.get_argument('username')
     shot_upheld = self.get_argument('shot_upheld')
     claim = self.get_argument('claim', '')
     
     try:
         resolving_user = get_user(username=username)
         shot = get_shot(shot_id)
         game = get_game(shot.game_id)
         session = Session()
         
         mission = get_mission(game_id=game.id, assassin_id=shot.assassin_id, target_id=shot.target_id, completed_timestamp=None)
         
         if shot_upheld == 'True':
             if shot.target_id == resolving_user.id or resolving_user in game.game_masters:
                 shot.kill_upheld = True
                 game.mission_completed(mission, shot)
                 response_dict = get_response_dict(True)
         else:
             if shot.target_id == resolving_user.id:
                 dispute = Dispute(game.id, shot_id, claim)
                 session.add(dispute)
                 session.flush()
                 session.commit()
                 response_dict = get_response_dict(True)
             elif resolving_user in game.game_masters:
                 shot.kill_upheld = False
                 response_dict = get_response_dict(True)
     except Exception as e:
         session.rollback()
         response_dict = get_response_dict(False, e.message)
     finally:
         Session.remove()
         self.finish(simplejson.dumps(response_dict))
开发者ID:sosso,项目名称:Assassins-Server,代码行数:37,代码来源:game_action_handlers.py

示例2: post

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import commit [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

示例3: buildUrl

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import commit [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

示例4: signin

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import commit [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

示例5: create_this_week_quote

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import commit [as 别名]
def create_this_week_quote():
    if not is_trade_day(date.today()):
        return

    ss = Session()

    today = date.today()
    week_first_date = today - timedelta(days=today.weekday())

    securities = ss.query(Quote.code).distinct().all()
    for sec in securities:
        sec_quotes_of_this_week = ss.query(Quote).filter(
            and_(
                Quote.code == sec.code,
                Quote.datetime >= week_first_date,
                Quote.datetime <= today,
                Quote.period == 'd1'
            )
        ).all()

        if not sec_quotes_of_this_week:
            continue

        week_quote = merge_quotes(sec_quotes_of_this_week)
        week_quote.period = 'w1'
        ss.merge(week_quote)
        ss.commit()
开发者ID:bluecover,项目名称:jettingrocket,代码行数:29,代码来源:celery_cron.py

示例6: makefriend

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import commit [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

示例7: register

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import commit [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

示例8: Post

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import commit [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

示例9: add_feed_to_db

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import commit [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

示例10: update_volume_with_email_passwd

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import commit [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

示例11: reset_purchases

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import commit [as 别名]
def reset_purchases():
    session = Session()

    product = session.query(Product).update({'purchased': False})
    product.purchased = True
    session.commit()

    return 'OK'
开发者ID:junkafarian,项目名称:super-granny-geek,代码行数:10,代码来源:app.py

示例12: run_image

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import commit [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

示例13: add_github_repo_to_db

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import commit [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

示例14: import_assignments

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import commit [as 别名]
def import_assignments(in_filepath):
    s = Session()
    obj = json.loads(open(in_filepath).read())

    for assignment in obj:
        set_or_create_assignment(assignment, s)

    s.commit()
开发者ID:augustjd,项目名称:newgrader,代码行数:10,代码来源:json_interface.py

示例15: create_tables

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import commit [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


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