本文整理汇总了Python中database.Session类的典型用法代码示例。如果您正苦于以下问题:Python Session类的具体用法?Python Session怎么用?Python Session使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Session类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: register_view
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: main
def main():
from_date = datetime.date(*map(int, sys.argv[1].split('-')))
to_date = datetime.date(*map(int, sys.argv[2].split('-')))
assert from_date <= to_date
quote = decode_quote(sys.argv[3])
#print quote
session = Session()
lit_years = {}
date = from_date
while date <= to_date:
found = False
session.rollback()
lit_date = get_lit_date(date, lit_years, session)
masses = []
try:
masses = lit_date.get_masses(strict=True)
except SelectingMassException:
pass
for mass in masses:
if found:
break
for reading in mass.readings:
try:
verses = decode_quote(reading.quote)
except BadQuoteException:
pass
if quotes_intersect(quote, verses):
print "%s: %s" % (date, reading.quote)
found = True
break
date += datetime.timedelta(days=1)
示例3: main
def main():
Base.metadata.create_all(engine)
session = Session()
video_fetcher = VideoFetcher('a', 10)
video_fetcher.get_new_views_for_existing_videos(session)
video_fetcher.get_new_videos(session)
session.commit()
示例4: sign_up
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: get_announcements
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()
示例6: load
def load(file_path):
if not file_path.endswith('xml'):
print('Not an XML file:' + file_path)
pass
if file_path.endswith('DIY.xml'):
author, title, sections = parse_xml(open(file_path))
else:
author, title, sections = parse_perseus(open(file_path),'div1')
session = Session()
a = get_or_create(session, Author, name=author)
session.commit()
t = get_or_create(session, Text, name=title, author=a.id)
session.commit()
global_ngrams = session.query(GlobalNgrams).first()
section_count = 1
log('Loading: ' + t.name)
if not USE_ORIGINAL_DIVISIONS:
sections = [' '.join(sections)]
if DIVISION_LENGTH:
sections = create_chunks(sections[0],DIVISION_LENGTH)
for sec in sections:
temp_section = get_or_create(session, Section, source_text=t.id, number=section_count)
log('Loading section ' + str(section_count))
session.commit()
temp_section_content = get_or_create(session, SectionContent, section = temp_section.id, content = sec)
log('Creating ngrams of ' + str(section_count))
temp_section_ngrams = get_or_create(session, SectionNgrams, section = temp_section.id, ngrams = generate_ngrams(temp_section_content.content))
log('Updating global ngram counts.')
update_global_counts(session, global_ngrams,temp_section_ngrams.ngrams)
section_count = section_count + 1
session.commit()
update_vector_space(session, global_ngrams)
示例7: on_return
def on_return(self, task):
"""Called by main thread on the return of data from the workers.
Post-processing"""
logger.info("Retrieved task %s", task.tag)
traj = Session.query(models.Trajectory).get(int(task.tag))
try:
# save lh5 version of the trajectory
conf = load_file(self.project.pdb_topology_file)
coordinates = msmbuilder.Trajectory.load_trajectory_file(str(traj.dry_xtc_fn), Conf=conf)
save_file(traj.lh5_fn, coordinates)
except Exception as e:
logger.error("When postprocessing %s, convert to lh5 failed!", traj)
logger.exception(e)
raise
# convert last_wet_snapshot to lh5
pdb_to_lh5(traj, "last_wet_snapshot_fn")
pdb_to_lh5(traj, "init_pdb_fn")
traj.host = task.host
traj.returned_time = datetime.now()
traj.length = len(coordinates)
Session.flush()
Session.commit()
logger.info("Finished converting new traj to lh5 sucessfully")
示例8: main
def main():
reading_id = int(sys.argv[1])
session = Session()
reading = session.query(Reading).filter(Reading.id == reading_id).one()
text = reading.text
PrependStream(sys.stdout, ' ').write('"' + text.strip() + '"')
sys.stdout.write('\n')
session.rollback()
示例9: index
def index():
if session.get('logged_in'):
return redirect(url_for('main'))
new = Session.query(music).order_by(music.id.desc())[0:10]
most = Session.query(music).order_by(music.count.desc())[0:10]
return render_template('login.html', most=most, new = new)
示例10: login_check
def login_check(user_name):
session = Session()
user = session.query(User).filter(or_(
User.nickname == user_name)).first()
print session
session.commit()
if not user:
return None
return user
示例11: albuminfo
def albuminfo ():
data = request.get_json()
album1 = Session.query(album).filter(album.id==data['id']).one()
json_data = dict(id = data['id'] ,name=album1.name,singer=album1.singer, url=album1.name+'.jpg', musicnum = album1.music_count)
musiclist1=[]
for m in Session.query(music).filter(music.albumid==data['id']).order_by(music.num).all():
musiclist1.append(m.diction())
json_data ["musiclist"] =musiclist1
return jsonify(json_data)
示例12: submit
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('chmod +x ./{driver}; ./{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()
self.wq.submit(task)
logger.info('Submitted to queue: %s', traj)
示例13: check_db
def check_db(loud=False, delete_orphans=False, fix=False):
session = Session()
check_orphans(session, loud, delete_orphans)
check_readings(session, loud, fix)
check_masses(session, loud)
check_events(session, loud)
#session.commit()
session.rollback()
session.close()
示例14: add_forcefields_to_db
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"
示例15: getlist
def getlist():
data = request.get_json()
item = Session.query(playlist_item).filter(playlist_item.listid==data['id']).order_by(playlist_item.order).all()
json_data = dict(id = data['id'])
musiclist = []
for m in item:
mm = m.music.diction()
mm["order"] = m.order
musiclist.append(mm)
json_data ["name"] = Session.query(playlist.name).filter(playlist.id==data['id']).first()
json_data ["musiclist"] =musiclist
return jsonify(json_data)