Пример #1
0
def userdata_doctype_view(userdata_model, request):
    """
    View used to register doctypes status

        userdata_model

            The UserDatas model retrieved through traversal
    """
    if 'submit' in request.params:
        schema = get_doctypes_form_schema(userdata_model)[0]
        appstruct = request.POST.items()
        appstruct = peppercorn.parse(appstruct)
        try:
            appstruct = schema.deserialize(appstruct)
        except colander.Invalid:
            logger.exception("Error while validating doctype registration")
        else:
            node_schema = SQLAlchemySchemaNode(UserDatasSocialDocTypes)
            for data in appstruct.values():
                model = node_schema.objectify(data)
                request.dbsession.merge(model)
            request.session.flash(
                u"Les informations saisies ont bien été enregistrées")

    return HTTPFound(request.route_path('userdata', id=userdata_model.id))
Пример #2
0
def vote_view(context, request):
    logged_in = authenticated_userid(request)
    schema = BallotSchema().clone()
    _add_category_schema(context, request, schema)
    form = Form(schema, buttons=("submit",))
    css_resources, js_resources = _form_resources(form)
    if "submit" in request.POST:
        controls = request.POST.items()
        try:
            form.validate(controls)
        except (ValidationFailure,), e:
            # Put the team names back in place
            cstruct = e.cstruct
            for vote in cstruct["votes"]:
                team_id = vote["team_hidden"]
                team_obj = context["teams"][team_id]
                team_title = team_obj.title
                team_descrip = team_obj.description
                vote["team_title"] = team_title
                vote["team_members"] = ", ".join(team_obj.member_names())
                vote["team_description"] = team_descrip
            return {
                "form": e.render(),
                "css_resources": css_resources,
                "js_resources": js_resources,
                "logged_in": logged_in,
            }
        results = parse(request.params.items())["votes"]
        context.results[logged_in] = results
        context._p_changed = True
        return HTTPFound(location=request.resource_url(context))
Пример #3
0
    def __call__(self):
        schema = BusinessTypeMentionEntries().bind(request=self.request)
        if 'submit' in self.request.params:
            controls = self.request.params.items()
            values = peppercorn.parse(controls)
            logger.debug(values)
            try:
                appstruct = schema.deserialize(values)
            except colander.Invalid:
                logger.exception(u"Error while validating association datas")
                self.request.session.flash(
                    u"Une erreur est survenue, veuillez "
                    u"contacter votre administrateur",
                    'error',
                )
            else:
                for datas in appstruct['items']:
                    mandatory = datas.get('mandatory')
                    if mandatory is not None:
                        # Facultatif ou obligatoire : on retrouve ou on crée
                        obj = self._find_item(datas, create=True)
                        obj.mandatory = mandatory == 'true'
                        self.request.dbsession.merge(obj)
                    else:
                        # Non utilisé : on supprime l'éventuel existant
                        obj = self._find_item(datas)
                        if obj is not None:
                            self.request.dbsession.delete(obj)
                self.request.session.flash(
                    u"Vos modifications ont été enregistrées"
                )

        return HTTPFound(self.request.current_route_path())
Пример #4
0
def edit_team(context, request):
    logged_in = authenticated_userid(request)
    schema = TeamSchema().bind(request=request)
    form = Form(schema, buttons=("submit",))
    css_resources, js_resources = _form_resources(form)
    if "submit" in request.POST:
        controls = request.POST.items()
        try:
            form.validate(controls)
        except (ValidationFailure,), e:
            return {
                "form": e.render(),
                "css_resources": css_resources,
                "js_resources": js_resources,
                "logged_in": logged_in,
            }
        params = parse(controls)
        context.title = params["title"]
        context.description = params["description"]
        leader = params["leader"]
        context.leader = leader
        members = params["members"]
        # Add the leader if they didn't add themselves
        if leader and leader not in members:
            members.append(leader)
        context.members = members
        # TODO: use find by interface here
        voting_booth = context.__parent__.__parent__
        return HTTPFound(location=request.resource_url(voting_booth))
Пример #5
0
def add_profile(context, request):
    logged_in = authenticated_userid(request)
    schema = ProfileAddSchema()
    form = Form(schema, buttons=("submit",))
    css_resources, js_resources = _form_resources(form)
    if "submit" in request.POST:
        controls = request.POST.items()
        try:
            form.validate(controls)
        except (ValidationFailure,), e:
            return {
                "form": e.render(),
                "css_resources": css_resources,
                "js_resources": js_resources,
                "logged_in": logged_in,
            }
        params = parse(controls)
        first_name = params["first_name"]
        last_name = params["last_name"]
        username = params["username"]
        email = params["email"]
        password = params["password"]["value"]
        # Create the profile
        profile = Profile(first_name=first_name, last_name=last_name, username=username, email=email)
        # Add the profile object
        profile.__parent__ = context["profiles"]
        profile.__name__ = username
        context["profiles"].add_profile(profile)
        # Add the user object
        user_folder = context["users"]
        user_folder.add(username, username, password)
        return HTTPFound(location=request.resource_url(context.__parent__))
Пример #6
0
    def sa_add(self):
        action = self.request.matched_route.name
        bc = breadcrumbs(self.tname, get_table_verbose_name(self.table),
                         action, self.pk)
        dbsession = self.request.dbsession
        try:
            obj = get_obj(dbsession, self.table, self.pk)
        except (NoResultFound, KeyError):
            raise HTTPNotFound
        form = SacrudForm(obj=obj, dbsession=dbsession,
                          request=self.request, table=self.table)()

        def options_for_response(form):
            return dict(
                form=form.render(), pk=self.pk, obj=obj, breadcrumbs=bc
            )

        if 'form.submitted' in self.request.params:
            controls = self.request.POST.items()
            pstruct = peppercorn.parse(controls)

            if '__formid__' in pstruct:
                try:
                    deserialized = form.validate_pstruct(pstruct).values()
                except deform.ValidationFailure as e:
                    return options_for_response(e)
                data = {k: preprocessing_value(v)
                        for d in deserialized
                        for k, v in d.items()}
            else:
                # if not peppercon format
                data = pstruct

            try:
                if action == PYRAMID_SACRUD_UPDATE:
                    obj = self.crud.update(self.pk, data)
                    flash_action = 'updated'
                else:
                    obj = self.crud.create(data)
                    flash_action = 'created'
                name = obj.__repr__()
                dbsession.flush()
            except SacrudMessagedException as e:
                self.flash_message(e.message, status=e.status)
                return self.get_response(options_for_response(form),
                                         SACRUD_EDIT_TEMPLATE)
            except Exception as e:
                transaction.abort()
                logging.exception("Something awful happened!")
                raise e
            transaction.commit()
            self.flash_message(_ps(
                u"You ${action} object of ${name}",
                mapping={'action': flash_action, 'name': escape(name or '')}
            ))
            return HTTPFound(
                location=self.request.route_url(PYRAMID_SACRUD_LIST,
                                                table=self.tname))
        return self.get_response(options_for_response(form),
                                 SACRUD_EDIT_TEMPLATE)
Пример #7
0
def add_team(context, request):
    logged_in = authenticated_userid(request)
    schema = TeamSchema().bind(request=request)
    form = Form(schema, buttons=("submit",))
    css_resources, js_resources = _form_resources(form)
    if "submit" in request.POST:
        controls = request.POST.items()
        try:
            form.validate(controls)
        except (ValidationFailure,), e:
            return {
                "form": e.render(),
                "css_resources": css_resources,
                "js_resources": js_resources,
                "logged_in": logged_in,
            }
        params = parse(controls)
        leader = params["leader"]
        members = params["members"]
        # Add the leader if they didn't add themselves
        if leader and leader not in members:
            members.append(leader)
        team = Team(title=params["title"], description=params["description"], members=members, leader=leader)
        team.__parent__ = context
        context.add_team(team)
        return HTTPFound(location=request.resource_url(context.__parent__))
Пример #8
0
 def __call__(self):
     appstruct = parse(self.request.POST.items())
     appstruct.pop('csrf_token', None)
     method = appstruct.pop('method', None)
     response = {}
     if method == 'add':
         principal = appstruct['principal']
         if principal.startswith('group:'):
             if principal in self.root['groups']:
                 self.context.local_roles[principal] = appstruct['roles']
             else:
                 response['errors'] = {
                     'principal': _("That GroupID don't exist")
                 }
         else:
             if principal in self.root['users']:
                 self.context.local_roles[principal] = appstruct['roles']
             else:
                 response['errors'] = {
                     'principal': _("That UserID don't exist")
                 }
     elif method == 'set':
         self.context.local_roles = appstruct
         #Validate, return a proper response
     else:
         pass
         #response['errors']?
     response['principals'] = self.get_principals()
     return response
Пример #9
0
def add_voting_booth(context, request):
    logged_in = authenticated_userid(request)
    schema = VotingBoothSchema()
    form = Form(schema, buttons=("submit",))
    css_resources, js_resources = _form_resources(form)
    if "submit" in request.POST:
        controls = request.POST.items()
        try:
            form.validate(controls)
        except (ValidationFailure,), e:
            return {
                "form": e.render(),
                "css_resources": css_resources,
                "js_resources": js_resources,
                "logged_in": logged_in,
            }
        values = parse(request.params.items())
        start, end = _process_dates(values)
        voting_booth = VotingBooth(title=values["title"], start=start, end=end, categories=values["categories"])
        voting_booth.__parent__ = context
        # maybe this should be done in the team add view?
        team_folder = TeamFolder()
        team_folder.__parent__ = voting_booth
        team_folder.__name__ = "teams"
        voting_booth["teams"] = team_folder
        context.add_booth(voting_booth)
        return HTTPFound(location=request.resource_url(voting_booth))
Пример #10
0
def record_attendances_view(context, request):
    """
    Record attendances for the given context (workshop)

    Special Note : Since we need a special layout in the form (with tabs and
        lines with the username as header, we can't render it with deform.  We
        use peppercorn's parser and we build an appropriate form in the template
    """
    schema = AttendanceSchema().bind(request=request)
    if 'submit' in request.params:
        controls = request.params.items()
        values = peppercorn.parse(controls)
        try:
            appstruct = schema.deserialize(values)
        except colander.Invalid as e:
            log.error(u"Error while validating workshop attendance")
            log.error(e)
        else:
            for datas in appstruct['attendances']:
                account_id = datas['account_id']
                timeslot_id = datas['timeslot_id']
                obj = Attendance.get((account_id, timeslot_id))
                obj.status = datas['status']
                request.dbsession.merge(obj)
            request.session.flash(u"L'émargement a bien été enregistré")

    url = request.route_path(
        'workshop',
        id=context.id,
        _query=dict(action="edit"),
    )

    return HTTPFound(url)
Пример #11
0
def userdata_doctype_view(userdata_model, request):
    """
    View used to register doctypes status

        userdata_model

            The UserDatas model retrieved through traversal
    """
    if 'submit' in request.params:
        schema = get_doctypes_form_schema(userdata_model)[0]
        appstruct = request.POST.items()
        appstruct = peppercorn.parse(appstruct)
        try:
            appstruct = schema.deserialize(appstruct)
        except colander.Invalid:
            logger.exception(
                "Error while validating doctype registration"
            )
        else:
            node_schema = SQLAlchemySchemaNode(UserDatasSocialDocTypes)
            for data in appstruct.values():
                model = node_schema.objectify(data)
                request.dbsession.merge(model)
            request.session.flash(
                u"Les informations saisies ont bien été enregistrées"
            )

    return HTTPFound(
        request.route_path('userdata', id=userdata_model.id)
    )
Пример #12
0
 def __call__(self):
     appstruct = parse(self.request.POST.items())
     appstruct.pop('csrf_token', None)
     method = appstruct.pop('method', None)
     response = {}
     if method == 'add':
         principal = appstruct['principal']
         if principal.startswith('group:'):
             if principal in self.root['groups']:
                 self.context.local_roles[principal] = appstruct['roles']
             else:
                 response['errors'] = {'principal': _("That GroupID don't exist")}
         else:
             if principal in self.root['users']:
                 self.context.local_roles[principal] = appstruct['roles']
             else:
                 response['errors'] = {'principal': _("That UserID don't exist")}
     elif method == 'set':
         self.context.local_roles = appstruct
         #Validate, return a proper response
     else:
         pass
         #response['errors']?
     response['principals'] = self.get_principals()
     return response
Пример #13
0
    def __call__(self):
        schema = BusinessTypeMentionEntries().bind(request=self.request)
        if 'submit' in self.request.params:
            controls = self.request.params.items()
            values = peppercorn.parse(controls)
            logger.debug(values)
            try:
                appstruct = schema.deserialize(values)
            except colander.Invalid:
                logger.exception(u"Error while validating association datas")
                self.request.session.flash(
                    u"Une erreur est survenue, veuillez "
                    u"contacter votre administrateur",
                    'error',
                )
            else:
                for datas in appstruct['items']:
                    mandatory = datas.get('mandatory')
                    if mandatory is not None:
                        # Facultatif ou obligatoire : on retrouve ou on crée
                        obj = self._find_item(datas, create=True)
                        obj.mandatory = mandatory == 'true'
                        self.request.dbsession.merge(obj)
                    else:
                        # Non utilisé : on supprime l'éventuel existant
                        obj = self._find_item(datas)
                        if obj is not None:
                            self.request.dbsession.delete(obj)
                self.request.session.flash(
                    u"Vos modifications ont été enregistrées")

        return HTTPFound(self.request.current_route_path())
Пример #14
0
def record_attendances_view(context, request):
    """
    Record attendances for the given context (workshop)

    Special Note : Since we need a special layout in the form (with tabs and
        lines with the username as header, we can't render it with deform.  We
        use peppercorn's parser and we build an appropriate form in the template
    """
    schema = AttendanceSchema().bind(request=request)
    if 'submit' in request.params:
        controls = request.params.items()
        values = peppercorn.parse(controls)
        try:
            appstruct = schema.deserialize(values)
        except colander.Invalid as e:
            log.error(u"Error while validating workshop attendance")
            log.error(e)
        else:
            for datas in appstruct['attendances']:
                account_id = datas['account_id']
                timeslot_id = datas['timeslot_id']
                obj = Attendance.get((account_id, timeslot_id))
                obj.status = datas['status']
                request.dbsession.merge(obj)
            request.session.flash(u"L'émargement a bien été enregistré")

    url = request.route_path(
        'workshop',
        id=context.id,
        _query=dict(action="edit"),
        )

    return HTTPFound(url)
Пример #15
0
 def add_featured_links(self, request, zip_file, save_dir):
     structure = peppercorn.parse(request.POST.items())
     if structure.has_key('featuredlinks'):
         featuredlinks = build_featured_links(structure)
         if featuredlinks:
             cnxml = get_cnxml_from_zipfile(zip_file)
             new_cnxml = add_featuredlinks_to_cnxml(cnxml, featuredlinks)
             files = get_files_from_zipfile(zip_file)
             save_cnxml(save_dir, new_cnxml, files)
     return featuredlinks
Пример #16
0
 def set_data(self, struct=None, obj=None, **kwargs):
     tmp_struct = {}
     for field in self.field_names():
         if field in struct:
             tmp_struct[field] = copy.deepcopy(struct[field])
         elif hasattr(obj, field):
             tmp_struct[field] = copy.deepcopy(getattr(obj, field))
         elif field in kwargs:
             tmp_struct[field] = copy.deepcopy(kwargs[field])
     self.untrusted_data = peppercorn.parse(tmp_struct.items())
 def add_featured_links(self, request, zip_file, save_dir):
     structure = peppercorn.parse(request.POST.items())
     if structure.has_key('featuredlinks'):
         featuredlinks = build_featured_links(structure)
         if featuredlinks:
             cnxml = get_cnxml_from_zipfile(zip_file)
             new_cnxml = add_featuredlinks_to_cnxml(cnxml,
                                                    featuredlinks)
             files = get_files_from_zipfile(zip_file)
             save_cnxml(save_dir, new_cnxml, files)
     return featuredlinks
Пример #18
0
    def edit_form_post_view(self):
        form = self.context.form(self.request)
        params = {'form': form.render()}

        def get_reponse(form=None):
            if form:
                params['form'] = form
            return render_to_response(self.context.renderer,
                                      params,
                                      request=self.request)

        if 'form.submitted' in self.request.params:
            controls = self.request.POST.items()
            pstruct = peppercorn.parse(controls)

            # Validate form
            try:
                deserialized = form.validate_pstruct(pstruct).values()
            except deform.ValidationFailure as e:
                return get_reponse(e.render())
            data = {
                k: preprocessing_value(k, v, form)  # TODO: optimize it
                for d in deserialized for k, v in d.items()
            }

            # Update object
            try:
                if self.context.obj:
                    obj = self.context.crud._add(self.context.obj, data)
                    flash_action = 'updated'
                else:
                    obj = self.context.crud.create(data)
                    flash_action = 'created'
                name = obj.__repr__()
                self.context.dbsession.flush()
            except SacrudException as e:
                self.flash_message(e.message, status=e.status)
                return get_reponse()
            except Exception as e:
                self.abort()
                logging.exception("Something awful happened!")
                raise e

            self.commit()

            # Make response
            self.flash_message(
                _ps(u"You ${action} object of ${name}",
                    mapping={
                        'action': flash_action,
                        'name': escape(name or '')
                    }))
            return self.list_view_response()
        return get_reponse()
Пример #19
0
    def from_request(self):
        """
        my_form = my_form.from_request(request)
        Pyramid only
        """

        if self.request.content_type.startswith('application/json'):
            self.serialized_value = self.request.json_body  # TODO possible exceptions
        else:
            self.serialized_value = peppercorn.parse(list(self.request.POST.items()))

        return self
Пример #20
0
    def __call__(self):
        """
        The main entry for our view
        """
        logger.info("Calling the treasury files view")
        filetype = self.request.matchdict['filetype']
        year = self.request.matchdict['year']
        month = self.request.matchdict['month']
        root_directory = get_root_directory(self.request)
        root_path = os.path.join(root_directory, filetype, year, month)

        result = self._base_result_dict(filetype)
        datas = self.collect_files(root_path)
        result['datas'] = datas

        if 'submit' in self.request.params:
            logger.info(" -> Datas were submitted")
            # L'utilisateur a demandé l'envoi de mail
            try:
                appstruct = peppercorn.parse(self.request.params.items())
                form_datas = MailSendingSchema().deserialize(appstruct)

            except colander.Invalid as e:
                logger.exception(u" - Submitted datas are invalid")
                result.update(self.request.params)
                result['errors'] = e.asdict()

            else:
                logger.info(" + Submitted datas are valid")
                mails = self._prepare_mails(
                    datas,
                    form_datas,
                    root_path,
                    year,
                    month,
                )

                # On check qu'il y a au moins une entrée pour laquelle on va
                # envoyer un mail
                if len(mails) == 0:

                    result['errors'] = {
                        'companies':
                        u"Veuillez sélectionner au moins \
    une entreprise"
                    }
                    result.update(form_datas)
                    return result

                force = form_datas.get('force', False)
                return self._send_mails(mails, force)

        return result
Пример #21
0
 def update_cnxml(self, request, zip_file, metadata=None):
     # retrieve the cnxml from the zip file on the server
     # add feature feature links to cnxml (later we will want to add metadata as well)
     # return the updated cnxml
     zip_cnxml_file = get_cnxml_from_zipfile(zip_file)
     updated_cnxml = "\n".join(zip_cnxml_file.readlines())
     structure = peppercorn.parse(request.POST.items())
     if structure.has_key('featuredlinks'):
         featuredlinks = build_featured_links(structure)
         if featuredlinks:
             updated_cnxml = add_featuredlinks_to_cnxml(zip_cnxml_file, featuredlinks)
     return updated_cnxml
Пример #22
0
 def account_view(self):
     """This is the settings form for the user. The first time a
     user logs in, they are taken here so we can get their first and
     last name.
     """
     # Special case when the db was blown away
     if self.user_id is not None and self.user is None:
         return self.logout()
     section_name = 'account'
     schema = SettingsSchema()
     form = Form(schema, buttons=('submit',))
     css_resources, js_resources = self.form_resources(form)
     if 'submit' in self.request.POST:
         controls = self.request.POST.items()
         try:
             form.validate(controls)
         except ValidationFailure as e:
             msg = 'There was an error saving your settings.'
             self.request.session.flash(msg, queue='error')
             return {
                 'form': e.render(),
                 'css_resources': css_resources,
                 'js_resources': js_resources,
                 'section': section_name,
             }
         values = parse(self.request.params.items())
         # Update the user
         with transaction.manager:
             self.user.first_name = values.get('first_name', u'')
             self.user.last_name = values.get('last_name', u'')
             self.user.time_zone = values.get('time_zone', u'US/Eastern')
             DBSession.add(self.user)
         self.request.session.flash(
             'Settings updated successfully',
             queue='success',
         )
         return HTTPFound('/list')
     # Get existing values
     if self.user is not None:
         appstruct = dict(
             first_name=self.user.first_name,
             last_name=self.user.last_name,
             time_zone=self.user.time_zone,
         )
     else:
         appstruct = {}
     return {
         'form': form.render(appstruct),
         'css_resources': css_resources,
         'js_resources': js_resources,
         'section': section_name,
     }
Пример #23
0
 def account_view(self):
     """This is the settings form for the user. The first time a
     user logs in, they are taken here so we can get their first and
     last name.
     """
     # Special case when the db was blown away
     if self.user_id is not None and self.user is None:
         return self.logout()
     section_name = 'account'
     schema = SettingsSchema()
     form = Form(schema, buttons=('submit', ))
     css_resources, js_resources = self.form_resources(form)
     if 'submit' in self.request.POST:
         controls = self.request.POST.items()
         try:
             form.validate(controls)
         except ValidationFailure as e:
             msg = 'There was an error saving your settings.'
             self.request.session.flash(msg, queue='error')
             return {
                 'form': e.render(),
                 'css_resources': css_resources,
                 'js_resources': js_resources,
                 'section': section_name,
             }
         values = parse(self.request.params.items())
         # Update the user
         with transaction.manager:
             self.user.first_name = values.get('first_name', u'')
             self.user.last_name = values.get('last_name', u'')
             self.user.time_zone = values.get('time_zone', u'US/Eastern')
             DBSession.add(self.user)
         self.request.session.flash(
             'Settings updated successfully',
             queue='success',
         )
         return HTTPFound('/list')
     # Get existing values
     if self.user is not None:
         appstruct = dict(
             first_name=self.user.first_name,
             last_name=self.user.last_name,
             time_zone=self.user.time_zone,
         )
     else:
         appstruct = {}
     return {
         'form': form.render(appstruct),
         'css_resources': css_resources,
         'js_resources': js_resources,
         'section': section_name,
     }
Пример #24
0
 def update_cnxml(self, request, zip_file, metadata=None):
     # retrieve the cnxml from the zip file on the server
     # add feature feature links to cnxml (later we will want to add metadata as well)
     # return the updated cnxml
     zip_cnxml_file = get_cnxml_from_zipfile(zip_file)
     updated_cnxml = "\n".join(zip_cnxml_file.readlines())
     structure = peppercorn.parse(request.POST.items())
     if structure.has_key('featuredlinks'):
         featuredlinks = build_featured_links(structure)
         if featuredlinks:
             updated_cnxml = add_featuredlinks_to_cnxml(
                 zip_cnxml_file, featuredlinks)
     return updated_cnxml
Пример #25
0
    def set_data(self, struct=None, obj=None, **kwargs):
        """ Sets the data for form """
        if struct is None:
            struct = {}
        parsed_data = peppercorn.parse(struct.items())
        if '_ziggurat_form_field_' in parsed_data:
            self._non_coerced_data = parsed_data['_ziggurat_form_field_']
        else:
            self._non_coerced_data = parsed_data
        self._coerced_data_holder = copy.deepcopy(self._non_coerced_data)
        self.set_nodes()

        coerce_recursive(self.widget, self)
Пример #26
0
    def edit_form_post_view(self):
        form = self.context.form(self.request)
        params = {'form': form.render()}

        def get_reponse(form=None):
            if form:
                params['form'] = form
            return render_to_response(
                self.context.renderer, params, request=self.request
            )

        if 'form.submitted' in self.request.params:
            controls = self.request.POST.items()
            pstruct = peppercorn.parse(controls)

            # Validate form
            try:
                deserialized = form.validate_pstruct(pstruct).values()
            except deform.ValidationFailure as e:
                return get_reponse(e.render())
            data = {k: preprocessing_value(k, v, form)  # TODO: optimize it
                    for d in deserialized
                    for k, v in d.items()}

            # Update object
            try:
                if self.context.obj:
                    obj = self.context.sacrud._add(self.context.obj, data)
                    flash_action = 'updated'
                else:
                    obj = self.context.sacrud.create(data)
                    flash_action = 'created'
                name = obj.__repr__()
                self.context.dbsession.flush()
            except SacrudException as e:
                self.flash_message(e.message, status=e.status)
                return get_reponse()
            except Exception as e:
                self.abort()
                logging.exception("Something awful happened!")
                raise e

            self.commit()

            # Make response
            self.flash_message(_ps(
                u"You ${action} object of ${name}",
                mapping={'action': flash_action, 'name': escape(name or '')}
            ))
            return self.list_view_response()
        return get_reponse()
Пример #27
0
    def __call__(self):
        """
        The main entry for our view
        """
        logger.info("Calling the treasury files view")
        filetype = self.request.matchdict['filetype']
        year = self.request.matchdict['year']
        month = self.request.matchdict['month']
        root_directory = get_root_directory(self.request)
        root_path = os.path.join(root_directory, filetype, year, month)

        result = self._base_result_dict(filetype)
        datas = self.collect_files(root_path)
        result['datas'] = datas

        if 'submit' in self.request.params:
            logger.info(" -> Datas were submitted")
            # L'utilisateur a demandé l'envoi de mail
            try:
                appstruct = peppercorn.parse(self.request.params.items())
                form_datas = MailSendingSchema().deserialize(appstruct)

            except colander.Invalid as e:
                logger.exception(u" - Submitted datas are invalid")
                result.update(self.request.params)
                result['errors'] = e.asdict()

            else:
                logger.info(" + Submitted datas are valid")
                mails = self._prepare_mails(
                    datas,
                    form_datas,
                    root_path,
                    year,
                    month,
                )

                # On check qu'il y a au moins une entrée pour laquelle on va
                # envoyer un mail
                if len(mails) == 0:

                    result['errors'] = {
                        'companies': u"Veuillez sélectionner au moins \
    une entreprise"}
                    result.update(form_datas)
                    return result

                force = form_datas.get('force', False)
                return self._send_mails(mails, force)

        return result
    def get_raw_featured_links(self, request):
        data = peppercorn.parse(request.POST.items())
        if data is None or len(data.get('featuredlinks')) < 1:
            return []

        # get featured links from data
        tmp_links = {}
        # first we organise the links by category
        for details in data['featuredlinks']:
            category = details['fl_category']
            tmp_list = tmp_links.get(category, [])
            tmp_list.append(details)
            tmp_links[category] = tmp_list
        return tmp_list
Пример #29
0
    def get_raw_featured_links(self, request):
        data = peppercorn.parse(request.POST.items())
        if data is None or len(data.get('featuredlinks')) < 1:
            return []

        # get featured links from data
        tmp_links = {}
        # first we organise the links by category
        for details in data['featuredlinks']:
            category = details['fl_category']
            tmp_list = tmp_links.get(category, [])
            tmp_list.append(details)
            tmp_links[category] = tmp_list
        return tmp_list
Пример #30
0
 def _post(self, form, controls=None):
     '''You may override this method in subclasses to do something special
     when the request method is POST.
     '''
     controls = peppercorn.parse(controls or self.request.POST.items())
     controls = self._preprocess_controls(controls)
     try:
         appstruct = form.validate_pstruct(controls)
     except d.ValidationFailure as e:
         self.status = 'invalid'
         return self._invalid(e, controls)
     else:
         self.status = 'valid'
         appstruct.pop('csrf_token', None)  # Discard the CSRF token
         return self._valid(form=form, controls=appstruct)
Пример #31
0
    def _get_sorted_component_names(self, request):
        """ Returns a list of (component names, params) from request
        """

        data = parse(request.POST.items())
        schemas = []        # establish position of widgets

        for k, v in self.request.POST.items():
            if (k == '__start__') and (':mapping' in v):
                sk = v.split(':')[0]
                parms = data[sk]

                if isinstance(parms, dict) and parms.get('schema_type', None):
                    schemas.append((sk, data[sk]))

        return schemas
    def post_index(self):
        pstruct = peppercorn.parse(self.request.POST.items())
        form = Form(BookListSchema())
        try:
            data = form.validate(pstruct)

            log.info(data)
        except FormException as e:
            return dict(
                data=pstruct,
                errors=e.prepare()
            )

        return dict(
            data=pstruct
        )
Пример #33
0
    def set_data(self, struct=None, obj=None, **kwargs):
        """ Sets the data for form """
        parsed_data = peppercorn.parse(struct.items())
        if '_ziggurat_form_field_' in parsed_data:
            self.non_coerced_data = parsed_data['_ziggurat_form_field_']
        else:
            self.non_coerced_data = parsed_data
        self.coerced_data_holder = copy.deepcopy(self.non_coerced_data)
        self.set_nodes()

        def coerce_recursive(widget, form):
            widget.coerce()
            if widget.children:
                for child_widget in widget.children:
                    coerce_recursive(child_widget, form)

        coerce_recursive(self.widget, self)
Пример #34
0
    def form_class(self, schema, **kwargs):
        data = parse(self.request.POST.items())

        schemas = self._schemas()
        schemas = self._apply_schema_edits(schemas, data)

        for s in schemas:
            schema.add(s)

        # move the pipeline components select widget to the bottom
        w = schema.__delitem__('pipeline_components')
        schema.add(w)

        kwargs.update(dict(self.form_options))

        self.form = Form(schema, renderer=deform_renderer, **kwargs)

        return self.form
Пример #35
0
    def validate(self, force_validate=False, params=None):
        """
        Runs validation and returns True/False whether form is 
        valid.
        
        This will check if the form should be validated (i.e. the
        request method matches) and the schema validates.

        Validation will only be run once; subsequent calls to 
        validate() will have no effect, i.e. will just return
        the original result.

        The `errors` and `data` dicts will be updated accordingly.

        `force_validate`  : will run validation regardless of request method.

        `params`          : dict or MultiDict of params. By default 
        will use **request.POST** (if HTTP POST) or **request.params**.
        """

        if self.is_validated:
            return not(self.errors)

        if not force_validate:
            if self.method and self.method != self.request.method:
                return False

        if params is None:
            if self.method == "POST":
                params = self.request.POST
            else:
                params = self.request.params
            
        params = peppercorn.parse(params.items())
        self.data.update(params)

        if self.schema:
            try:
                self.data = self.schema.deserialize(params)
            except colander.Invalid, e:
                self.errors = e.asdict()
Пример #36
0
def index():

    if flask.request.method == "POST":
        #Please note the "multi=True"

        controlData = peppercorn.parse(flask.request.form.items(multi=True))

        print "controlData", controlData  #this is it!!!!!!!!!!!!!!!!!!!!
        #Now, create the form to be returned to the user according to the schema defined before and populating it with the data that were posted by the user and processed by the application so far.
        form = deform.Form(topList(), buttons=('submit', )).render(controlData)
        aMess = "Processed Data"  #Just a string to define a message
        return flask.render_template("index.html", theForm=form, title="HI")

    else:
        #Just return an empty form

        schema = Schema()
        form = deform.Form(schema, buttons=('submit', )).render()
        return flask.render_template("index.html",
                                     theForm=form,
                                     theMessage="HI")
Пример #37
0
def form_view(request):
    itemSchema = ItemSchema()
    itemForm = Form(itemSchema, buttons=('submit',),  formid='itemForm', counter=counter)
    categorySchema = CategorySchema()
    categoryForm = Form(categorySchema, buttons=('submit',), formid='categoryForm', counter=counter)
    purchaseSchema = PurchaseSchema()
    purchaseForm = Form(purchaseSchema, buttons=('submit',), formid='purchaseForm', counter=counter)
    db = sqlite()
    dbfunctions = {
        'itemForm': {'add': db.addItem},
        'categoryForm': {'add':db.addCategory},
        'purchaseForm': {'add':db.addPurchase}
    }
    html = []
    if 'submit' in request.POST:
        posted_formid = request.POST['__formid__']
        for (formid, form) in [('itemForm', itemForm), ('categoryForm', categoryForm), ('purchaseForm', purchaseForm)]:
            if formid == posted_formid:
                controls = list(request.POST.items())
                pstruct = peppercorn.parse(controls)
                try:
                    form.validate(controls)
                    pprint.pprint(pstruct)
                    dbAdd = dbfunctions.get(formid).get('add')
                    dbAdd(pstruct)
                    url = request.application_url
                    return HTTPFound(location=url)
                except ValidationFailure as e:
                    return {'form':e.render()}
            else:
                form.schema.update()
                html.append(form.render())
    else:
        for form in itemForm, categoryForm, purchaseForm:
            form.schema.update()
            html.append(form.render())
    html = ''.join(html)
    return {'form':html}
Пример #38
0
def edit_voting_booth(context, request):
    logged_in = authenticated_userid(request)
    schema = VotingBoothSchema()
    form = Form(schema, buttons=("submit",))
    css_resources, js_resources = _form_resources(form)
    if "submit" in request.POST:
        controls = request.POST.items()
        try:
            form.validate(controls)
        except (ValidationFailure,), e:
            return {
                "form": e.render(),
                "css_resources": css_resources,
                "js_resources": js_resources,
                "logged_in": logged_in,
            }
        values = parse(request.params.items())
        start, end = _process_dates(values)
        context.title = values["title"]
        context.start = start
        context.end = end
        context.categories = values["categories"]
        return HTTPFound(location=request.resource_url(context))
Пример #39
0
 def parse_from_peppercorn(self, tuples):
     self.data = {'data': peppercorn.parse(tuples)}
Пример #40
0
    def validate(self, controls, subcontrol=None):
        """
        Validate the set of controls returned by a form submission
        against the schema associated with this field or form.
        ``controls`` should be a *document-ordered* sequence of
        two-tuples that represent the form submission data.  Each
        two-tuple should be in the form ``(key, value)``.  ``node``
        should be the schema node associated with this widget.

        For example, using WebOb, you can compute a suitable value for
        ``controls`` via::

          request.POST.items()

        Or, if you're using a ``cgi.FieldStorage`` object named
        ``fs``, you can compute a suitable value for ``controls``
        via::

          controls = []
          if fs.list:
              for control in fs.list:
                  if control.filename:
                      controls.append((control.name, control))
                  else:
                      controls.append((control.name, control.value))

        Equivalent ways of computing ``controls`` should be available to
        any web framework.

        When the ``validate`` method is called:

        - if the fields are successfully validated, a data structure
          represented by the deserialization of the data as per the
          schema is returned.  It will be a mapping.

        - If the fields cannot be successfully validated, a
          :exc:`deform.exception.ValidationFailure` exception is raised.

        The typical usage of ``validate`` in the wild is often
        something like this (at least in terms of code found within
        the body of a :mod:`pyramid` view function, the particulars
        will differ in your web framework)::

          from webob.exc import HTTPFound
          from deform.exception import ValidationFailure
          from deform import Form
          import colander

          from my_application import do_something

          class MySchema(colander.MappingSchema):
              color = colander.SchemaNode(colander.String())

          schema = MySchema()

          def view(request):
              form = Form(schema, buttons=('submit',))
              if 'submit' in request.POST:  # form submission needs validation
                  controls = request.POST.items()
                  try:
                      deserialized = form.validate(controls)
                      do_something(deserialized)
                      return HTTPFound(location='http://example.com/success')
                  except ValidationFailure as e:
                      return {'form':e.render()}
              else:
                  return {'form':form.render()} # the form just needs rendering

        .. warning::

            ``form.validate(controls)`` mutates the ``form`` instance, so the
            ``form`` instance should be constructed (and live) inside one
            request.

        If ``subcontrol`` is supplied, it represents a named subitem in the
        data returned by ``peppercorn.parse(controls)``.  Use this subitem as
        the pstruct to validate instead of using the entire result of
        ``peppercorn.parse(controls)`` as the pstruct to validate.  For
        example, if you've embedded a mapping in the form named ``user``, and
        you want to validate only the data contained in that mapping instead
        if all of the data in the form post, you might use
        ``form.validate(controls, subcontrol='user')``.
        """
        pstruct = peppercorn.parse(controls)
        if subcontrol is not None:
            pstruct = pstruct.get(subcontrol, colander.null)
        return self.validate_pstruct(pstruct)
Пример #41
0
    def sa_add(self):
        bc = breadcrumbs(self.tname, get_table_verbose_name(self.table),
                         'sa_create')
        if self.pk:
            bc = breadcrumbs(self.tname,
                             get_table_verbose_name(self.table),
                             'sa_update',
                             id=self.pk)
        dbsession = self.request.dbsession
        try:
            obj = get_obj(dbsession, self.table, self.pk)
        except (NoResultFound, KeyError):
            raise HTTPNotFound
        form = SacrudForm(obj=obj,
                          dbsession=dbsession,
                          request=self.request,
                          table=self.table)()

        def get_responce(form):

            return dict(form=form.render(),
                        pk=self.pk,
                        obj=obj,
                        breadcrumbs=bc,
                        pk_to_list=pk_to_list)

        if 'form.submitted' in self.request.params:
            controls = self.request.POST.items()
            pstruct = peppercorn.parse(controls)
            if '__formid__' in pstruct:
                try:
                    deserialized = form.validate_pstruct(pstruct).values()
                except deform.ValidationFailure as e:
                    return get_responce(e)
                data = {
                    k: preprocessing_value(v)
                    for d in deserialized for k, v in d.items()
                }
            else:
                # if not peppercon format
                data = pstruct

            try:
                if self.pk:
                    obj = self.crud.update(self.pk, data)
                else:
                    obj = self.crud.create(data)
                name = obj.__repr__()
                dbsession.flush()
            except SacrudMessagedException as e:
                self.flash_message(e.message, status=e.status)
                return get_responce(form)
            except Exception as e:
                transaction.abort()
                logging.exception("Something awful happened!")
                raise e
            transaction.commit()

            if self.pk:
                self.flash_message(
                    _ps(u"You updated object of ${name}",
                        mapping={'name': escape(name or '')}))
            else:
                self.flash_message(
                    _ps("You created new object of ${name}",
                        mapping={'name': escape(name or '')}))
            return HTTPFound(
                location=self.request.route_url('sa_list', table=self.tname))
        return get_responce(form)
Пример #42
0
def experimentForm(request):

   
    
    """ project form page """
    class All(colander.MappingSchema):
        setup_schema(None,experiment)
        experimentSchema=experiment.__colanderalchemy__
        setup_schema(None,experimental_conditions)
        conditionsSchema=experimental_conditions.__colanderalchemy__
        setup_schema(None,data_aquisition)
        data_aquisition_Schema=data_aquisition.__colanderalchemy__
        
    
    tables = All()
    form = deform.Form(tables,buttons=('submit',))
        
    if 'submit' in request.POST:
        #map columns
        controls = request.POST.items()

        controls = request.POST.items()     #call validate
        pstruct = peppercorn.parse(controls)
        print(pstruct)
        

        try:



                appstruct = form.validate(controls)
                experiment_description = request.params['experiment_description']
                exp = pstruct['experimentSchema'] # try to add to database
                print(exp)
                page = experiment(project_ID=0,**exp)
                request.dbsession.add(page)
                experiment_description= request.params['experiment_description']
                #retrieve last db entry for experiment ID 
                id = request.dbsession.query(experiment).order_by(experiment.experiment_ID.desc()).first()#link experiment column to related foreign keys
                #experiment_id = request.dbsession.query(experiment).filter_by(experiment_description=experiment_description).first()
                experiment_id = int(id.experiment_ID) 
                
                experimental_cond = pstruct['conditionsSchema']
                page = experimental_conditions(experiment_ID=experiment_id, **experimental_cond)
                request.dbsession.add(page)
                data_aq = pstruct['data_aquisition_Schema']
                page = data_aquisition(**data_aq, experiment_ID=experiment_id)
                request.dbsession.add(page)
                #experiment_id = request.dbsession.query(experiment).filter_by(experiment_description=experiment_description).first()
                
                next_url = request.route_url('experimentPage', experiment=experiment_id)
                return HTTPFound(location=next_url)
             
        except deform.ValidationFailure as e: # catch the exception
                return {'experimentForm':e.render()}
           

        
    
    else:
        experimentForm = form.render()
        return{'experimentForm':experimentForm}
Пример #43
0
    def validate(self, controls):
        """
        Validate the set of controls returned by a form submission
        against the schema associated with this field or form.
        ``controls`` should be a *document-ordered* sequence of
        two-tuples that represent the form submission data.  Each
        two-tuple should be in the form ``(key, value)``.  ``node``
        should be the schema node associated with this widget.

        For example, using WebOb, you can compute a suitable value for
        ``controls`` via::

          request.POST.items()

        Or, if you're using a ``cgi.FieldStorage`` object named
        ``fs``, you can compute a suitable value for ``controls``
        via::

          controls = []
          if fs.list:
              for control in fs.list:
                  if control.filename:
                      controls.append((control.name, control))
                  else:
                      controls.append((control.name, control.value))

        Equivalent ways of computing ``controls`` should be available to
        any web framework.

        When the ``validate`` method is called:

        - if the fields are successfully validated, a data structure
          represented by the deserialization of the data as per the
          schema is returned.  It will be a mapping.

        - If the fields cannot be successfully validated, a
          :exc:`colander.Invalid` exception is raised.

        The typical usage of ``validate`` in the wild is often
        something like this (at least in terms of code found within
        the body of a :mod:`pyramid` view function, the particulars
        will differ in your web framework)::

          from webob.exc import HTTPFound
          from deform.exception import ValidationFailure
          from deform import schema
          from deform.form import Form

          from my_application import do_something

          class MySchema(schema.MappingSchema):
              color = schema.SchemaNode(schema.String())

          schema = MySchema()
          form = Form(schema)
          
          if 'submit' in request.POST:  # the form submission needs validation
              controls = request.POST.items()
              try:
                  deserialized = form.validate(controls)
                  do_something(deserialized)
                  return HTTPFound(location='http://example.com/success')
              except ValidationFailure, e:
                  return {'form':e.render()}
          else:
              return {'form':form.render()} # the form just needs rendering
        """
        pstruct = peppercorn.parse(controls)
        e = None

        try:
            cstruct = self.deserialize(pstruct)
        except colander.Invalid, e:
            # fill in errors raised by widgets
            self.widget.handle_error(self, e)
            cstruct = e.value
Пример #44
0
    def validate(self, controls, subcontrol=None):
        """
        Validate the set of controls returned by a form submission
        against the schema associated with this field or form.
        ``controls`` should be a *document-ordered* sequence of
        two-tuples that represent the form submission data.  Each
        two-tuple should be in the form ``(key, value)``.  ``node``
        should be the schema node associated with this widget.

        For example, using WebOb, you can compute a suitable value for
        ``controls`` via::

          request.POST.items()

        Or, if you're using a ``cgi.FieldStorage`` object named
        ``fs``, you can compute a suitable value for ``controls``
        via::

          controls = []
          if fs.list:
              for control in fs.list:
                  if control.filename:
                      controls.append((control.name, control))
                  else:
                      controls.append((control.name, control.value))

        Equivalent ways of computing ``controls`` should be available to
        any web framework.

        When the ``validate`` method is called:

        - if the fields are successfully validated, a data structure
          represented by the deserialization of the data as per the
          schema is returned.  It will be a mapping.

        - If the fields cannot be successfully validated, a
          :exc:`deform.exception.ValidationFailure` exception is raised.

        The typical usage of ``validate`` in the wild is often
        something like this (at least in terms of code found within
        the body of a :mod:`pyramid` view function, the particulars
        will differ in your web framework)::

          from webob.exc import HTTPFound
          from deform.exception import ValidationFailure
          from deform import Form
          import colander

          from my_application import do_something

          class MySchema(colander.MappingSchema):
              color = colander.SchemaNode(colander.String())

          schema = MySchema()

          def view(request):
              form = Form(schema, buttons=('submit',))
              if 'submit' in request.POST:  # form submission needs validation
                  controls = request.POST.items()
                  try:
                      deserialized = form.validate(controls)
                      do_something(deserialized)
                      return HTTPFound(location='http://example.com/success')
                  except ValidationFailure as e:
                      return {'form':e.render()}
              else:
                  return {'form':form.render()} # the form just needs rendering

        .. warning::

            ``form.validate(controls)`` mutates the ``form`` instance, so the
            ``form`` instance should be constructed (and live) inside one
            request.

        If ``subcontrol`` is supplied, it represents a named subitem in the
        data returned by ``peppercorn.parse(controls)``.  Use this subitem as
        the pstruct to validate instead of using the entire result of
        ``peppercorn.parse(controls)`` as the pstruct to validate.  For
        example, if you've embedded a mapping in the form named ``user``, and
        you want to validate only the data contained in that mapping instead
        if all of the data in the form post, you might use
        ``form.validate(controls, subcontrol='user')``.
        """
        try:
            pstruct = peppercorn.parse(controls)
        except ValueError as e:
            exc = colander.Invalid(self.schema,
                                   "Invalid peppercorn controls: %s" % e)
            self.widget.handle_error(self, exc)
            cstruct = colander.null
            raise exception.ValidationFailure(self, cstruct, exc)
        if subcontrol is not None:
            pstruct = pstruct.get(subcontrol, colander.null)
        return self.validate_pstruct(pstruct)
Пример #45
0
def spectraForm(request):
    """ project form page """

    tmpstore = FileUploadTempStore()

    class Sample(colander.MappingSchema):
        setup_schema(None, spectra)
        spectraSchema = spectra.__colanderalchemy__
        type = colander.SchemaNode(
            colander.String(),
            default='',
            widget=deform.widget.SelectWidget(values=type_choices))
        format = colander.SchemaNode(
            colander.String(),
            default='',
            widget=deform.widget.SelectWidget(values=format_choices))
        sample_power_spectrum = colander.SchemaNode(
            deform.FileData(), widget=deform.widget.FileUploadWidget(tmpstore))
        background_power_spectrum = colander.SchemaNode(
            deform.FileData(), widget=deform.widget.FileUploadWidget(tmpstore))
        initial_result_spectrum = colander.SchemaNode(
            deform.FileData(), widget=deform.widget.FileUploadWidget(tmpstore))
        final_spectrum = colander.SchemaNode(
            deform.FileData(), widget=deform.widget.FileUploadWidget(tmpstore))
        setup_schema(None, post_processing_and_deposited_spectra)
        ppSchema = post_processing_and_deposited_spectra.__colanderalchemy__
        upload = colander.SchemaNode(
            deform.FileData(), widget=deform.widget.FileUploadWidget(tmpstore))

    form = Sample()

    form = deform.Form(form, buttons=('submit', ))

    if 'submit' in request.POST:

        #add more of these and then work on jcamp graph overlays with javascript

        try:
            #appstruct = form.validate(controls) #call validate
            #upload file functionality - sample_power_spectrum as initial example
            print(request.POST)
            controls = request.POST.items()
            pstruct = peppercorn.parse(controls)
            print(pstruct)
            """ this doesnt work for now dirName = request.params['experiment_ID']
                dirName = 'C:/ftirdb/ftirdb/data/' + dirName
                os.mkdir(dirName)"""
            myfile = pstruct['sample_power_spectrum']['upload']
            background = pstruct['background_power_spectrum']['upload']
            init = pstruct['initial_result_spectrum']['upload']
            final = pstruct['final_spectrum']['upload']
            #using pure path as coding on windows and putting on to a linux server
            permanent_store = pathlib.PureWindowsPath(
                'C:/ftirdb/ftirdb/static/data')
            permanent_file = open(
                os.path.join(permanent_store, myfile.filename.lstrip(os.sep)),
                'wb')
            shutil.copyfileobj(myfile.file, permanent_file)
            myfile.file.close()
            permanent_file.close()
            permanent_file = open(
                os.path.join(permanent_store,
                             background.filename.lstrip(os.sep)), 'wb')
            shutil.copyfileobj(background.file, permanent_file)
            background.file.close()
            permanent_file.close()
            permanent_file = open(
                os.path.join(permanent_store, init.filename.lstrip(os.sep)),
                'wb')
            shutil.copyfileobj(init.file, permanent_file)
            init.file.close()
            permanent_file.close()
            permanent_file = open(
                os.path.join(permanent_store, final.filename.lstrip(os.sep)),
                'wb')
            shutil.copyfileobj(final.file, permanent_file)
            final.file.close()
            permanent_file.close()
            print(myfile.filename)
            #break through adding schema to db without having to manually enter each one
            ok = pstruct['spectraSchema']
            type = request.params['type']
            format = request.params['format']
            page = spectra(**ok, spectra_type=type, format=format)
            request.dbsession.add(page)

            #try the same for upload and file name to add to db
            pok = pstruct['ppSchema']
            sample_power_spectrum = myfile.filename
            background_power_spectrum = background.filename
            initial = init.filename
            final = final.filename
            searchdb = request.dbsession.query(spectra).order_by(
                spectra.spectra_ID.desc()).first()
            spectra_ID = searchdb.spectra_ID
            print(spectra_ID)
            page = post_processing_and_deposited_spectra(
                spectra_ID=spectra_ID,
                final_published_spectrum=final,
                sample_power_spectrum=sample_power_spectrum,
                background_power_spectrum=background_power_spectrum,
                initial_result_spectrum=initial,
                **pok)
            request.dbsession.add(page)
            #in future change this so it just querys spectra and takes the first option

            next_url = request.route_url('spectraPage', spectra_ID=spectra_ID)
            return HTTPFound(location=next_url)

        except deform.ValidationFailure as e:  # catch the exception
            return {'spectraForm': e.render()}
    else:

        spectraForm = form.render()
        return {'spectraForm': spectraForm}
Пример #46
0
    return {'main':main, 'messages':messages, 'form':myform.render(),'logged_in':logged_in, 'actions':actions}

	
@view_config(route_name='signup', renderer='templates/justforms.pt')
def signup(request):
	"""Sign up form page
	"""
    schema = SignupSchema()
    myform = Form(schema, buttons=('submit',))
    came_from = request.params.get('came_from', '/')
    main = get_renderer('templates/unlogged.pt').implementation()
    logged_in = authenticated_userid(request)   

    if 'submit' in request.POST or 'Submit' in request.POST:
        controls = request.POST.items()
        params = peppercorn.parse(request.POST.items())
        username = params['username']

        #validate form
        try:
            myform.validate(controls)
        except ValidationFailure, e:
            return {'main':main, 'form':e.render(), 'logged_in':logged_in}
        
        login = username
        firstname = params['firstname']
        lastname = params['lastname']
        password = _hash_pw(params['password']['value'])
        email = params['email']
        gender = params['gender']
        lookingfor = params['lookingfor']
Пример #47
0
def spectrometerForm(request):
    """ project form page """

    tmpstore = FileUploadTempStore()
    exp = request.matchdict['experiment_ID']

    class Sample(colander.MappingSchema):
        setup_schema(None, spectrometer)
        spectrometerSchema = spectrometer.__colanderalchemy__
        light_source = colander.SchemaNode(
            colander.String(),
            default='',
            widget=deform.widget.SelectWidget(values=light_source_choice))
        beamsplitter = colander.SchemaNode(
            colander.String(),
            default='',
            widget=deform.widget.SelectWidget(values=beam_splitter_choice))
        detector = colander.SchemaNode(
            colander.String(),
            default='',
            widget=deform.widget.SelectWidget(values=detector_choice))
        optics = colander.SchemaNode(
            colander.String(),
            default='',
            widget=deform.widget.SelectWidget(values=optics_choice))
        type_of_recording = colander.SchemaNode(
            colander.String(),
            default='',
            widget=deform.widget.SelectWidget(values=recording_choice))
        mode_of_recording = colander.SchemaNode(
            colander.String(),
            default='',
            widget=deform.widget.SelectWidget(values=mode_choice))
        setup_schema(None, atr)
        atrSchema = atr.__colanderalchemy__
        prism = colander.SchemaNode(
            colander.String(),
            default='',
            widget=deform.widget.SelectWidget(values=prism_choice))
        setup_schema(None, not_atr)
        not_atrSchema = not_atr.__colanderalchemy__
        window = colander.SchemaNode(
            colander.String(),
            default='',
            widget=deform.widget.SelectWidget(values=window_choice))
        setup_schema(None, transflectance_diffuse)
        trans_diff_Schema = transflectance_diffuse.__colanderalchemy__

    form = Sample()

    form = deform.Form(form, buttons=('submit', ))

    if 'submit' in request.POST:  #
        controls = request.POST.items()

        try:
            #upload file functionality - sample_power_spectrum as initial example

            print(controls)
            appstruct = form.validate(controls)
            pstruct = peppercorn.parse(controls)
            print(pstruct)

            optics = request.params['optics']
            beamsplitter = request.params['beamsplitter']
            type_of_recording = request.params['type_of_recording']
            mode_of_recording = request.params['mode_of_recording']
            detector = request.params['detector']
            light_source = request.params['light_source']
            prism = request.params['prism']
            window = request.params['window']

            #break through adding schema to db without having to manually enter each one
            """ok = pstruct['Spectrometerschema']     
                page = spectrometer(experiment_ID=exp,optics=optics,beamsplitter=beamsplitter,type_of_recording=type_of_recording,
                                    detector__type=detector,light_source=light_source,mode_of_recording=mode_of_recording,**ok)
                request.dbsession.add(page)
                
                
                #try the same for upload and file name to add to db
                pok = pstruct['atrSchema']
                page = atr(**pok,prism_material=prism)
                request.dbsession.add(page)

                naok = pstruct['not_atrSchema']
                page = not_atr(**naok,sample_window_material=window)
                request.dbsession.add(page)

                tran = pstruct['trans_diff_Schema']
                page = transflectance_diffuse(**tran)
                request.dbsession.add(page)
                appstruct = form.validate(controls) #call validate
                #need to fix this
                print(appstruct)
                
                experiment_id = request.dbsession.query(spectrometer).filter_by(optics=optics).first()
                spec_id = experiment_id.spectrometer_ID"""
            next_url = request.route_url('spectrometerPage', spectrometer_ID=1)
            return HTTPFound(location=next_url)

        except deform.ValidationFailure as e:  # catch the exception
            return {'spectrometerForm': e.render()}

    else:

        spectrometerForm = form.render()
        return {'spectrometerForm': spectrometerForm}
Пример #48
0
 def _callFUT(self, fields):
     from peppercorn import parse
     return parse(fields)
 def _reverse(self, fields):
     from peppercorn import parse
     return parse(fields)
Пример #50
0
    def validate(self, controls):
        """
        Validate the set of controls returned by a form submission
        against the schema associated with this field or form.
        ``controls`` should be a *document-ordered* sequence of
        two-tuples that represent the form submission data.  Each
        two-tuple should be in the form ``(key, value)``.  ``node``
        should be the schema node associated with this widget.

        For example, using WebOb, you can compute a suitable value for
        ``controls`` via::

          request.POST.items()

        Or, if you're using a ``cgi.FieldStorage`` object named
        ``fs``, you can compute a suitable value for ``controls``
        via::

          controls = []
          if fs.list:
              for control in fs.list:
                  if control.filename:
                      controls.append((control.name, control))
                  else:
                      controls.append((control.name, control.value))

        Equivalent ways of computing ``controls`` should be available to
        any web framework.

        When the ``validate`` method is called:

        - if the fields are successfully validated, a data structure
          represented by the deserialization of the data as per the
          schema is returned.  It will be a mapping.

        - If the fields cannot be successfully validated, a
          :exc:`deform.exception.ValidationFailure` exception is raised.

        The typical usage of ``validate`` in the wild is often
        something like this (at least in terms of code found within
        the body of a :mod:`pyramid` view function, the particulars
        will differ in your web framework)::

          from webob.exc import HTTPFound
          from deform.exception import ValidationFailure
          from deform import schema
          from deform.form import Form

          from my_application import do_something

          class MySchema(schema.MappingSchema):
              color = schema.SchemaNode(schema.String())

          schema = MySchema()
          form = Form(schema)
          
          if 'submit' in request.POST:  # the form submission needs validation
              controls = request.POST.items()
              try:
                  deserialized = form.validate(controls)
                  do_something(deserialized)
                  return HTTPFound(location='http://example.com/success')
              except ValidationFailure, e:
                  return {'form':e.render()}
          else:
              return {'form':form.render()} # the form just needs rendering
        """
        pstruct = peppercorn.parse(controls)
        exc = None

        try:
            cstruct = self.deserialize(pstruct)
        except colander.Invalid as e:
            # fill in errors raised by widgets
            self.widget.handle_error(self, e)
            cstruct = e.value
            exc = e

        try:
            appstruct = self.schema.deserialize(cstruct)
        except colander.Invalid as e:
            # fill in errors raised by schema nodes
            self.widget.handle_error(self, e)
            exc = e

        if exc:
            raise exception.ValidationFailure(self, cstruct, exc)

        return appstruct