本文整理汇总了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
示例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
示例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)
示例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()
示例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()
示例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
示例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
示例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"))
示例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
示例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")
示例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()
示例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()
示例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)
示例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")
示例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