当前位置: 首页>>代码示例>>Python>>正文


Python orm.load_only函数代码示例

本文整理汇总了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)
开发者ID:phouse512,项目名称:arkaios,代码行数:28,代码来源:app.py

示例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)))
开发者ID:ThiefMaster,项目名称:indico,代码行数:31,代码来源:generate_processing_page.py

示例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())
开发者ID:gitter-badger,项目名称:acj-versus,代码行数:29,代码来源:comment.py

示例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
开发者ID:OSPK,项目名称:salink,代码行数:25,代码来源:views.py

示例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
开发者ID:VinnieJohns,项目名称:ggrc-core,代码行数:28,代码来源:query_helper.py

示例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())}
开发者ID:gitter-badger,项目名称:acj-versus,代码行数:30,代码来源:criteria.py

示例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)
开发者ID:clld,项目名称:clld,代码行数:13,代码来源:rdf.py

示例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
开发者ID:belokop,项目名称:indico_bare,代码行数:27,代码来源:util.py

示例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())
开发者ID:belokop,项目名称:indico_bare,代码行数:60,代码来源:util.py

示例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'))
开发者ID:belokop,项目名称:indico_bare,代码行数:26,代码来源:util.py

示例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
开发者ID:condemoreloer,项目名称:ichnaea,代码行数:29,代码来源:tasks.py

示例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)
开发者ID:alazaro,项目名称:lunch-app,代码行数:33,代码来源:views.py

示例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()
开发者ID:abrt,项目名称:faf,代码行数:27,代码来源:queries.py

示例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}
开发者ID:MichelCordeiro,项目名称:indico,代码行数:26,代码来源:util.py

示例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'Неверный раздел')
开发者ID:Impish-,项目名称:echoba,代码行数:7,代码来源:forms.py


注:本文中的sqlalchemy.orm.load_only函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。