Example #1
0
    def _deserialize_type(self, cstruct):
        """
        Get the type of the entity based on `cstruct`.
        """
        # Build a schema containing only the type key.
        type_schema = MappingSchema()
        type_schema[self.type_key] = self[self.type_key]
        # Assign the proper name to the subschema so that
        # Invalid exceptions contains the right hierarchy.
        type_schema.name = self.name

        return type_schema.deserialize(cstruct)[self.type_key]
Example #2
0
    def _deserialize_type(self, cstruct):
        """
        Get the type of the entity based on `cstruct`.
        """
        # Build a schema containing only the type key.
        type_schema = MappingSchema()
        type_schema[self.type_key] = self[self.type_key]
        # Assign the proper name to the subschema so that
        # Invalid exceptions contains the right hierarchy.
        type_schema.name = self.name

        return type_schema.deserialize(cstruct)[self.type_key]
Example #3
0
    def deserialize(self, cstruct=null):
        if cstruct is null:
            return null

        schema_type = self._deserialize_type(cstruct)
        subschema = self._build_schema(schema_type)
        return MappingSchema.deserialize(subschema, cstruct)
Example #4
0
    def serialize(self, appstruct=null):
        if appstruct is null:
            return null

        schema_type = appstruct[self.type_key]
        subschema = self._build_schema(schema_type)
        return MappingSchema.serialize(subschema, appstruct)
Example #5
0
    def serialize(self, appstruct=null):
        if appstruct is null:
            return null

        schema_type = appstruct[self.type_key]
        subschema = self._build_schema(schema_type)
        return MappingSchema.serialize(subschema, appstruct)
Example #6
0
    def deserialize(self, cstruct=null):
        if cstruct is null:
            return null

        schema_type = self._deserialize_type(cstruct)
        subschema = self._build_schema(schema_type)
        return MappingSchema.deserialize(subschema, cstruct)
Example #7
0
def Vyucujuci(**kwargs):
  schema = MappingSchema(**kwargs)
  schema.add(SchemaNode(Integer(),
    name='osoba',
    title=u'Osoba',
    widget=widgets.RemoteSelect2Widget(
      search_url=url_for('osoba.search', _external=True),
      item_url=url_for('osoba.get', _external=True),
      template="osoba"
    )
  ))
  schema.add(SchemaNode(Set(),
    name='typy',
    title=u'Typy',
    widget=deform.widget.CheckboxChoiceWidget(values=[(x[0], x[1]) for x in g.db.load_typy_vyucujuceho(iba_povolene=True)])
  ))
  return schema
Example #8
0
def _validate_dict_schema(schema: MappingSchema, cstruct: dict,
                          request: Request, location='body'):
    validated = {}
    try:
        validated = schema.deserialize(cstruct)
    except Invalid as err:
        for child in err.children:
            _add_colander_invalid_error_to_request(child, request, location)
    request.validated.update(validated)
Example #9
0
 def test_set_other(self, meta, context, registry, mock_workflow):
     from colander import MappingSchema
     registry.content.get_workflow.return_value = mock_workflow
     inst = meta.sheet_class(meta, context, registry=registry)
     inst.schema = inst.schema.clone()
     inst.schema.add(MappingSchema(name='other'))
     inst.set({'other': {}})
     appstruct = getattr(context, inst._annotation_key)
     assert 'other' in appstruct
Example #10
0
def OdporucanaLiteratura(**kwargs):
  schema = MappingSchema(**kwargs)
  schema.add(SchemaNode(Sequence(),
    SchemaNode(Integer(),
      name='literatura',
      title=u'Literatúra z knižného fondu',
      widget=widgets.RemoteSelect2Widget(
        search_url=url_for('.literatura_search', _external=True),
        item_url=url_for('.literatura_get', _external=True),
        template="literatura"
      )
    ),
    name='zoznam',
    title=u'Literatúra z knižného fondu',
    description=u'''Písaním do boxu sa spustí vyhľadávanie knihy v aktuálnom
      knižnom fonde. Ak sa kniha nenájde, musíte ju pridať do položky
      "Nová literatúra"''',
    widget=deform.widget.SequenceWidget(orderable=True),
    validator=DuplicitnyValidator(None,
      u'''Literatúra sa už v zozname nachádza, prosím zadajte ju iba raz''')
  ))
  schema.add(SchemaNode(Sequence(),
    SchemaNode(String(),
      name='bibl',
      title=u'Nová literatúra',
      widget=deform.widget.AutocompleteInputWidget(min_length=1,
        values=url_for('.nova_literatura_search', _external=True)
      )
    ),
    name='nove',
    title=u'Nová literatúra',
    description=Markup(u'''<p>Pozor, literatúru musíme byť schopní zabezpečiť!</p>
      <p>Napríklad:</p>
      <ul>
        <li>Propedeutika astrológie / Jozef Mrkvička, František Hruška. Springer, 2012</li>
        <li>Vlastné elektronické texty vyučujúceho predmetu zverejňované
          prostredníctvom web stránky predmetu.</li>
        <li>Výber aktuálnych článkov z oblasti.</li>
      </ul>'''),
    widget=deform.widget.SequenceWidget(orderable=True)
  ))
  return schema
Example #11
0
def _validate_dict_schema(schema: MappingSchema,
                          cstruct: dict,
                          request: Request,
                          location='body'):
    validated = {}
    try:
        validated = schema.deserialize(cstruct)
    except Invalid as err:
        for child in err.children:
            _add_colander_invalid_error_to_request(child, request, location)
        if not err.children:
            _add_colander_invalid_error_to_request(err, request, location)
    request.validated.update(validated)
Example #12
0
        def test_only_mapping_is_accepted(self):
            schema = CorniceSchema.from_colander(WrongSchema)
            dummy_request = get_mock_request('', {
                'foo': 'test',
                'bar': 'test'
            })
            self.assertRaises(SchemaError, validate_colander_schema, schema,
                              dummy_request)

            # We shouldn't accept a MappingSchema if the `typ` has
            #  been set to something else:
            schema = CorniceSchema.from_colander(
                MappingSchema(Sequence, SchemaNode(String(), name='foo'),
                              SchemaNode(String(), name='bar'),
                              SchemaNode(String(), name='baz')))
            self.assertRaises(SchemaError, validate_colander_schema, schema,
                              dummy_request)
Example #13
0
def VzdelavaciaCinnost(**kwargs):
  schema = MappingSchema(**kwargs)
  schema.add(SchemaNode(String(),
    name='druh_cinnosti',
    title=u'Druh činnosti',
    widget=deform.widget.Select2Widget(values=g.db.load_druhy_cinnosti())
  ))
  schema.add(SchemaNode(Integer(),
    name='pocet_hodin',
    title=u'Počet hodín'
  ))
  schema.add(SchemaNode(String(),
    name='za_obdobie',
    title=u'Za obdobie',
    widget=deform.widget.Select2Widget(values=(('T', 'týždeň'), ('S', 'semester'))),
    description=u'Obdobie "za semester" sa používa len výnimočne v prípade, že sa príslušná činnosť vykonáva blokovo (napr. "prax" 30 hodín)'
  ))
  schema.add(SchemaNode(String(),
    name='metoda_vyucby',
    title=u'Metóda výučby',
    widget=deform.widget.Select2Widget(values=(('P', 'prezenčná'), ('D', 'dištančná'), ('K', 'kombinovaná')))
  ))
  return schema
Example #14
0
def validate_request_data(context: ILocation,
                          request: Request,
                          schema=MappingSchema(),
                          extra_validators=[]):
    """ Validate request data.

    :param context: passed to validator functions
    :param request: passed to validator functions
    :param schema: Schema to validate. Data to validate is extracted from the
                   request.body. For schema nodes with attribute `location` ==
                   `querystring` the data is extracted from the query string.
                   The validated data (dict or list) is stored in the
                   `request.validated` attribute.
                   The `None` value is allowed to disable schema validation.
    :param extra_validators: Functions called after schema validation.
                             The passed arguments are `context` and  `request`.
                             The should append errors to `request.errors` and
                             validated data to `request.validated`.

    :raises HTTPBadRequest: HTTP 400 for bad request data.
    """
    parent = context if request.method == 'POST' else context.__parent__
    workflow = _get_workflow(context, request)
    schema_with_binding = schema.bind(context=context,
                                      request=request,
                                      registry=request.registry,
                                      workflow=workflow,
                                      parent_pool=parent)
    body = {}
    if request.content_type == 'multipart/form-data':
        body = unflatten_multipart_request(request)
    if request.content_type == 'application/json':
        body = _extract_json_body(request)
    validate_user_headers(request)
    qs = _extract_querystring(request)
    validate_body_or_querystring(body, qs, schema_with_binding, context,
                                 request)
    _validate_extra_validators(extra_validators, context, request)
    if request.errors:
        request.validated = {}
        raise HTTPBadRequest()
Example #15
0
 def deserialize(self, cstruct):
     if 'field' in cstruct and not isinstance(cstruct['field'], list):
         cstruct['field'] = [cstruct['field']]
     return MappingSchema.deserialize(self, cstruct)
Example #16
0
        def deserialize(self, cstruct):
            if 'body' in cstruct and cstruct['body'] == b'hello,open,yeah':
                values = cstruct['body'].decode().split(',')
                cstruct['body'] = dict(zip(['foo', 'bar', 'yeah'], values))

            return MappingSchema.deserialize(self, cstruct)
Example #17
0
 def schema_type():
     return MappingSchema.schema_type(unknown='raise')
Example #18
0
 def schema_type():
     return MappingSchema.schema_type(unknown='raise')
Example #19
0
 def deserialize(self, cstruct):
     if 'field' in cstruct and not isinstance(cstruct['field'], list):
         cstruct['field'] = [cstruct['field']]
     return MappingSchema.deserialize(self, cstruct)
Example #20
0
        def deserialize(self, cstruct):
            if 'body' in cstruct and cstruct['body'] == b'hello,open,yeah':
                values = cstruct['body'].decode().split(',')
                cstruct['body'] = dict(zip(['foo', 'bar', 'yeah'], values))

            return MappingSchema.deserialize(self, cstruct)
Example #21
0
def Infolist(infolist):
  schema = MappingSchema(warning_validator=bude_v_povinnom_validator)
  schema.add(SchemaNode(String(),
    name='fakulta',
    title=u'Fakulta',
    widget=deform.widget.Select2Widget(values=g.db.load_fakulty()),
    description=u'Uvádza sa názov fakulty, ktorá predmet personálne a materiálne zabezpečuje'
  ))
  for lang in current_app.config['LANGUAGES']:
    kwargs = {}
    if lang != current_app.config['DEFAULT_LANG']:
      kwargs['missing'] = u''
    schema.add(SchemaNode(String(),
      name='nazov_predmetu__{}'.format(lang),
      title=u'Názov predmetu ({})'.format(lang),
      **kwargs
    ))
  schema.add(SchemaNode(String(),
    name='povodny_kod_predmetu',
    title=u'Kód predmetu',
    description=u'Kódy predmetov budu priradené centrálne',
    missing=colander.null
  ))
  schema.add(SchemaNode(Bool(),
    name='treba_zmenit_kod',
    title=u'Ide o výraznú zmenu, žiadame priradiť predmetu nový kód'
  ))
  schema.add(SchemaNode(Bool(),
    name='bude_v_povinnom',
    title=u'Tento predmet bude zaradený ako povinný alebo povinne voliteľný v niektorom študijnom programe'
  ))
  schema.add(SchemaNode(Sequence(),
    VzdelavaciaCinnost(
      name='vzdelavacia_cinnost',
      title=u'Činnosť'
    ),
    name='cinnosti',
    title=u'Druh, rozsah a metóda vzdelávacích činností',
    description=u'''Ak má predmet prednášky a cvičenia, treba vyplniť dva bloky
      s príslušnými rozsahmi'''
  ))
  schema.add(SchemaNode(Integer(),
    name='pocet_kreditov',
    title=u'Počet kreditov',
    description=Markup(u'''<p>Kreditová hodnota predmetu nezávisí na programe,
      v ktorom sa jeho absolvovanie hodnotí. 1 kredit zodpovedá 25-30 hodinám
      práce študenta. Táto hodnota zahŕňa časovú náročnosť priamej výučby
      (počas 13 týždňov), samostatného štúdia, domácich úloh a projektov,
      ako aj prípravy na skúšku.</p><p>Bližšie pokyny k tvorbe študijných programov:</p><ul class="help-block"><li>FMFI: <a href="https://sluzby.fmph.uniba.sk/ka/dokumenty/pravidla/pravidla-tvorby-studijnych-programov.docx">https://sluzby.fmph.uniba.sk/ka/dokumenty/pravidla/pravidla-tvorby-studijnych-programov.docx</a></li></ul>'''),
    missing=colander.null,
    warn_if_missing=True
  ))
  schema.add(SchemaNode(String(),
    name='predpokladany_semester',
    title=u'Predpokladaný semester výučby',
    widget=deform.widget.Select2Widget(values=(('', ''), ('Z', 'zimný'), ('L', 'letný'), ('N', 'neurčený')), placeholder=u'Vyberte semester'),
    missing=colander.null,
    warn_if_missing=True
  ))
  schema.add(SchemaNode(String(),
    name='predpokladany_stupen_studia',
    title=u'Predpokladaný stupeň štúdia',
    widget=deform.widget.Select2Widget(
      values=(('', ''), ('1.', '1.'), ('2.', '2.'), ('3.', '3.')),
      placeholder=u'Vyberte stupeň štúdia'
    ),
    missing=colander.null,
    warn_if_missing=True
  ))
  schema.add(SchemaNode(widgets.PodmienkaTyp(),
    name='podmienujuce_predmety',
    title=u'Podmieňujúce predmety',
    missing=Podmienka(''),
    widget=widgets.PodmienkaWidget(),
    description=Markup(u'''Uvádzajú sa predmety, ktoré študent musí riadne absolvovať,
      aby si mohol zapísať tento predmet. <strong>Podmieňujúce predmety by mali
      byť splniteľné v rámci študijného programu.</strong> Nemali by ísť napr.
      medzi bakalárskym a magisterským štúdiom alebo medzi rôznymi študijnými
      programami. Ak chcete vyjadriť obsahovú nadväznosť medzi bakalárskym a
      magisterským programom, využite kolonku Odporúčané predmety.
      Napríklad: "(1-INF-123 alebo 1-INF-234) a 1-INF-456".
      Kódy budú automaticky preklopené na nové priradené kódy.''')
  ))
  schema.add(SchemaNode(widgets.PodmienkaTyp(),
    name='odporucane_predmety',
    title=u'Odporúčané predmety',
    missing=Podmienka(''),
    widget=widgets.PodmienkaWidget(),
    description=u'Napríklad: "(1-INF-123 alebo 1-INF-234) a 1-INF-456". Kódy budú automaticky preklopené na nové priradené kódy.'
  ))
  schema.add(SchemaNode(widgets.PodmienkaTyp(),
    name='vylucujuce_predmety',
    title=u'Vylučujúce predmety',
    missing=Podmienka(''),
    widget=widgets.PodmienkaWidget(),
    description=u'Napríklad: "1-INF-123 alebo 1-INF-456". Kódy budú automaticky preklopené na nové priradené kódy.'
  ))
  schema.add(PodmienkyAbsolvovania(
    infolist.get('podm_absolvovania', {}),
    name='podm_absolvovania',
    title=u'Podmienky absolvovania predmetu'
  ))
  for lang in current_app.config['LANGUAGES']:
    schema.add(SchemaNode(String(),
      name='vysledky_vzdelavania__{}'.format(lang),
      title=u'Výsledky vzdelávania ({})'.format(lang),
      description=Markup(u'''Výsledky vzdelávania určujú, <strong>aké znalosti alebo schopnosti študenti
        budú mať po absolvovaní tohto predmetu</strong>. Môžu sa týkať obsahových
        znalostí (po absolvovaní predmetu študenti budú vedieť kategorizovať
        makroekonomické stratégie na základe ekonomických teórií, z ktorých
        tieto stratégie vychádzajú), schopností (po absolvovaní predmetu
        študenti budú schopní počítať jednoduché derivácie), alebo hodnôt a
        všeobecných schopností (po absolvovaní predmetu budú študenti schopní
        spolupracovať v rámci malých tímov). <strong>Formulácia typu "oboznámiť
        študentov s ..." nie je v tomto kontexte vhodná.</strong>'''),
      widget=deform.widget.TextAreaWidget(rows=5),
      missing=colander.null,
      warn_if_missing=(lang == current_app.config['DEFAULT_LANG'])
    ))
  for lang in current_app.config['LANGUAGES']:
    schema.add(SchemaNode(String(),
      name='strucna_osnova__{}'.format(lang),
      title=u'Stručná osnova predmetu ({})'.format(lang),
      description=u'''Osnova predmetu určuje postupnosť obsahových tém,
        ktoré budú v rámci predmetu preberané. Text zbytočne neštrukturujte
        (ideálne vymenujte postupnosť tém v rámci jedného odstavca).''',
      widget=deform.widget.TextAreaWidget(rows=5),
      missing=colander.null,
      warn_if_missing=(lang == current_app.config['DEFAULT_LANG'])
    ))
  schema.add(OdporucanaLiteratura(
    name='odporucana_literatura',
    title=u'Odporúčaná literatúra',
    description=Markup(u'''<p>Akreditačná komisia bude hodnotiť, ako dobre je pokrytá odporúčaná
      študijná literatúra v rámci prezenčného fondu knižnice. Preto v rámci
      odporúčanej literatúry k predmetu:</p>
      <ol style="list-style-type: lower-alpha">
        <li>Uvádzajte knihy, ktoré slúžia ako <strong>hlavný zdroj</strong>
          informácií pre študentov (spravidla 1-3). Ďalšie zdroje možno
          študentom odporučiť napr. pomocou web stránky predmetu.</li>
        <li>Vyberajte pokiaľ možno zo zoznamu literatúry, ktorá je v
          súčasnosti k dispozícii v knižnom fonde.</li>
        <li>V žiadnom prípade <strong>neuvádzajte literatúru, ktorú nie je
          možné zohnať</strong>.</li>
      </ol>''')
  ))
  schema.add(SchemaNode(String(),
    name='potrebny_jazyk',
    title=u'Jazyk, ktorého znalosť je potrebná na absolvovanie predmetu',
    widget=deform.widget.Select2Widget(values=[(x[0], x[1]) for x in g.db.load_jazyky_vyucby()])
  ))
  schema.add(SchemaNode(Sequence(),
    Vyucujuci(name='vyucujuci', title=u'Vyučujúci'),
    name='vyucujuci',
    title=u'Vyučujúci',
    descrption=Markup(u'''<p><strong>Ak je predmet zaradený v niektorom
      študijnom programe ako povinný alebo povinne voliteľný, musí prvý z
      uvedených vyučujúcich byť profesor alebo docent.</strong>
      V prípade, že sa požadovaný vyučujúci nenachádza v
      zozname, prosím kontaktujte nás (potrebujeme meno, priezvisko a tituly
      vyučujúceho).</p>'''),
    widget=deform.widget.SequenceWidget(orderable=True),
    validator=DuplicitnyValidator('osoba',
      u'''Vyučujúci sa už v zozname nachádza, prosím zadajte ho iba raz''')
  ))
  schema.add(SchemaNode(Bool(),
    name='finalna_verzia',
    title=u'Táto verzia je finálna a dá sa použiť do akreditačného spisu'
  ))
  return schema
Example #22
0
def PodmienkyAbsolvovania(podm_absolvovania, **kwargs):
  schema = MappingSchema(**kwargs)
  nahrada = podm_absolvovania.get('nahrada__sk')
  if g.user.moze_pridat_nahradu_hodnotenia() or not nahrada:
    for lang in current_app.config['LANGUAGES']:
      schema.add(SchemaNode(String(),
        name='priebezne__{}'.format(lang),
        title=u'Spôsob priebežného hodnotenia ({})'.format(lang),
        description=u'Napríklad: domáce úlohy, písomka',
        missing=''
      ))
    schema.add(SchemaNode(Integer(),
      name='percenta_zapocet',
      title=u'Percentá na pripustenie ku skúške',
      description=u'Zobrazí vetu "Na pripustenie ku skúške je potrebných aspoň X% bodov z priebežného hodnotenia." Ak túto vetu nechcete zobraziť, ponechajte pole prázdne.',
      missing=colander.null,
    ))
    for lang in current_app.config['LANGUAGES']:
      schema.add(SchemaNode(String(),
        name='skuska__{}'.format(lang),
        title=u'Forma skúšky ({})'.format(lang),
        description=u'Napríklad: písomná, ústna; nevyplňovať ak predmet nemá skúšku',
        missing=''
      ))
    schema.add(SchemaNode(Integer(),
      name='percenta_skuska',
      title=u'Váha skúšky v hodnotení (%)',
      description=u'''Napríklad ak predmet nemá skúšku, váha skúšky bude 0.
        Ak predmet nemá priebežné hodnotenie, váha skúšky bude 100.''',
      missing=0
    ))
    percenta_na = MappingSchema(
      name='percenta_na',
      title=u'Stupnica hodnotenia'
    )
    schema.add(percenta_na)
    for i, x in enumerate(['A', 'B', 'C', 'D', 'E']):
      percenta_na.add(SchemaNode(Integer(),
        name=x,
        title=u'Minimálna hranica na {} (%)'.format(x),
        default=(90 - i * 10)
      ))
    schema.add(SchemaNode(Bool(),
      name='nepouzivat_stupnicu',
      title=u'Nepoužívať stupnicu hodnotenia',
      description=u'''Napríklad pri štátnicových predmetoch. Predmety ktoré
        majú vyplnený nejaký druh vzdelávacej činnosti musia používať stupnicu hodnotenia.''',
    ))
  if g.user.moze_pridat_nahradu_hodnotenia() or nahrada:
    for lang in current_app.config['LANGUAGES']:
      kwargs = {}
      if g.user.moze_pridat_nahradu_hodnotenia() or lang != current_app.config['DEFAULT_LANG']:
        kwargs['missing'] = colander.null
      schema.add(SchemaNode(String(),
        name='nahrada__{}'.format(lang),
        title=u'Podmienky absolvovania predmetu (náhradný textový obsah - {})'.format(lang),
        widget=deform.widget.TextAreaWidget(rows=5),
        **kwargs
      ))
  return schema
Example #23
0
 class ASchema(MappingSchema):
     field1 = MappingSchema()