本文整理汇总了Python中meta.Session类的典型用法代码示例。如果您正苦于以下问题:Python Session类的具体用法?Python Session怎么用?Python Session使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Session类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: all_related_revisions
def all_related_revisions(self):
'''Returns chronological list of all object revisions related to
this package. Includes PackageRevisions, PackageTagRevisions,
PackageExtraRevisions and ResourceRevisions.
@return List of tuples (revision, [list of object revisions of this
revision])
Ordered by most recent first.
'''
from tag import PackageTag
from resource import ResourceGroup, Resource
from package_extra import PackageExtra
results = {} # revision:[PackageRevision1, PackageTagRevision1, etc.]
for pkg_rev in self.all_revisions:
if not results.has_key(pkg_rev.revision):
results[pkg_rev.revision] = []
results[pkg_rev.revision].append(pkg_rev)
for class_ in [ResourceGroup, Resource, PackageExtra, PackageTag]:
rev_class = class_.__revision_class__
if class_ == Resource:
q = Session.query(rev_class).join('continuity',
'resource_group')
obj_revisions = q.filter(ResourceGroup.package_id == self.id).all()
else:
obj_revisions = Session.query(rev_class).filter_by(package_id=self.id).all()
for obj_rev in obj_revisions:
if not results.has_key(obj_rev.revision):
results[obj_rev.revision] = []
results[obj_rev.revision].append(obj_rev)
result_list = results.items()
ourcmp = lambda rev_tuple1, rev_tuple2: \
cmp(rev_tuple2[0].timestamp, rev_tuple1[0].timestamp)
return sorted(result_list, cmp=ourcmp)
示例2: add_relationship
def add_relationship(self, type_, related_package, comment=u''):
'''Creates a new relationship between this package and a
related_package. It leaves the caller to commit the change.'''
import package_relationship
from ckan import model
if type_ in package_relationship.PackageRelationship.get_forward_types():
subject = self
object_ = related_package
elif type_ in package_relationship.PackageRelationship.get_reverse_types():
type_ = package_relationship.PackageRelationship.reverse_to_forward_type(type_)
assert type_
subject = related_package
object_ = self
else:
raise KeyError, 'Package relationship type: %r' % type_
rels = self.get_relationships(with_package=related_package,
type=type_, active=False, direction="forward")
if rels:
rel = rels[0]
if comment:
rel.comment=comment
if rel.state == model.State.DELETED:
rel.undelete()
else:
rel = package_relationship.PackageRelationship(
subject=subject,
object=object_,
type=type_,
comment=comment)
Session.add(rel)
return rel
示例3: diff
def diff(self, to_revision=None, from_revision=None):
"""Overrides the diff in vdm, so that related obj revisions are
diffed as well as PackageRevisions"""
from tag import PackageTag
from resource import ResourceGroup, Resource
from package_extra import PackageExtra
results = {} # field_name:diffs
results.update(super(Package, self).diff(to_revision, from_revision))
# Iterate over PackageTag, PackageExtra, Resources etc.
for obj_class in [ResourceGroup, Resource, PackageExtra, PackageTag]:
obj_rev_class = obj_class.__revision_class__
# Query for object revisions related to this package
if obj_class == Resource:
obj_rev_query = (
Session.query(obj_rev_class)
.join("continuity", "resource_group")
.join("revision")
.filter(ResourceGroup.package_id == self.id)
.order_by(Revision.timestamp.desc())
)
else:
obj_rev_query = (
Session.query(obj_rev_class)
.filter_by(package_id=self.id)
.join("revision")
.order_by(Revision.timestamp.desc())
)
# Columns to include in the diff
cols_to_diff = obj_class.revisioned_fields()
cols_to_diff.remove("id")
if obj_class is Resource:
cols_to_diff.remove("resource_group_id")
else:
cols_to_diff.remove("package_id")
# Particular object types are better known by an invariant field
if obj_class is PackageTag:
cols_to_diff.remove("tag_id")
elif obj_class is PackageExtra:
cols_to_diff.remove("key")
# Iterate over each object ID
# e.g. for PackageTag, iterate over Tag objects
related_obj_ids = set([related_obj.id for related_obj in obj_rev_query.all()])
for related_obj_id in related_obj_ids:
q = obj_rev_query.filter(obj_rev_class.id == related_obj_id)
to_obj_rev, from_obj_rev = super(Package, self).get_obj_revisions_to_diff(q, to_revision, from_revision)
for col in cols_to_diff:
values = [getattr(obj_rev, col) if obj_rev else "" for obj_rev in (from_obj_rev, to_obj_rev)]
value_diff = self._differ(*values)
if value_diff:
if obj_class.__name__ == "PackageTag":
display_id = to_obj_rev.tag.name
elif obj_class.__name__ == "PackageExtra":
display_id = to_obj_rev.key
else:
display_id = related_obj_id[:4]
key = "%s-%s-%s" % (obj_class.__name__, display_id, col)
results[key] = value_diff
return results
示例4: init_model
def init_model(engine):
"""Call me before using any of the tables or classes in the model"""
sm = orm.sessionmaker(autoflush = True, autocommit = False, bind = engine)
meta.engine = engine
meta.Session = orm.scoped_session(sm)
Session.configure(bind = engine)
示例5: find_by_date
def find_by_date(cls, date, primary=False):
start = datetime.combine(date,time(0,0,0))
end = datetime.combine(date,time(23,59,59))
if primary == True:
return Session.query(TimeSlot).filter(TimeSlot.start_time.between(start,end)).filter(TimeSlot.primary==primary).order_by(TimeSlot.start_time).all()
else:
return Session.query(TimeSlot).filter(TimeSlot.start_time.between(start,end)).order_by(TimeSlot.start_time).all()
示例6: find_by_id
def find_by_id(cls, id, abort_404 = True, published = True):
if published:
#I can't see why this exists as events as published, not schedules
#Original: result = Session.query(Schedule).filter_by(id=id).filter_by(published=published).first()
result = Session.query(Schedule).filter_by(id=id).first()
else:
result = Session.query(Schedule).filter_by(id=id).first()
if result is None and abort_404:
abort(404, "No such Schedule")
return result
示例7: wrapper
def wrapper(*args, **kawrgs):
s = request.environ.get('beaker.session')
user_id = s.get('user', 0)
if user_id:
session = Session()
user = session.query(User).filter_by(id=user_id).first()
request.user = user
else:
request.user = None
request.result_status = {}
body = callback(*args, **kawrgs)
return body
示例8: __init__
def __init__(self):
"""Load initial application settings from database """
Application.__init__(self)
# setup the database session
database = 'sqlite:///%s'%os.path.join(APP_DIR,config.get('Inkcut','database_dir'),config.get('Inkcut','database_name'))
log.info("Database: %s"%database)
engine = create_engine(database)
Session.configure(bind=engine)
self.session = Session()
self.job = None
self._flags = {'block_callbacks':True}
示例9: __init__
def __init__(self):
"""Load initial application settings from database """
# setup the database session
engine = create_engine('sqlite:///%s'%os.path.join(APP_DIR,config.get('Inkcut','database_dir'),config.get('Inkcut','database_name')))
Session.configure(bind=engine)
self.session = Session()
self.job = None
self.ui = {
'main_window':MainWindow(self),
'device_dialog':DeviceDialog(self),
}
self.statusbar = self.ui['main_window'].widgets['statusbar']
示例10: install
def install():
Base.metadata.create_all(Session().bind)
data = [
("Chicago", "United States", ("60601", "60602", "60603", "60604")),
("Montreal", "Canada", ("H2S 3K9", "H2B 1V4", "H7G 2T8")),
("Edmonton", "Canada", ("T5J 1R9", "T5J 1Z4", "T5H 1P6")),
("New York", "United States", ("10001", "10002", "10003", "10004", "10005", "10006")),
("San Francisco", "United States", ("94102", "94103", "94104", "94105", "94107", "94108")),
]
countries = {}
all_post_codes = []
for city, country, postcodes in data:
try:
country = countries[country]
except KeyError:
countries[country] = country = Country(country)
city = City(city, country)
pc = [PostalCode(code, city) for code in postcodes]
Session.add_all(pc)
all_post_codes.extend(pc)
for i in xrange(1, 51):
person = Person(
"person %.2d" % i,
Address(street="street %.2d" % i, postal_code=all_post_codes[random.randint(0, len(all_post_codes) - 1)]),
)
Session.add(person)
Session.commit()
# start the demo fresh
Session.remove()
示例11: find_next_proposal
def find_next_proposal(cls, id, type_id, signed_in_person_id):
withdrawn = ProposalStatus.find_by_name('Withdrawn')
next = Session.query(Proposal).from_statement("""
SELECT
p.id
FROM
(SELECT id
FROM proposal
WHERE id <> %d
AND status_id <> %d
AND proposal_type_id = %d
EXCEPT
SELECT proposal_id AS id
FROM review
WHERE review.reviewer_id = %d) AS p
LEFT JOIN
review AS r
ON(p.id=r.proposal_id)
GROUP BY
p.id
ORDER BY COUNT(r.reviewer_id), RANDOM()
LIMIT 1
""" % (id, withdrawn.id, type_id, signed_in_person_id))
next = next.first()
if next is not None:
return next.id
else:
# looks like you've reviewed everything!
return None
示例12: find_accepted_by_id
def find_accepted_by_id(cls, id):
#status = ProposalStatus.find_by_name('Accepted')
#result = Session.query(Proposal).filter_by(id=id,status_id=status.id)
# Optimisation: assume that ProposalStatus of ID=1 is Accepted
result = Session.query(Proposal).filter_by(id=id,status_id=1).one()
return result
示例13: getEdgesDegree2ByNxMG
def getEdgesDegree2ByNxMG(self):
MG = nx.MultiGraph()
networkMG = Edge_data
queryMG = Session.query(networkMG)
Session.close()
for res in queryMG:
ed = res.compute_results(['edge_id','start_node','end_node'])
MG.add_edge(ed['start_node'], ed['end_node'], eid=ed['edge_id'])
nodes = MG.nodes()
for node in nodes:
if MG.degree(node) == 2:
edge1, edge2 = MG.edges(node)
ed1 =MG.get_edge_data(*edge1)[0]['eid']
ed2 = MG.get_edge_data(*edge2)[0]['eid']
#print '%s / %s / %s' %(node, ed1, ed2)
yield (ed1, ed2)
示例14: find_all_tiered
def find_all_tiered(cls):
sponsors = Session.query(Sponsor).order_by(Sponsor.weight).all()
tiers = {}
for tier in sponsor_tiers:
tiers[tier] = [sponsor for sponsor in sponsors
if sponsor.tier == tier]
return tiers
示例15: update_resources
def update_resources(self, res_dicts, autoflush=True):
'''Change this package\'s resources.
@param res_dicts - ordered list of dicts, each detailing a resource
The resource dictionaries contain 'url', 'format' etc. Optionally they
can also provide the 'id' of the Resource, to help matching
res_dicts to existing Resources. Otherwise, it searches
for an otherwise exactly matching Resource.
The caller is responsible for creating a revision and committing.'''
from ckan import model
assert isinstance(res_dicts, (list, tuple))
# Map the incoming res_dicts (by index) to existing resources
index_to_res = {}
# Match up the res_dicts by id
def get_resource_identity(resource_obj_or_dict):
if isinstance(resource_obj_or_dict, dict):
# Convert dict into a Resource object, since that ensures
# all columns exist when you redictize it. This object is
# garbage collected as it isn't added to the Session.
res_keys = set(resource_obj_or_dict.keys()) - \
set(('id', 'position'))
res_dict = dict([(res_key, resource_obj_or_dict[res_key]) \
for res_key in res_keys])
resource = model.Resource(**res_dict)
else:
resource = resource_obj_or_dict
res_dict = resource.as_dict(core_columns_only=True)
return res_dict
existing_res_identites = [get_resource_identity(res) \
for res in self.resources]
for i, res_dict in enumerate(res_dicts):
assert isinstance(res_dict, dict)
id = res_dict.get('id')
if id:
res = Session.query(model.Resource).autoflush(autoflush).get(id)
if res:
index_to_res[i] = res
else:
res_identity = get_resource_identity(res_dict)
try:
matching_res_index = existing_res_identites.index(res_identity)
except ValueError:
continue
index_to_res[i] = self.resources[matching_res_index]
# Edit resources and create the new ones
new_res_list = []
for i, res_dict in enumerate(res_dicts):
if i in index_to_res:
res = index_to_res[i]
for col in set(res_dict.keys()) - set(('id', 'position')):
setattr(res, col, res_dict[col])
else:
# ignore particular keys that disrupt creation of new resource
for key in set(res_dict.keys()) & set(('id', 'position')):
del res_dict[key]
res = model.Resource(**res_dict)
model.Session.add(res)
new_res_list.append(res)
self.resource_groups[0].resources = new_res_list