本文整理汇总了Python中sqlalchemy.orm.load_only函数的典型用法代码示例。如果您正苦于以下问题:Python load_only函数的具体用法?Python load_only怎么用?Python load_only使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了load_only函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: quarterly_review
def quarterly_review(quarter):
quarter = str(quarter)
sortingDictionary = {0: Attendee.id, 1: Attendee.year, 2: Attendee.first_name, 3: Attendee.last_name }
siftingDictionary = {1: "freshman", 2: "sophomore", 3: "junior", 4: "senior", 5: "other" }
# get params
sort = request.args.get('sort', 0, type=int)
sift = request.args.get('sift', 0, type=int)
weeks = [0 for i in range(10)]
if (sift == 0):
users = db.session.query(Attendee).order_by(sortingDictionary[sort]).options(load_only("id", "first_name", "last_name", "year"))
userCount = db.session.query(Attendee).order_by(sortingDictionary[sort]).options(load_only("id", "first_name", "last_name", "year")).count()
else:
users = db.session.query(Attendee).filter_by(year=siftingDictionary[sift]).order_by(sortingDictionary[sort]).options(load_only("id", "first_name", "last_name", "year"))
userCount = db.session.query(Attendee).filter_by(year=siftingDictionary[sift]).order_by(sortingDictionary[sort]).options(load_only("id", "first_name", "last_name", "year")).count()
attendanceArray = [[0 for i in range(10)] for j in range(userCount)]
sumArray = [0 for i in range(userCount)]
weekDB = db.session.query(LargeGroup).filter_by(quarter=quarter).options(load_only("id"))
# set up full quarter week array with db ID's if exists, 0 otherwise
for week in weekDB:
try:
weeks[int(week.weekNumber)-1] = week.id
except ValueError,e:
print str(e)
示例2: main
def main():
html_tag_regex = '<[a-zA-Z]+.*>'
contributions = (Contribution.query
.filter(Contribution.description.op('~')(html_tag_regex))
.options(load_only('id', 'description'))
.all())
subcontributions = (SubContribution.query
.filter(SubContribution.description.op('~')(html_tag_regex))
.options(load_only('id', 'description'))
.all())
categories = (Category.query
.filter(Category.description.op('~')(html_tag_regex))
.options(load_only('id', 'description'))
.all())
def as_dict(objs):
return {x.id: x.description for x in objs}
def format_table(model):
return model.__table__.fullname
object_descriptions = {
format_table(Contribution): as_dict(contributions),
format_table(SubContribution): as_dict(subcontributions),
format_table(Category): as_dict(categories)
}
env = Environment(loader=FileSystemLoader(os.path.dirname(__file__)))
template = env.get_template('fix_descriptions_template.html')
print(template.render(object_descriptions=htmlsafe_dumps(object_descriptions)))
示例3: post
def post(self, course_id, question_id, answer_id, comment_id):
"""
Create an answer comment
"""
Courses.exists_or_404(course_id)
PostsForQuestions.query.options(load_only('id')).get_or_404(question_id)
PostsForAnswers.query.options(load_only('id')).get_or_404(answer_id)
comment = PostsForComments.query.get_or_404(comment_id)
require(EDIT, comment)
params = existing_comment_parser.parse_args()
# make sure the comment id in the rul and the id matches
if params['id'] != comment.id:
return {"error": "Comment id does not match URL."}, 400
# modify comment according to new values, preserve original values if values not passed
comment.content = params.get("content")
if not comment.content:
return {"error": "The comment content is empty!"}, 400
comment.answer_assoc.type = params.get("type")
db.session.add(comment)
on_answer_comment_modified.send(
self,
event_name=on_answer_comment_modified.name,
user=current_user,
course_id=course_id,
data=get_model_changes(comment))
db.session.commit()
return marshal(comment, dataformat.get_answer_comment())
示例4: autocomplete
def autocomplete():
search = unicode(request.args.get('q'))
products = Product.query.options(load_only("title", "id")).filter(Product.title.startswith(search), Product.status == 'publish').limit(5).all()
products2 = Product.query.options(load_only("title", "id")).filter(Product.title.contains('%' + search + '%'), Product.status == 'publish').limit(5).all()
p = {}
q = []
for product in products:
# p.extend(['{ title:'+product.title+', image: '+product.image+'}'])
p = {"label": product.title, "url": "/p/" + str(product.id)}
q.extend([p])
for product in products2:
r = {"label": product.title, "url": "/p/" + str(product.id)}
q.extend([r])
seen = set() # http://stackoverflow.com/questions/9427163/remove-duplicate-dict-in-list-in-python
l = []
for d in q:
t = tuple(d.items())
if t not in seen:
seen.add(t)
l.append(d)
products = json.dumps(l)
response = Response(products, mimetype='application/json')
return response
示例5: _relevant_to_snapshot
def _relevant_to_snapshot(object_name, ids):
"""Filter by relevant object over snapshot"""
snapshot_qs = models.Snapshot.query.filter(
models.Snapshot.parent_type == models.Audit.__name__,
models.Snapshot.child_type == object_name,
models.Snapshot.child_id.in_(ids),
).options(
load_only(models.Snapshot.id),
).distinct(
).subquery(
"snapshot"
)
dest_qs = models.Relationship.query.filter(
models.Relationship.destination_id == snapshot_qs.c.id,
models.Relationship.destination_type == models.Snapshot.__name__,
models.Relationship.source_type == object_class.__name__,
).options(
load_only("source_id")
).distinct()
source_qs = models.Relationship.query.filter(
models.Relationship.source_id == snapshot_qs.c.id,
models.Relationship.source_type == models.Snapshot.__name__,
models.Relationship.destination_type == object_class.__name__,
).options(
load_only("destination_id")
).distinct()
ids_qs = dest_qs.union(source_qs).distinct().subquery("ids")
return object_class.id == ids_qs.c.relationships_source_id
示例6: post
def post(self, course_id, question_id, criteria_id):
Courses.exists_or_404(course_id)
PostsForQuestions.query.options(load_only('id')).get_or_404(question_id)
Criteria.query.options(load_only('id')).get_or_404(criteria_id)
question = PostsForQuestions(post=Posts(courses_id=course_id))
criteria_question = CriteriaAndPostsForQuestions(question=question)
require(CREATE, criteria_question)
criteria_question = CriteriaAndPostsForQuestions.query.filter_by(criteria_id=criteria_id). \
filter_by(questions_id=question_id).first()
if criteria_question:
criteria_question.active = True
else:
criteria_question = CriteriaAndPostsForQuestions()
criteria_question.criteria_id = criteria_id
criteria_question.questions_id = question_id
db.session.add(criteria_question)
on_question_criteria_create.send(
self,
event_name=on_question_criteria_create.name,
user=current_user,
course_id=course_id,
data={'question_id': question_id, 'criteria_id': criteria_id})
db.session.commit()
return {'criterion': marshal(criteria_question, dataformat.get_criteria_and_posts_for_questions())}
示例7: render
def render(self, ctx, req):
if req.params.get('sEcho'):
# triggered from a datatable, thus potentially filtered and sorted
items = ctx.get_query(limit=1000)
else:
# triggered without any filter parameters
items = ctx.rdf_index_query(req.db.query(ctx.db_model()).order_by(ctx.db_model().pk))
if isinstance(ctx.model.name, property):
items = [(item.id, None) for item in items.options(load_only('id'))]
else:
items = [(item.id, item.name)
for item in items.options(load_only('id', 'name'))]
return convert(super(RdfIndex, self).render(items, req), 'xml', self.rdflibname)
示例8: get_events_with_linked_sessions
def get_events_with_linked_sessions(user, from_dt=None, to_dt=None):
"""Returns a dict with keys representing event_id and the values containing
data about the user rights for sessions within the event
:param user: A `User`
:param from_dt: The earliest event start time to look for
:param to_dt: The latest event start time to look for
"""
query = (user.in_session_acls
.options(load_only('session_id', 'roles', 'full_access', 'read_access'))
.options(noload('*'))
.options(contains_eager(SessionPrincipal.session).load_only('event_id'))
.join(Session)
.join(Event, Event.id == Session.event_id)
.filter(~Session.is_deleted, ~Event.is_deleted, Event.starts_between(from_dt, to_dt)))
data = defaultdict(set)
for principal in query:
roles = data[principal.session.event_id]
if 'coordinate' in principal.roles:
roles.add('session_coordinator')
if 'submit' in principal.roles:
roles.add('session_submission')
if principal.full_access:
roles.add('session_manager')
if principal.read_access:
roles.add('session_access')
return data
示例9: serialize_category_ical
def serialize_category_ical(category, user, event_filter):
"""Export the events in a category to iCal
:param category: The category to export
:param user: The user who needs to be able to access the events
:param event_filter: A SQLalchemy criterion to restrict which
events will be returned. Usually something
involving the start/end date of the event.
"""
own_room_strategy = joinedload('own_room')
own_room_strategy.load_only('building', 'floor', 'number', 'name')
own_room_strategy.lazyload('owner')
own_venue_strategy = joinedload('own_venue').load_only('name')
query = (Event.query
.filter(Event.category_chain.contains([int(category.getId())]),
~Event.is_deleted,
event_filter)
.options(load_only('id', 'start_dt', 'end_dt', 'title', 'description', 'own_venue_name',
'own_room_name', 'protection_mode'),
subqueryload('acl_entries'),
joinedload('person_links'),
own_room_strategy,
own_venue_strategy)
.order_by(Event.start_dt))
events = [e for e in query if e.can_access(user)]
cal = ical.Calendar()
cal.add('version', '2.0')
cal.add('prodid', '-//CERN//INDICO//EN')
now = now_utc(False)
for event in events:
url = url_for('event.conferenceDisplay', confId=event.id, _external=True)
location = ('{} ({})'.format(event.room_name, event.venue_name)
if event.venue_name and event.room_name
else (event.venue_name or event.room_name))
cal_event = ical.Event()
cal_event.add('uid', u'indico-event-{}@cern.ch'.format(event.id))
cal_event.add('dtstamp', now)
cal_event.add('dtstart', event.start_dt)
cal_event.add('dtend', event.end_dt)
cal_event.add('url', url)
cal_event.add('summary', event.title)
cal_event.add('location', location)
description = []
if event.person_links:
speakers = [u'{} ({})'.format(x.full_name, x.affiliation) if x.affiliation else x.full_name
for x in event.person_links]
description.append(u'Speakers: {}'.format(u', '.join(speakers)))
if event.description:
desc_text = unicode(event.description) or u'<p/>' # get rid of RichMarkup
try:
description.append(unicode(html.fromstring(desc_text).text_content()))
except ParserError:
# this happens e.g. if desc_text contains only a html comment
pass
description.append(url)
cal_event.add('description', u'\n'.join(description))
cal.add_component(cal_event)
return BytesIO(cal.to_ical())
示例10: serialize_category_atom
def serialize_category_atom(category, url, user, event_filter):
"""Export the events in a category to Atom
:param category: The category to export
:param url: The URL of the feed
:param user: The user who needs to be able to access the events
:param event_filter: A SQLalchemy criterion to restrict which
events will be returned. Usually something
involving the start/end date of the event.
"""
query = (Event.query
.filter(Event.category_chain.contains([int(category.getId())]),
~Event.is_deleted,
event_filter)
.options(load_only('id', 'start_dt', 'title', 'description', 'protection_mode'),
subqueryload('acl_entries'))
.order_by(Event.start_dt))
events = [e for e in query if e.can_access(user)]
feed = AtomFeed(feed_url=url, title='Indico Feed [{}]'.format(to_unicode(category.getTitle())))
for event in events:
feed.add(title=event.title,
summary=unicode(event.description), # get rid of RichMarkup
url=url_for('event.conferenceDisplay', confId=event.id, _external=True),
updated=event.start_dt)
return BytesIO(feed.to_string().encode('utf-8'))
示例11: monitor_api_key_limits
def monitor_api_key_limits(self):
result = {}
try:
today = util.utcnow().strftime('%Y%m%d')
keys = self.redis_client.keys('apilimit:*:' + today)
if keys:
values = self.redis_client.mget(keys)
keys = [k.split(':')[1] for k in keys]
else:
values = []
names = {}
if keys:
with self.db_session(commit=False) as session:
query = (ApiKey.querykeys(session, keys)
.options(load_only('valid_key', 'shortname')))
for api_key in query.all():
names[api_key.valid_key] = api_key.name
result = {}
for k, v in zip(keys, values):
name = names.get(k, k)
value = int(v)
result[name] = value
self.stats_client.gauge('apilimit.' + name, value)
except Exception: # pragma: no cover
# Log but ignore the exception
self.raven_client.captureException()
return result
示例12: conflict_create
def conflict_create(order_id):
"""
Renders conflict create page.
"""
order = Order.query.get(order_id)
form = CreateConflict(formdata=request.form)
form.user_connected.choices = [
(user.username, user.username) for user in User.query.options(load_only("username")).all()
]
form.user_connected.choices.append(("None", "None"))
form.user_connected.default = ("None", "None")
if request.method == "POST":
conflict = Conflict()
conflict.did_order_come = request.form.get("did_order_come") == "y"
conflict.i_know_who = request.form.get("i_know_who") == "y"
conflict.user_connected = request.form.get("user_connected")
conflict.order_connected = order.id
conflict.created_by_user = current_user.username
db.session.add(conflict)
db.session.commit()
if conflict.i_know_who:
new_conflict = Conflict.query.order_by(Conflict.date_added.desc()).first()
conflict_url = server_url() + url_for("conflict_resolve", conf_id=new_conflict.id)
msg = Message("Lunch app new conflict", recipients=[conflict.user_connected])
msg.body = (
"You were chosen as the one who ate my lunch! "
"Please use the link below to respond"
" \n\n {}".format(conflict_url)
)
mail.send(msg)
flash("Conflict created")
return redirect("my_orders")
return render_template("conflict_create.html", form=form)
示例13: get_all_report_hashes
def get_all_report_hashes(
db, date_from=None, date_to=None, opsys=None, opsys_releases=None, limit_from=None, limit_to=None
):
"""
Return ReportHash instance if there is at least one bug in database for selected date range
"""
query = db.session.query(ReportHash).join(Report).options(load_only("hash"))
if opsys and opsys != "*":
if opsys == "rhel":
opsys = "Red Hat Enterprise Linux"
query = query.join(ReportOpSysRelease).join(OpSysRelease).join(OpSys).filter(OpSys.name == opsys)
if opsys_releases and opsys_releases != "*":
query = query.filter(OpSysRelease.version == opsys_releases)
if date_from and date_from != "*":
query = query.filter(Report.last_occurrence >= date_from)
if date_to and date_to != "*":
query = query.filter(Report.last_occurrence <= date_to)
if limit_from is not None and limit_to is not None:
query = query.slice(limit_from, limit_to)
return query.all()
示例14: get_events_with_submitted_surveys
def get_events_with_submitted_surveys(user, from_dt=None, to_dt=None):
"""Gets the IDs of events where the user submitted a survey.
:param user: A `User`
:param from_dt: The earliest event start time to look for
:param to_dt: The latest event start time to look for
:return: A set of event ids
"""
event_date_filter = True
if from_dt and to_dt:
event_date_filter = IndexedEvent.start_date.between(from_dt, to_dt)
elif from_dt:
event_date_filter = IndexedEvent.start_date >= from_dt
elif to_dt:
event_date_filter = IndexedEvent.start_date <= to_dt
# Survey submissions are not stored in links anymore, so we need to get them directly
query = (
user.survey_submissions.options(load_only("survey_id"))
.options(joinedload(SurveySubmission.survey).load_only("event_id"))
.join(Survey)
.join(Event)
.join(IndexedEvent, IndexedEvent.id == Survey.event_id)
.filter(~Survey.is_deleted, ~Event.is_deleted)
.filter(event_date_filter)
)
return {submission.survey.event_id for submission in query}
示例15: validate_section_id
def validate_section_id(self, field):
session = self.get_session()
field.data = field.data if field.data > 0 else None
if field.data is None:
return
if field.data not in [x.id for x in session.query(Section).options(load_only("id")).all()]:
raise ValueError(u'Неверный раздел')