本文整理汇总了Python中cms.db.Session.add方法的典型用法代码示例。如果您正苦于以下问题:Python Session.add方法的具体用法?Python Session.add怎么用?Python Session.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cms.db.Session
的用法示例。
在下文中一共展示了Session.add方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: AddStatementHandler
# 需要导入模块: from cms.db import Session [as 别名]
# 或者: from cms.db.Session import add [as 别名]
class AddStatementHandler(BaseHandler):
"""Add a statement to a task.
"""
@require_permission(BaseHandler.PERMISSION_ALL)
def get(self, task_id):
task = self.safe_get_item(Task, task_id)
self.r_params = self.render_params()
self.r_params["task"] = task
self.render("add_statement.html", **self.r_params)
@require_permission(BaseHandler.PERMISSION_ALL)
def post(self, task_id):
fallback_page = "/task/%s/statements/add" % task_id
task = self.safe_get_item(Task, task_id)
language = self.get_argument("language", None)
if language is None:
self.application.service.add_notification(
make_datetime(), "No language code specified",
"The language code can be any string.")
self.redirect(fallback_page)
return
statement = self.request.files["statement"][0]
if not statement["filename"].endswith(".pdf"):
self.application.service.add_notification(
make_datetime(), "Invalid task statement",
"The task statement must be a .pdf file.")
self.redirect(fallback_page)
return
task_name = task.name
self.sql_session.close()
try:
digest = self.application.service.file_cacher.put_file_content(
statement["body"],
"Statement for task %s (lang: %s)" % (task_name, language))
except Exception as error:
self.application.service.add_notification(
make_datetime(), "Task statement storage failed", repr(error))
self.redirect(fallback_page)
return
# TODO verify that there's no other Statement with that language
# otherwise we'd trigger an IntegrityError for constraint violation
self.sql_session = Session()
task = self.safe_get_item(Task, task_id)
self.contest = task.contest
statement = Statement(language, digest, task=task)
self.sql_session.add(statement)
if self.try_commit():
self.redirect("/task/%s" % task_id)
else:
self.redirect(fallback_page)
示例2: main
# 需要导入模块: from cms.db import Session [as 别名]
# 或者: from cms.db.Session import add [as 别名]
def main():
# Get session
session = Session()
# Apre una sessione e lista i forum
# forums = session.query(Forum).all()
forums = session.query(forum.Forum).all()
print "Forums found: ", len(forums)
params = {'title': "Discussioni sul sito", 'description': "Per malfunzionamenti, dubbi o suggerimenti relativi al sito."}
my_forum = forum.Forum(**params)
session.add(my_forum)
session.commit()
示例3: AddManagerHandler
# 需要导入模块: from cms.db import Session [as 别名]
# 或者: from cms.db.Session import add [as 别名]
class AddManagerHandler(BaseHandler):
"""Add a manager to a dataset.
"""
@require_permission(BaseHandler.PERMISSION_ALL)
def get(self, dataset_id):
dataset = self.safe_get_item(Dataset, dataset_id)
task = dataset.task
self.contest = task.contest
self.r_params = self.render_params()
self.r_params["task"] = task
self.r_params["dataset"] = dataset
self.render("add_manager.html", **self.r_params)
@require_permission(BaseHandler.PERMISSION_ALL)
def post(self, dataset_id):
fallback_page = self.url("dataset", dataset_id, "managers", "add")
dataset = self.safe_get_item(Dataset, dataset_id)
task = dataset.task
manager = self.request.files["manager"][0]
task_name = task.name
self.sql_session.close()
try:
digest = self.service.file_cacher.put_file_content(
manager["body"],
"Task manager for %s" % task_name)
except Exception as error:
self.service.add_notification(
make_datetime(),
"Manager storage failed",
repr(error))
self.redirect(fallback_page)
return
self.sql_session = Session()
dataset = self.safe_get_item(Dataset, dataset_id)
task = dataset.task
manager = Manager(manager["filename"], digest, dataset=dataset)
self.sql_session.add(manager)
if self.try_commit():
self.redirect(self.url("task", task.id))
else:
self.redirect(fallback_page)
示例4: AddSpoilerHandler
# 需要导入模块: from cms.db import Session [as 别名]
# 或者: from cms.db.Session import add [as 别名]
class AddSpoilerHandler(BaseHandler):
"""Add a spoiler to a task.
"""
@require_permission(BaseHandler.PERMISSION_ALL)
def get(self, task_id):
task = self.safe_get_item(Task, task_id)
self.contest = task.contest
self.r_params = self.render_params()
self.r_params["task"] = task
self.render("add_spoiler.html", **self.r_params)
@require_permission(BaseHandler.PERMISSION_ALL)
def post(self, task_id):
fallback_page = self.url("task", task_id, "spoiler", "add")
task = self.safe_get_item(Task, task_id)
spoiler = self.request.files["spoiler"][0]
task_name = task.name
self.sql_session.close()
try:
digest = self.service.file_cacher.put_file_content(
spoiler["body"],
"Task spoiler for %s" % task_name)
except Exception as error:
self.service.add_notification(
make_datetime(),
"Spoiler storage failed",
repr(error))
self.redirect(fallback_page)
return
# TODO verify that there's no other Spoiler with that filename
# otherwise we'd trigger an IntegrityError for constraint violation
self.sql_session = Session()
task = self.safe_get_item(Task, task_id)
spoiler = Spoiler(spoiler["filename"], digest, task=task)
self.sql_session.add(spoiler)
if self.try_commit():
self.redirect(self.url("task", task_id))
else:
self.redirect(fallback_page)
示例5: AddAttachmentHandler
# 需要导入模块: from cms.db import Session [as 别名]
# 或者: from cms.db.Session import add [as 别名]
class AddAttachmentHandler(BaseHandler):
"""Add an attachment to a task.
"""
@require_permission(BaseHandler.PERMISSION_ALL)
def get(self, task_id):
task = self.safe_get_item(Task, task_id)
self.r_params = self.render_params()
self.r_params["task"] = task
self.render("add_attachment.html", **self.r_params)
@require_permission(BaseHandler.PERMISSION_ALL)
def post(self, task_id):
fallback_page = "/task/%s/attachments/add" % task_id
task = self.safe_get_item(Task, task_id)
attachment = self.request.files["attachment"][0]
task_name = task.name
self.sql_session.close()
try:
digest = self.application.service.file_cacher.put_file_content(
attachment["body"],
"Task attachment for %s" % task_name)
except Exception as error:
self.application.service.add_notification(
make_datetime(),
"Attachment storage failed",
repr(error))
self.redirect(fallback_page)
return
# TODO verify that there's no other Attachment with that filename
# otherwise we'd trigger an IntegrityError for constraint violation
self.sql_session = Session()
task = self.safe_get_item(Task, task_id)
attachment = Attachment(attachment["filename"], digest, task=task)
self.sql_session.add(attachment)
if self.try_commit():
self.redirect("/task/%s" % task_id)
else:
self.redirect(fallback_page)
示例6: TestCaseWithDatabase
# 需要导入模块: from cms.db import Session [as 别名]
# 或者: from cms.db.Session import add [as 别名]
class TestCaseWithDatabase(unittest.TestCase):
"""TestCase subclass starting with a clean testing database."""
@classmethod
def setUpClass(cls):
assert "fortesting" in str(cms.db.engine), \
"Monkey patching of DB connection string failed"
drop_db()
init_db()
cls.connection = cms.db.engine.connect()
cms.db.metadata.create_all(cls.connection)
@classmethod
def tearDownClass(cls):
drop_db()
cls.connection.close()
cms.db.engine.dispose()
def setUp(self):
self.session = Session()
def tearDown(self):
self.session.rollback()
def delete_data(self):
"""Delete all the data in the DB.
This is useful to call during tear down, for tests that rely on
starting from a clean DB.
"""
for table in itervalues(Base.metadata.tables):
self.session.execute(table.delete())
self.session.commit()
@staticmethod
def add_fsobject(digest, content):
dbbackend = DBBackend()
fobj = dbbackend.create_file(digest)
fobj.write(content)
dbbackend.commit_file(fobj, digest)
@staticmethod
def get_contest(**kwargs):
"""Create a contest"""
args = {
"name": unique_unicode_id(),
"description": unique_unicode_id(),
}
args.update(kwargs)
contest = Contest(**args)
return contest
def add_contest(self, **kwargs):
"""Create a contest and add it to the session"""
contest = self.get_contest(**kwargs)
self.session.add(contest)
return contest
@staticmethod
def get_user(**kwargs):
"""Create a user"""
args = {
"username": unique_unicode_id(),
"password": "",
"first_name": unique_unicode_id(),
"last_name": unique_unicode_id(),
}
args.update(kwargs)
user = User(**args)
return user
def add_user(self, **kwargs):
"""Create a user and add it to the session"""
user = self.get_user(**kwargs)
self.session.add(user)
return user
@staticmethod
def get_participation(user=None, contest=None, **kwargs):
"""Create a participation"""
user = user if user is not None else TestCaseWithDatabase.get_user()
contest = contest \
if contest is not None else TestCaseWithDatabase.get_contest()
args = {
"user": user,
"contest": contest,
}
args.update(kwargs)
participation = Participation(**args)
return participation
def add_participation(self, **kwargs):
"""Create a participation and add it to the session"""
participation = self.get_participation(**kwargs)
self.session.add(participation)
return participation
@staticmethod
def get_task(**kwargs):
#.........这里部分代码省略.........
示例7: AddTestcaseHandler
# 需要导入模块: from cms.db import Session [as 别名]
# 或者: from cms.db.Session import add [as 别名]
class AddTestcaseHandler(BaseHandler):
"""Add a testcase to a dataset.
"""
@require_permission(BaseHandler.PERMISSION_ALL)
def get(self, dataset_id):
dataset = self.safe_get_item(Dataset, dataset_id)
task = dataset.task
self.r_params = self.render_params()
self.r_params["task"] = task
self.r_params["dataset"] = dataset
self.render("add_testcase.html", **self.r_params)
@require_permission(BaseHandler.PERMISSION_ALL)
def post(self, dataset_id):
fallback_page = "/dataset/%s/testcases/add" % dataset_id
dataset = self.safe_get_item(Dataset, dataset_id)
task = dataset.task
codename = self.get_argument("codename")
try:
input_ = self.request.files["input"][0]
output = self.request.files["output"][0]
except KeyError:
self.application.service.add_notification(
make_datetime(),
"Invalid data",
"Please fill both input and output.")
self.redirect(fallback_page)
return
public = self.get_argument("public", None) is not None
task_name = task.name
self.sql_session.close()
try:
input_digest = \
self.application.service.file_cacher.put_file_content(
input_["body"],
"Testcase input for task %s" % task_name)
output_digest = \
self.application.service.file_cacher.put_file_content(
output["body"],
"Testcase output for task %s" % task_name)
except Exception as error:
self.application.service.add_notification(
make_datetime(),
"Testcase storage failed",
repr(error))
self.redirect(fallback_page)
return
self.sql_session = Session()
dataset = self.safe_get_item(Dataset, dataset_id)
task = dataset.task
testcase = Testcase(
codename, public, input_digest, output_digest, dataset=dataset)
self.sql_session.add(testcase)
if self.try_commit():
# max_score and/or extra_headers might have changed.
self.application.service.proxy_service.reinitialize()
self.redirect("/task/%s" % task.id)
else:
self.redirect(fallback_page)
示例8: AddTestcasesHandler
# 需要导入模块: from cms.db import Session [as 别名]
# 或者: from cms.db.Session import add [as 别名]
class AddTestcasesHandler(BaseHandler):
"""Add several testcases to a dataset.
"""
@require_permission(BaseHandler.PERMISSION_ALL)
def get(self, dataset_id):
dataset = self.safe_get_item(Dataset, dataset_id)
task = dataset.task
self.r_params = self.render_params()
self.r_params["task"] = task
self.r_params["dataset"] = dataset
self.render("add_testcases.html", **self.r_params)
@require_permission(BaseHandler.PERMISSION_ALL)
def post(self, dataset_id):
fallback_page = "/dataset/%s/testcases/add_multiple" % dataset_id
# TODO: this method is quite long, some splitting is needed.
dataset = self.safe_get_item(Dataset, dataset_id)
task = dataset.task
try:
archive = self.request.files["archive"][0]
except KeyError:
self.application.service.add_notification(
make_datetime(),
"Invalid data",
"Please choose tests archive.")
self.redirect(fallback_page)
return
public = self.get_argument("public", None) is not None
overwrite = self.get_argument("overwrite", None) is not None
# Get input/output file names templates, or use default ones.
input_template = self.get_argument("input_template", "input.*")
output_template = self.get_argument("output_template", "output.*")
input_re = re.compile(re.escape(input_template).replace("\\*",
"(.*)") + "$")
output_re = re.compile(re.escape(output_template).replace("\\*",
"(.*)") + "$")
task_name = task.name
self.sql_session.close()
fp = StringIO(archive["body"])
try:
with zipfile.ZipFile(fp, "r") as archive_zfp:
tests = dict()
# Match input/output file names to testcases' codenames.
for filename in archive_zfp.namelist():
match = input_re.match(filename)
if match:
codename = match.group(1)
if codename not in tests:
tests[codename] = [None, None]
tests[codename][0] = filename
else:
match = output_re.match(filename)
if match:
codename = match.group(1)
if codename not in tests:
tests[codename] = [None, None]
tests[codename][1] = filename
skipped_tc = []
overwritten_tc = []
added_tc = []
for codename, testdata in tests.iteritems():
# If input or output file isn't found, skip it.
if not testdata[0] or not testdata[1]:
continue
self.sql_session = Session()
# Check, whether current testcase already exists.
dataset = self.safe_get_item(Dataset, dataset_id)
task = dataset.task
if codename in dataset.testcases:
# If we are allowed, remove existing testcase.
# If not - skip this testcase.
if overwrite:
testcase = dataset.testcases[codename]
self.sql_session.delete(testcase)
if not self.try_commit():
skipped_tc.append(codename)
continue
overwritten_tc.append(codename)
else:
skipped_tc.append(codename)
continue
# Add current testcase.
try:
input_ = archive_zfp.read(testdata[0])
output = archive_zfp.read(testdata[1])
except Exception as error:
self.application.service.add_notification(
make_datetime(),
#.........这里部分代码省略.........
示例9: TestCaseWithDatabase
# 需要导入模块: from cms.db import Session [as 别名]
# 或者: from cms.db.Session import add [as 别名]
class TestCaseWithDatabase(unittest.TestCase):
"""TestCase subclass starting with a clean testing database."""
@classmethod
def setUpClass(cls):
cms.db.engine = create_engine(cms.config.database)
drop_db()
init_db()
cls.connection = cms.db.engine.connect()
cms.db.metadata.create_all(cls.connection)
@classmethod
def tearDownClass(cls):
drop_db()
cls.connection.close()
cms.db.engine.dispose()
def setUp(self):
self.session = Session()
def tearDown(self):
self.session.rollback()
def add_contest(self, **kwargs):
"""Add a contest."""
args = {
"name": unique_unicode_id(),
"description": unique_unicode_id(),
}
args.update(kwargs)
contest = Contest(**args)
self.session.add(contest)
return contest
def add_user(self, **kwargs):
"""Add a user."""
args = {
"username": unique_unicode_id(),
"password": "",
"first_name": unique_unicode_id(),
"last_name": unique_unicode_id(),
}
args.update(kwargs)
user = User(**args)
self.session.add(user)
return user
def add_participation(self, user=None, contest=None, **kwargs):
"""Add a participation."""
user = user if user is not None else self.add_user()
contest = contest if contest is not None else self.add_contest()
args = {
"user": user,
"contest": contest,
}
args.update(kwargs)
participation = Participation(**args)
self.session.add(participation)
return participation
def add_task(self, contest=None, **kwargs):
"""Add a task."""
contest = contest if contest is not None else self.add_contest()
args = {
"contest": contest,
"name": unique_unicode_id(),
"title": unique_unicode_id(),
}
args.update(kwargs)
task = Task(**args)
self.session.add(task)
return task
def add_dataset(self, task=None, **kwargs):
"""Add a dataset."""
task = task if task is not None else self.add_task()
args = {
"task": task,
"description": unique_unicode_id(),
"task_type": "",
"task_type_parameters": "",
"score_type": "",
"score_type_parameters": "",
}
args.update(kwargs)
dataset = Dataset(**args)
self.session.add(dataset)
return dataset
def add_testcase(self, dataset=None, **kwargs):
"""Add a testcase."""
dataset = dataset if dataset is not None else self.add_dataset()
args = {
"dataset": dataset,
"codename": unique_unicode_id(),
"input": unique_digest(),
"output": unique_digest(),
}
args.update(kwargs)
testcase = Testcase(**args)
#.........这里部分代码省略.........
示例10: DatabaseMixin
# 需要导入模块: from cms.db import Session [as 别名]
# 或者: from cms.db.Session import add [as 别名]
class DatabaseMixin(DatabaseObjectGeneratorMixin):
"""Mixin for tests with database access."""
@classmethod
def setUpClass(cls):
super(DatabaseMixin, cls).setUpClass()
assert "fortesting" in str(engine), \
"Monkey patching of DB connection string failed"
drop_db()
init_db()
@classmethod
def tearDownClass(cls):
drop_db()
super(DatabaseMixin, cls).tearDownClass()
def setUp(self):
super(DatabaseMixin, self).setUp()
self.session = Session()
def tearDown(self):
self.session.rollback()
super(DatabaseMixin, self).tearDown()
def delete_data(self):
"""Delete all the data in the DB.
This is useful to call during tear down, for tests that rely on
starting from a clean DB.
"""
for table in itervalues(metadata.tables):
self.session.execute(table.delete())
self.session.commit()
@staticmethod
def add_fsobject(digest, content):
dbbackend = DBBackend()
fobj = dbbackend.create_file(digest)
fobj.write(content)
dbbackend.commit_file(fobj, digest)
def add_contest(self, **kwargs):
"""Create a contest and add it to the session"""
contest = self.get_contest(**kwargs)
self.session.add(contest)
return contest
def add_announcement(self, **kwargs):
"""Create an announcement and add it to the session"""
announcement = self.get_announcement(**kwargs)
self.session.add(announcement)
return announcement
def add_user(self, **kwargs):
"""Create a user and add it to the session"""
user = self.get_user(**kwargs)
self.session.add(user)
return user
def add_participation(self, **kwargs):
"""Create a participation and add it to the session"""
participation = self.get_participation(**kwargs)
self.session.add(participation)
return participation
def add_message(self, **kwargs):
"""Create a message and add it to the session"""
message = self.get_message(**kwargs)
self.session.add(message)
return message
def add_question(self, **kwargs):
"""Create a question and add it to the session"""
question = self.get_question(**kwargs)
self.session.add(question)
return question
def add_task(self, **kwargs):
"""Create a task and add it to the session"""
task = self.get_task(**kwargs)
self.session.add(task)
return task
def add_statement(self, task=None, **kwargs):
"""Create a statement and add it to the session"""
task = task if task is not None else self.add_task()
args = {
"task": task,
"digest": unique_digest(),
"language": unique_unicode_id(),
}
args.update(kwargs)
statement = Statement(**args)
self.session.add(statement)
return statement
def add_dataset(self, **kwargs):
"""Create a dataset and add it to the session"""
dataset = self.get_dataset(**kwargs)
#.........这里部分代码省略.........