本文整理汇总了Python中database.Session.add方法的典型用法代码示例。如果您正苦于以下问题:Python Session.add方法的具体用法?Python Session.add怎么用?Python Session.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类database.Session
的用法示例。
在下文中一共展示了Session.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: register_view
# 需要导入模块: from database import Session [as 别名]
# 或者: from database.Session import add [as 别名]
def register_view(self):
form = RegistrationForm(request.form)
if request.method == 'POST' and form.validate():
user = Users()
user.username = form.username.data
user.email = form.email.data
user.roles = ','.join(form.role.data)
# we hash the users password to avoid saving it as plaintext in the db,
# remove to use plain text:
user.password = generate_password_hash(form.password.data)
Session.add(user)
Session.commit()
login.login_user(user)
flash('Thanks for registering')
return redirect(url_for('.index'))
link = '<p>Already have an account? <a href="' + url_for('.login_view') + '">Click here to log in.</a></p>'
form_roles = []
roles = Session.query(Role).all()
for role in roles:
form_roles.append((role.key, role.name))
form.role.choices = form_roles
self._template_args['form'] = form
self._template_args['link'] = link
return super(MyAdminIndexView, self).index()
示例2: insert_test_values
# 需要导入模块: from database import Session [as 别名]
# 或者: from database.Session import add [as 别名]
def insert_test_values():
from database import Session
from database.objects import User, Address, BlogPost, Keyword
from random import randint
letters = "abcdefghijklmnopqrstuvwxyz"
s = Session()
keyword = Keyword("firstpost")
for n in range(100):
name = ""
for l in range(randint(4, 10)):
letter = letters[randint(0, len(letters) - 1)]
name += letter
user = User(name=name, fullname=name, password="test")
user.addresses = [
Address(email_address=("%[email protected]" % name)),
Address(email_address=("%[email protected]" % name)),
]
post = BlogPost(("%ss Blog Post" % name), "This is a test", user)
post.keywords.append(Keyword(name))
post.keywords.append(keyword)
s.add(post)
s.commit()
s.close()
示例3: get_announcements
# 需要导入模块: from database import Session [as 别名]
# 或者: from database.Session import add [as 别名]
def get_announcements(course, url):
'''Gets all new announcements
Returns a list of all new announcements.
'''
session = Session()
try:
r = s.get('https://edux.pjwstk.edu.pl/Announcements.aspx', stream=True)
r.raise_for_status()
new_announcements = extract_announcements(r.content)
# All pairs of (timestamp, message) are saved to db
# if they arent there already
for (timestamp, message) in new_announcements:
announcement = session.query(Announcement). \
filter_by(course=course,
created_at=timestamp,
message=message). \
first()
if announcement is None:
# This is what we care about
announcement = Announcement(
course=course,
created_at=timestamp,
message=message)
session.add(announcement)
print u'New announcement at {0}'.format(timestamp)
yield (timestamp, message)
session.commit()
except Exception:
session.rollback()
raise
finally:
session.close()
示例4: sign_up
# 需要导入模块: from database import Session [as 别名]
# 或者: from database.Session import add [as 别名]
def sign_up():
form = SignUpForm()
user = User()
if form.validate_on_submit():
user_name = request.form.get('user_name')
user_email = request.form.get('user_email')
register_check = User.login_check(user_name)
if register_check:
flash("error: The user's name already exists!")
return redirect('/sign-up')
if len(user_name) and len(user_email):
user.nickname = user_name
user.email = user_email
try:
session = Session()
session.add(user)
session.commit()
except:
flash("The Database error!")
return redirect('/sign-up')
flash("Sign up successful!")
return redirect('/index')
return render_template(
"sign_up.html",
form=form)
示例5: submit
# 需要导入模块: from database import Session [as 别名]
# 或者: from database.Session import add [as 别名]
def submit(self, traj):
""" Submit a job to the work-queue for further sampling.
Parameters
----------
"""
if traj.submit_time is not None:
raise ValueError("This traj has already been submitted")
Session.add(traj)
Session.flush()
traj.populate_default_filenames()
if not hasattr(traj, "init_pdb"):
raise ValueError("Traj is supposed to have a pdb object tacked on")
save_file(traj.init_pdb_fn, traj.init_pdb)
remote_driver_fn = os.path.split(str(traj.forcefield.driver))[1]
remote_pdb_fn = "input.pdb"
remote_output_fn = "production_dry{}".format(traj.forcefield.output_extension)
if traj.mode is None or traj.forcefield is None:
raise ValueError("malformed traj")
task = Task(
"python ./{driver} {pdb_fn} {ff} {water} {mode} {threads}".format(
pdb_fn=remote_pdb_fn,
mode=traj.mode,
driver=remote_driver_fn,
ff=traj.forcefield.name,
water=traj.forcefield.water,
threads=traj.forcefield.threads,
)
)
# why does traj.forcefield.driver come out as unicode?
task.specify_input_file(str(traj.forcefield.driver), remote_driver_fn)
task.specify_output_file(traj.wqlog_fn, "logs/driver.log")
task.specify_input_file(traj.init_pdb_fn, remote_pdb_fn)
task.specify_output_file(traj.dry_xtc_fn, remote_output_fn)
if self.return_wet_xtc:
# this is the XTC file with waters, generated by the driver
# when you're doing implicit solvent only, this stuff is not used.
remote_wet_output_fn = "production_wet{}".format(traj.forcefield.output_extension)
task.specify_output_file(traj.wet_xtc_fn, remote_wet_output_fn)
task.specify_output_file(traj.last_wet_snapshot_fn, "last_wet_snapshot.pdb")
else:
logger.debug("Not requesting production_wet%s from driver (implicit)", traj.forcefield.output_extension)
task.specify_tag(str(traj.id))
task.specify_algorithm(WORK_QUEUE_SCHEDULE_FILES) # what does this do?
traj.submit_time = datetime.now()
# need to do a commit from this the qmaster, since this is a different
# session
Session.commit()
self.wq.submit(task)
logger.info("Submitted to queue: %s", traj)
示例6: save_album
# 需要导入模块: from database import Session [as 别名]
# 或者: from database.Session import add [as 别名]
def save_album(album_name,album_id,album_cover):
try:
category = Albums(album_name=album_name,album_id=album_id,album_cover=album_cover)
Session.add(category)
Session.commit()
except Exception as e:
Session.rollback()
raise e
示例7: save_cate
# 需要导入模块: from database import Session [as 别名]
# 或者: from database.Session import add [as 别名]
def save_cate(cate_name,cate_id):
try:
category = Categories(category_name=cate_name,category_id=cate_id)
Session.add(category)
Session.commit()
except Exception as e:
Session.rollback()
raise e
示例8: index
# 需要导入模块: from database import Session [as 别名]
# 或者: from database.Session import add [as 别名]
def index(self, fullname=None, username=None, password=None):
if cherrypy.request.method == "POST":
session = Session()
new_user = User(username, fullname, password)
session.add(new_user)
session.commit()
session.close()
raise cherrypy.HTTPRedirect("/")
示例9: add_user
# 需要导入模块: from database import Session [as 别名]
# 或者: from database.Session import add [as 别名]
def add_user(self, name, address):
if not (name == '' or address == ''):
s = Session()
u = User(name=name, fullname='%s test' % name, password='pwtest')
u.addresses = [Address(email_address=address), ]
s.add(u)
s.commit()
self.send_user(u)
s.close()
示例10: addfav
# 需要导入模块: from database import Session [as 别名]
# 或者: from database.Session import add [as 别名]
def addfav():
data = request.get_json()
playlist1 = Session.query(playlist).filter(playlist.userid==session['userid']).order_by(playlist.id).first()
maxorder = Session.query(func.max(playlist_item.order)).filter(playlist_item.listid == playlist1.id).first()[0]
if not maxorder:
maxorder = 0
Session.add(playlist_item(listid=playlist1.id, musicid=data['id'], order=maxorder+1))
Session.commit()
return "Success"
示例11: save_wallpaper
# 需要导入模块: from database import Session [as 别名]
# 或者: from database.Session import add [as 别名]
def save_wallpaper(title, file_name, image_url, id=None, category=None, album_id=None, album_name=None ,username=None):
try:
wallpaper = Wallpapers(title=title, image_url=image_url, id=id, category_id=category, user_id=username,
album_id=album_id, album_name=album_name)
Session.add(wallpaper)
Session.commit()
except Exception as e:
Session.rollback()
raise e
示例12: add_forcefields_to_db
# 需要导入模块: from database import Session [as 别名]
# 或者: from database.Session import add [as 别名]
def add_forcefields_to_db(self, p):
if Session.query(models.Forcefield).count() == 0:
# add forcefields
for ff in p:
obj = models.Forcefield(**ff)
obj.driver = os.path.join(self.params_dir, ff['driver'])
Session.add(obj)
Session.commit()
else:
print "NOTE: I'M NOT PARSING NEW FORCEFIELDS"
示例13: Factory
# 需要导入模块: from database import Session [as 别名]
# 或者: from database.Session import add [as 别名]
class Factory(object):
def __init__(self, model):
self.session = Session()
self.model = model
def fetch_all(self):
return self.session.query(self.model).all()
def insert(self, obj, commit=True):
self.session.add(obj)
if commit:
self.session.commit()
def commit(self):
self.session.commit()
示例14: get_folders
# 需要导入模块: from database import Session [as 别名]
# 或者: from database.Session import add [as 别名]
def get_folders(course):
'''Gets all folders
'''
session = Session()
try:
r = s.get('https://edux.pjwstk.edu.pl/Folder.aspx')
r.raise_for_status()
new_folders = extract_folders(r.content)
for (folder_id, title, start_at, finish_at) in new_folders:
folder = session.query(Folder). \
filter_by(folder_id=folder_id). \
first()
if folder is None:
folder = Folder(
folder_id=folder_id,
course=course,
title=title,
start_at=start_at,
finish_at=finish_at)
send_notify('New folder "{}" at {}'.format(title,
course.title),
'''Folder title: {0.title}
Start at: {0.start_at}
Finish at: {0.finish_at}'''.format(folder))
session.add(folder)
if (folder.title != title or
folder.start_at != start_at or
folder.finish_at != finish_at):
new = {
'title': title,
'start_at': start_at,
'finish_at': finish_at
}
send_notify('Folder "{0}" updated'.format(title),
'''Folder title: {new[title]} (old: {0.title})
Start at: {new[start_at]} (old: {0.start_at})
Finish at: {new[finish_at]} (old: {0.finish_at})'''.format(folder,
new=new))
folder.title = title
folder.start_at = start_at
folder.finish_at = finish_at
session.add(folder)
session.commit()
finally:
session.close()
示例15: load
# 需要导入模块: from database import Session [as 别名]
# 或者: from database.Session import add [as 别名]
def load(file_):
nvdxml = utilities.NvdXml()
session = Session()
reader = csv.reader(file_)
next(reader, None) # Ignoring the header
for row in reader:
debug(row)
cve = Cve(id=row[0], year=utilities.get_year(row[0]), product=row[1])
nvd_details = nvdxml.get_details(cve.id)
if nvd_details:
cve.cvss = Cvss()
cve.cvss.access_complexity = nvd_details['access-complexity']
cve.cvss.access_vector = nvd_details['access-vector']
cve.cvss.authentication = nvd_details['authentication']
cve.cvss.availability_impact = nvd_details['availability-impact']
cve.cvss.confidentiality_impact = nvd_details[
'confidentiality-impact'
]
cve.cvss.integrity_impact = nvd_details['integrity-impact']
cve.cvss.score = nvd_details['score']
cve.cvss.exploitability_subscore = nvd_details[
'exploitability-subscore'
]
cve.cvss.impact_subscore = nvd_details[
'impact-subscore'
]
cve.bounty = Bounty()
cve.bounty.amount = float(row[2].replace('$', '').replace(',', ''))
session.add(cve)
try:
session.commit()
except sqlalchemy.exc.IntegrityError as e:
error('{} is a duplicate.'.format(cve.id))
session.rollback()
else:
warning('{} was not found in NVD.'.format(cve.id))