本文整理汇总了Python中meta.Session类的典型用法代码示例。如果您正苦于以下问题:Python Session类的具体用法?Python Session怎么用?Python Session使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Session类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:AdamJensen-dk,项目名称:ckan-drupal,代码行数:34,代码来源:package.py
示例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
开发者ID:AdamJensen-dk,项目名称:ckan-drupal,代码行数:32,代码来源:package.py
示例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
开发者ID:jakebarnwell,项目名称:PythonGenerator,代码行数:59,代码来源:package.py
示例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)
开发者ID:vhallac,项目名称:rails_to_pylons,代码行数:8,代码来源:__init__.py
示例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()
开发者ID:PaulWay,项目名称:zookeepr,代码行数:8,代码来源:time_slot.py
示例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
开发者ID:SharifulAlamSourav,项目名称:zookeepr,代码行数:11,代码来源:schedule.py
示例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
开发者ID:endeavorchan,项目名称:dessert-house,代码行数:12,代码来源:plugins.py
示例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}
开发者ID:pc-coholic,项目名称:Inkcut,代码行数:12,代码来源:inkcut.py
示例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']
开发者ID:pc-coholic,项目名称:Inkcut,代码行数:14,代码来源:inkcut.py
示例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()
开发者ID:simplegeo,项目名称:sqlalchemy,代码行数:35,代码来源:fixture_data.py
示例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
开发者ID:SharifulAlamSourav,项目名称:zookeepr,代码行数:29,代码来源:proposal.py
示例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
开发者ID:SharifulAlamSourav,项目名称:zookeepr,代码行数:7,代码来源:proposal.py
示例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)
开发者ID:loicgasser,项目名称:top4net,代码行数:16,代码来源:bug23.py
示例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
开发者ID:ben-denham,项目名称:zookeepr,代码行数:7,代码来源:sponsor.py
示例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
开发者ID:AdamJensen-dk,项目名称:ckan-drupal,代码行数:60,代码来源:package.py
示例16: get_entities
def get_entities(entity_class, ids, order=True):
'''
Return all entities of the type *entity_class* where id is
in *ids*.
*entity_class*
An slqalchemy model class.
*ids* (list of int)
A list of ids.
*order* (boolean)
Return the entities in the same order as *ids* (default: True)
Returns
A list of model objects
'''
if ids == []:
return []
from meta import Session
db_mapper_attr = ref_attr_value(entity_class)
q = Session.query(entity_class).filter(db_mapper_attr.in_(ids))
if not order:
return q.all()
# order == True: get and order the results
all_map = dict((str(ref_attr_value(entity)), entity) for entity in q.all())
ordered_results = []
for id_ in ids:
entity = all_map.get(str(id_))
if entity is not None:
ordered_results.append(entity)
return ordered_results
开发者ID:alkadis,项目名称:vcv,代码行数:33,代码来源:refs.py
示例17: select_values
def select_values(self):
streams = Session.query(Stream).order_by(Stream.name).all()
values = [ (None, '(none)') ]
for stream in streams:
v = (stream.id, stream.name)
values.append(v)
return values
开发者ID:Ivoz,项目名称:zookeepr,代码行数:7,代码来源:stream.py
示例18: get_relationships
def get_relationships(self, with_package=None, type=None, active=True,
direction='both'):
'''Returns relationships this package has.
Keeps stored type/ordering (not from pov of self).'''
assert direction in ('both', 'forward', 'reverse')
if with_package:
assert isinstance(with_package, Package)
from package_relationship import PackageRelationship
forward_filters = [PackageRelationship.subject==self]
reverse_filters = [PackageRelationship.object==self]
if with_package:
forward_filters.append(PackageRelationship.object==with_package)
reverse_filters.append(PackageRelationship.subject==with_package)
if active:
forward_filters.append(PackageRelationship.state==State.ACTIVE)
reverse_filters.append(PackageRelationship.state==State.ACTIVE)
if type:
forward_filters.append(PackageRelationship.type==type)
reverse_type = PackageRelationship.reverse_type(type)
reverse_filters.append(PackageRelationship.type==reverse_type)
q = Session.query(PackageRelationship)
if direction == 'both':
q = q.filter(or_(
and_(*forward_filters),
and_(*reverse_filters),
))
elif direction == 'forward':
q = q.filter(and_(*forward_filters))
elif direction == 'reverse':
q = q.filter(and_(*reverse_filters))
return q.all()
开发者ID:AdamJensen-dk,项目名称:ckan-drupal,代码行数:31,代码来源:package.py
示例19: find_scheduled_by_date_and_type
def find_scheduled_by_date_and_type(cls, date, event_type):
from schedule import Schedule
from event import Event
from time_slot import TimeSlot
start = datetime.combine(date,time(0,0,0))
end = datetime.combine(date,time(23,59,59))
return Session.query(Location).join(Schedule).join(Event).join(TimeSlot).filter(Event.type==event_type).filter(TimeSlot.start_time.between(start, end)).order_by(Location.display_order).all()
开发者ID:PaulWay,项目名称:zookeepr,代码行数:8,代码来源:location.py
示例20: __init__
def __init__(self):
"""
Database loading.
"""
self.sites = [] # list with all sites objects
self.logger = Logger("Manager")
self.session = Session()
self.sites = self.session.query(Site).all() # loading all sites
开发者ID:Menda,项目名称:Leolo,代码行数:8,代码来源:manager.py
注:本文中的meta.Session类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论