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


Python session.add函数代码示例

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


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

示例1: __get_calculator

 def __get_calculator(self, matrix):
     calculator = Calculator()
     calculator.algorithm_name = matrix.algorithm
     calculator.filter_name = matrix.matrix_filter
     session.add(calculator)
     session.commit()
     return calculator
开发者ID:yoloismymoto,项目名称:baseball,代码行数:7,代码来源:average.py

示例2: sync_photo

def sync_photo(id, flickr, check_dirty=False):    
    print id
    db_photo = session.query(Photo).filter(Photo.flickr_id == id).first()
    if db_photo and not check_dirty:
        print 'Photo is already local.'
        return db_photo
    photo = simplejson.loads(flickr.photos_getInfo(photo_id=id, nojsoncallback=1))
    p = photo['photo'] 
    (id, title) = (int(p['id']), p['title']['_content'])
    url = url_for_photo(p)
    page_url = p['urls']['url'][0]['_content']
    description = """%s\n
%s
Taken: %s in %s
Flickr: %s""" % (p['title']['_content'], p['description']['_content'], p['dates']['taken'], loc_to_string(p), page_url)

    if db_photo:
        print "Photo %s already exists" % id
        if db_photo.title == title and db_photo.description == description:
           return db_photo 
        db_photo.dirty = True   
        db_photo.title = title
        db_photo.description = description
    else:    
        url = url_for_photo(p)
        db_photo = Photo(title= title, description=description, flickr_id=id, dirty=False, url=url) 
        if not p['visibility']['ispublic']:
            db_photo.private = True
        session.add(db_photo)
    sync_tags(db_photo, p)
      
    session.commit()

    return db_photo
开发者ID:crschmidt,项目名称:flickr2facebook,代码行数:34,代码来源:transfer.py

示例3: parse_location

def parse_location(activity_dict):
    """Receives a shipment activity dictionary. If the activity contains
    a city and a state, saves the location to the database."""
    for shipment_id in activity_dict:
        activity_list = activity_dict[shipment_id]
        for activity in activity_list:
            if activity['ActivityLocation'] != 'Unknown':
                address_info = activity['ActivityLocation']['Address']
                if address_info.has_key('City') and address_info.has_key('StateProvinceCode'):
                    city = address_info['City']
                    # state = address_info['StateProvinceCode']
                    shipment_id = shipment_id
                    # date = datetime.strptime(activity['Date'], "%Y%m%d")
                    timestamp = datetime.strptime(activity['Date'] + activity['Time'], "%Y%m%d%H%M%S")
                    status = activity['Status']['StatusType']['Description']

                    # Query db to see if this activity has already been saved
                    try:
                        previous_location = (db_session.query(Location)
                                                       .filter_by(shipment_id=shipment_id)
                                                       .filter_by(placename=city)
                                                       .filter_by(timestamp=timestamp.strftime("%Y-%m-%d %H:%M:%S.000000"))
                                                       .filter_by(status_description=status)
                                                       .one())
                    # If location not in db, create Location object, save to db
                    except sqlalchemy.orm.exc.NoResultFound, e:
                        location = Location(shipment_id=shipment_id,
                                            placename=city,
                                            latitude="None",
                                            longitude="None",
                                            timestamp=timestamp,
                                            status_description=status,
                                            tracking_url='Need to get this.')
                        db_session.add(location)
开发者ID:etothemanders,项目名称:GoingPostal,代码行数:34,代码来源:email_helper.py

示例4: load_rss

def load_rss():
	# query the db: how long is it? Use this number later to empty db of old stories
    exstories = db_session.query(Stories).all()
    last_id = exstories[-1].id
    sources = {"NPR News": 'http://www.npr.org/rss/rss.php?id=1001', "BBC": 'http://feeds.bbci.co.uk/news/rss.xml'}
    for source in sources:
        print source
        # use feedparser to grab & parse the rss feed
        parsed = feedparser.parse(sources[source])
        print "parsed"
        # go through each entry in the RSS feed to pull out elements for Stories
        for i in range(len(parsed.entries)):
            title = parsed.entries[i].title
            url = parsed.entries[i].link
            source = source
            # pull abstract, parse out extra crap that is sometimes included
            abstract = (parsed.entries[i].description.split('<'))[0]
            print abstract

            # connect with db
            story = db_session.Stories(title=title, url=url, abstract=abstract, source=source)
            print "connected with db model??"
            # add story to db
            db_session.add(story)
            print "added story to db"
            # commit
        db_session.commit()
        print "committed"
    # delete from db old stories
    for l in range(1,last_id+1):
        db_session.query(Stories).filter_by(id=l).delete()
    db_session.commit()    
开发者ID:coderkat,项目名称:filtr,代码行数:32,代码来源:clock.py

示例5: load_globalcounts

def load_globalcounts(list_of_wordcounts):
    """
    Adds wordcounts for all unique words. There should only be one row per unique word.
    """
    # i = 0

    for localcount_dict in list_of_wordcounts:
        # if i < 5:
        for word, count in localcount_dict.iteritems():
            item = session.query(GlobalCount).filter(GlobalCount.term == word).first()
            if item:
                print "%r is already in globalcounts. Updating count..." % word
                # update the global count for this word, because we have added new songs with more occurrences of this word
                q = session.query(LocalCount.term, func.sum(LocalCount.count))
                q = q.group_by(LocalCount.term)
                q = q.filter(LocalCount.term == word)
                results = q.all()

                # print "Current count for %r is %d" % (item.term, item.count)
                item.count = results[0][1]
                print "Updating %r's count to %d" % (item.term, item.count)
                session.commit()

            else:
                print "%r not in globalcounts table, creating new row" % word
                qq = session.query(LocalCount.term, func.sum(LocalCount.count))
                qq = qq.group_by(LocalCount.term)
                qq = qq.filter(LocalCount.term == word)
                resultsresults = qq.all()

                countcount = resultsresults[0][1]
                new_row = GlobalCount(term = word, count = countcount)
                session.add(new_row)
                # you must commit before you query the same word/item again!
                session.commit()
开发者ID:magshi,项目名称:golem,代码行数:35,代码来源:seed.py

示例6: load_localcounts

def load_localcounts(lyrics_data, list_of_wordcounts):
    """
    Adds local wordcounts for each song.
    """
    # i = 0

    for song_dictionary in lyrics_data:
        # if i < 5:
        url = song_dictionary['url']
        # put on your counting shoes
        for k, v in song_dictionary.iteritems():
            lyrics = song_dictionary['lyrics']
            unique_words = {}

            for line in lyrics:
                line = line.lower()
                words = re.findall('\w+', line)

                # unique words for each song
                for word in words:
                    if unique_words.get(word):
                        unique_words[word] += 1
                    else:
                        unique_words[word] = 1

        # make all the localcount rows for that song
        for word, localcount in unique_words.iteritems():
            new_row = LocalCount(song_id = url, term = word, count = localcount)
            print "Adding %r with count of %r" % (new_row.term, new_row.count)
            session.add(new_row)
            # i += 1
        session.commit()
        list_of_wordcounts.append(unique_words)

    return list_of_wordcounts
开发者ID:magshi,项目名称:golem,代码行数:35,代码来源:seed.py

示例7: execute

 def execute(self):
     t = Task(self.name)
     if self.should_be_active:
         t.activate()
     session.add(t)
     session.commit()
     print "Added task %d." % t.id
开发者ID:soulplant,项目名称:tasks,代码行数:7,代码来源:main.py

示例8: register_user

def register_user():
    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        confirm_password = request.form['confirm_password']
        age = request.form['age']
        gender = request.form['gender']
        job = request.form['job']
        zipcode = request.form['zipcode']

        if password != confirm_password:
            flash("Your passwords do not match. Please re-type all your information.")
            return redirect("/sign_up")

        existing = db_session.query(User).filter_by(email=email).first()
        if existing:
            flash("Email is already in use.", "error")
            return redirect(url_for("display_search"))
        
        #create a new user object
        user = User(email=email, password=password, age=age, gender=gender, job=job, zipcode=zipcode)
        db_session.add(user)
        db_session.commit()
        db_session.refresh(user)
        session['user_id'] = user.id
        # save a cookie to the browser
        return redirect(url_for("display_search"))
    return redirect(url_for("login"))
开发者ID:moonlimb,项目名称:ratings,代码行数:28,代码来源:critiquing.py

示例9: login

def login(provider_name):
	response = make_response()
	result = authomatic.login(WerkzeugAdapter(request, response), provider_name)

	if result:
		# If we've received a user from Facebook...
		if result.user:
			# Get the user's profile data and look for it in our database
			result.user.update()
			facebook_id = result.user.id
			user = dbsession.query(User).filter_by(facebook_id = facebook_id).first()

			# If we don't find the user in our database, add it!
			if not user:
				user = User(facebook_id = facebook_id, email=result.user.email, name=result.user.name)
				dbsession.add(user)
				dbsession.commit()

			# Store the user in our session, logging them in 
			login_user(user)

		# Redirect somewhere after log in. In this case, the homepage
		return redirect('/')

	return response
开发者ID:dominic,项目名称:flask-facebook-oauth-example,代码行数:25,代码来源:app.py

示例10: close_trade

def close_trade(id):
	trade = Trade.query.filter_by(id=id).one()
	trade.close_date = datetime.datetime.utcnow()
	db_session.add(trade)
	db_session.commit()
	flash("Your trade has been marked as complete.", "success")
	return redirect("/trade_history")
开发者ID:jesslattif,项目名称:BarterApp,代码行数:7,代码来源:server.py

示例11: load_users

def load_users(session):
    with open("seed_data/u.user", "rb") as user_file:
        reader = csv.reader(user_file, delimiter="|")
        for row in reader:
            user = User(id=row[0], age=row[1], zipcode=row[4])
            session.add(user)
    session.commit()
开发者ID:QLGu,项目名称:Movie-Recommendation-App,代码行数:7,代码来源:seed.py

示例12: load_ratings

def load_ratings(session):
    with open("seed_data/u.data", "rb") as ratings_file:
        reader = csv.reader(ratings_file, delimiter="\t")
        for row in reader:
            rating = Rating(user_id=row[0], movie_id=row[1], rating=row[2])
            session.add(rating)
    session.commit()
开发者ID:QLGu,项目名称:Movie-Recommendation-App,代码行数:7,代码来源:seed.py

示例13: update_page

def update_page(page, chapter):
    print "Calling %s" % page.page_link
    response = urllib2.urlopen(page.page_link)
    if not (response.code >= 200 and response.code < 300):
        raise Exception("Could not retrieve the page for link . %s" % page.page_link)
    print "Response %s" % response.code
    content = response.read()
    (next_link, image) = get_image_and_next_link(content, page.page_link)
    while next_link is not None:
        if image is None:
            raise Exception("Something went wrong with the lack of image for given page")
        page.image_link = image
        next_page = Page(next_link, chapter)
        session.add(next_page)
        session.commit()
        print "Added Page[%d] %s" % (next_page.id, next_page.page_link)
        page.next_page_id = next_page.id
        session.add(page)
        session.commit()
        print "Update page %d with image %s" % (page.id, page.image_link)
        page = next_page
        response = urllib2.urlopen(page.page_link)
        if not (response.code >= 200 and response.code < 300):
            raise Exception("Could not retrieve the page for link . %s" % page.page_link)
        content = response.read()
        (next_link, image) = get_image_and_next_link(content, page.page_link)
开发者ID:arshadansari27,项目名称:manga-dl,代码行数:26,代码来源:feed_reader.py

示例14: sign_up_form

def sign_up_form():
		## input new user input into database
		email = request.form.get("email")
		password = request.form.get("password")
		username = request.form.get("username")
		first_name = request.form.get("first_name")
		last_name = request.form.get("last_name")
		gender = int(request.form.get("gender"))
		age = int(request.form.get("age"))
		zipcode = request.form.get("zipcode")
		
		hashed_password = hash_password(password, email)

		# create an instance of User with email, password, username, etc. as attributes
		user = User(email=email, password=hashed_password, username=username, first_name=first_name, 
			last_name=last_name, gender=gender, age=age, zipcode=zipcode)
		
		# check for email in db, if not there, add it to db
		if dbsession.query(User).filter_by(email = email).first():
			flash("This email address is already in use. Please try again.")
			return redirect("/sign_up")
		else:
			dbsession.add(user)
			dbsession.commit()
			created_user = dbsession.query(User).filter_by(email = email).first()
			session["login"] = created_user.id
			session["user"] = created_user
			return redirect("/pick_genres")
开发者ID:katereese,项目名称:Videodrome,代码行数:28,代码来源:flask_server.py

示例15: cadastrar

    def cadastrar(self): #sempre chama o dicionario em funcao da funcao

        self.nome = raw_input("Digite o hostname do server: ")
        self.descricao = raw_input("Digite descricao para o server: ")
        #self.ip = raw_input("Digite IP para o server: ")    

        try:
            ssh = SSH()
            docker = Docker()
            
            ssh.executa_comando(docker.criar(self.nome))

            
            container = ssh.executa_comando(docker.pegar_ip(self.nome))
            container = json.loads(container)

            self.ip = container[0].get("NetworkSettings").get("IPAddress")

            s = ServidorModel(self)
            #s.nome = servidor.get("nome")
            #s.descricao = servidor.get("descricao")
            #s.ip = servidor.get("ip")
            
            session.add(s)
            session.commit()
            print "Servidor cadastrado com sucesso!"
        except Exception as e:
            session.rollback()
            print "Falhou ao cadastrar servidor: ",e    
开发者ID:AleNunes,项目名称:Python_Basic,代码行数:29,代码来源:servidores.py


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