コード例 #1
0
ファイル: views.py プロジェクト: moenchishti/eea.corpus
    def corpus(self):
        """ Return a corpus based on environment.

        It will try to return it from cache, otherwise load it from disk.
        If corpus hasn't been extracted from the document, it will redirect to
        a corpus creation tool.
        """

        corpus = get_corpus(self.request)

        if corpus is None:
            raise exc.HTTPNotFound()

        return corpus
コード例 #2
0
ファイル: affaire.py プロジェクト: chokri-koussa/infolica
def delete_courrier_affaire_view(request):
    settings = request.registry.settings
    filename = request.params['filename']
    temporary_directory = settings["temporary_directory"]
    file_path = os.path.join(temporary_directory, filename)

    if os.path.exists(file_path):
        os.remove(file_path)
        response = True

        return "ok"

    else:
        raise exc.HTTPNotFound("Le fichier est indisponible")
コード例 #3
0
def get_uuid(shortid):
    settings = get_current_registry().settings
    with psycopg2.connect(settings[config.CONNECTION_STRING]) as db_connection:
        with db_connection.cursor() as cursor:
            cursor.execute(SQL['get-module-uuid'], {'id': shortid})
            try:
                return cursor.fetchone()[0]
            except (
                    TypeError,
                    IndexError,
            ):  # None returned
                logger.debug("Short ID was supplied and could not discover "
                             "UUID.")
                raise httpexceptions.HTTPNotFound()
コード例 #4
0
    def __call__(self):
        try:
            page_content_file = os.path.join(
                os.path.dirname(__file__), '..', 'pagecontent',
                self.request.matchdict['doc_name'] + '.html')
            with file(page_content_file) as f:
                page_content = f.read()
        except IOError:
            return httpexceptions.HTTPNotFound()

        return {
            'doc': self.request.matchdict['doc_name'],
            'page_content': page_content
        }
コード例 #5
0
 def update(self):
     """Update a single user entry"""
     user_id = int(self.request.matchdict['id'])
     if not self.logged_in or user_id != self.logged_in:
         return exc.HTTPForbidden()
     user = self.request.dbsession.query(User).get(user_id)
     if user is not None:
         args = self.request.json
         for key, value in args.items():
             if args[key] is not None:
                 setattr(user, key, value)
         transaction.commit()
         return {'user': user.to_json()}
     raise exc.HTTPNotFound()
コード例 #6
0
ファイル: api.py プロジェクト: nextgis/nextgisweb
def _item_get(request):
    fnd, fnm = request.env.file_upload.get_filename(request.matchdict['id'])

    if not isfile(fnm):
        raise exc.HTTPNotFound()

    with open(fnm, 'rb') as fd:
        meta = pickle.loads(fd.read())

        # Don't return incomplete upload
        if meta.get('incomplete', False):
            raise UploadNotCompleted()

        return Response(json.dumpb(meta), content_type='application/json')
コード例 #7
0
def confirmUser(request):
    if not Helper.HiddenPages.validate(request.path):
        return exc.HTTPNotFound()

    if not Helper.HiddenPages.validate(request.path):
        return exc.HTTPNotFound()

    try:
        username = request.params["username"]
        title = request.params["title"]
        firstname = request.params["firstname"]
        lastname = request.params["lastname"]
        organisation = request.params["organisation"]
        email = request.params["email"]
        password = request.params["password"]
    except:
        raise exc.HTTPBadRequest("Invalid request")

        # Check if username already exists

    if len(db.execute("User_Info", [username])):
        raise exc.HTTPBadRequest("Username Exists")

    salt, hashedPassword = Helper.hashPassword(password)
    db.execute("User_confirmTemp", [
        username, email, salt, hashedPassword, title, firstname, lastname,
        organisation, request.path[-10:]
    ])

    questions = db.execute("collectQuestions", [])
    api = ExpertModelAPI()
    for rows in questions:
        qid = rows["qid"]
        model_id = api.create_model(model_type=DEFAULT_TECH)
        db.execute("eModel_insertModel", [model_id, username, qid])

    Helper.HiddenPages.remove(request.path)
コード例 #8
0
ファイル: views.py プロジェクト: ningyifan/h
    def activate(self):
        """
        Handle a request for a user activation link.

        Checks if the activation code passed is valid, and (as a safety check)
        that it is an activation for the passed user id. If all is well,
        activate the user and redirect them to the stream.
        """
        code = self.request.matchdict.get('code')
        id_ = self.request.matchdict.get('id')

        if code is None or id_ is None:
            return httpexceptions.HTTPNotFound()

        try:
            id_ = int(id_)
        except ValueError:
            return httpexceptions.HTTPNotFound()

        activation = Activation.get_by_code(code)
        if activation is None:
            return httpexceptions.HTTPNotFound()

        user = User.get_by_activation(activation)
        if user is None or user.id != id_:
            return httpexceptions.HTTPNotFound()

        # Activate the user (by deleting the activation)
        self.request.db.delete(activation)

        self.request.session.flash(
            _("Your e-mail address has been verified. "
              "Thank you!"), 'success')
        self.request.registry.notify(ActivationEvent(self.request, user))

        return httpexceptions.HTTPFound(
            location=self.request.route_url('index'))
コード例 #9
0
ファイル: login.py プロジェクト: sitn/infolica
def login_view(request):
    """
    Login
    """
    response = None

    login = None
    password = None

    if 'login' in request.params:
        login = request.params['login']

    if 'password' in request.params:
        password = request.params['password']

    # Check if user exists in DB
    query = request.dbsession.query(Operateur)
    log.info('Attempt to log with: {}'.format(login))
    operateur = query.filter(
        func.lower(Operateur.login) == func.lower(login)).first()

    if not operateur:
        return exc.HTTPNotFound('Username {} was not found'.format(login))

    try:
        resp_json = LDAPQuery.do_login(request, login, password)

    except Exception as error:
        log.error(str(error))
        return {'error': 'true', 'code': 403, 'message': str(error)}

    if resp_json and 'dn' in resp_json:
        headers = remember(request, resp_json['dn'])

        if operateur:
            operateur_json = Utils.serialize_one(operateur)
            """
            operateur_json['role_id'] = Utils.get_role_id_by_name(request, resp_json['role_name'])
            operateur_json['role_name'] = resp_json['role_name']
            operateur_json['fonctions'] = Utils.get_fonctions_roles_by_id(request, operateur_json['role_id'])
            operateur_json['fonctions'] = [x["nom"] for x in operateur_json['fonctions']]"""

            operateur_json = json.dumps(operateur_json) if operateur else ''

            response = Response(operateur_json,
                                content_type='application/json; charset=UTF-8',
                                headers=headers)

    return response
コード例 #10
0
 def _parse_feature_results(self, results):
     for i in range(0, len(results)):
         if 'error' in results[i]:
             if results[i]['error'] != '':
                 raise exc.HTTPNotFound(results[i]['error'])  # pragma: no cover
         if results[i] is not None and 'matches' in results[i]:
             # Add results to the list
             for res in results[i]['matches']:
                 if 'feature_id' in res['attrs']:
                     res['attrs']['featureId'] = res['attrs']['feature_id']
                 if self.typeInfo == 'featuresearch' or not self.bbox or \
                         self._bbox_intersection(self.bbox, res['attrs']['geom_st_box2d']):
                     if res['attrs']['layer'] == 'ch.bfs.gebaeude_wohnungs_register':
                         res['attrs'] = self._parse_address(res['attrs'])
                     self.results['results'].append(res)
コード例 #11
0
ファイル: views.py プロジェクト: hashin/h
def _validate_request(request):
    """
    Check that the passed request is appropriate for proceeding with account
    claim. Asserts that:

    - no-one is logged in
    - the claim token is provided and authentic
    - the user referred to in the token exists
    - the user referred to in the token has not already claimed their account

    and raises for redirect or 404 otherwise.
    """
    # If signed in, redirect to stream
    if request.authenticated_userid is not None:
        _perform_logged_in_redirect(request)

    payload = _validate_token(request)
    if payload is None:
        raise exc.HTTPNotFound()

    try:
        username = util.user.split_user(payload['userid'])['username']
    except ValueError:
        log.warn('got claim token with invalid userid=%r', payload['userid'])
        raise exc.HTTPNotFound()

    user = User.get_by_username(username)
    if user is None:
        log.warn('got claim token with invalid userid=%r', payload['userid'])
        raise exc.HTTPNotFound()

    # User already has a password? Claimed already.
    if user.password:
        _perform_already_claimed_redirect(request)

    return user
コード例 #12
0
ファイル: layers.py プロジェクト: cclauss/mf-chsdi3
def get_layer(query, model, layerId):
    ''' Returns exactly one layer or raises
    an exception. This function can be used with
    both a layer config model or a layer metadata
    model. '''
    query = query.filter(model.layerBodId == layerId)

    try:
        layer = query.one()
    except NoResultFound:
        raise exc.HTTPNotFound('No layer with id %s' % layerId)
    except MultipleResultsFound:  # pragma: no cover
        raise exc.HTTPInternalServerError('Multiple layers found for the same id %s' % layerId)

    return layer
コード例 #13
0
ファイル: features.py プロジェクト: fredj/mf-chsdi3
def _get_feature_db(featureId, params, models, process=True):
    feature = None
    # One layer can have several models
    for model in models:
        # return a sqlalchemy.util._collections.result
        feature = _get_feature_by_id(featureId, params, model)
        if feature is not None:
            vector_model = model
            break
    if feature is None:
        raise exc.HTTPNotFound('No feature with id %s' % featureId)
    if process:
        feature = _process_feature(feature, params)
        feature = {'feature': feature}
    return feature, vector_model
コード例 #14
0
def delete_pet(context, request):
    """
    Remove a pet

    request.matchdict:

        * 'pet_id'  Pet's Unique identifier  `{"type": "string", "required": true, "pattern": "^[a-zA-Z0-9-]+$"}`
    """
    pet_id = request.matchdict["pet_id"]
    if pet_id in PETS:
        logger.info('Deleting pet %s..', pet_id)
        del PETS[pet_id]
        raise httpexceptions.HTTPNoContent()
    else:
        raise httpexceptions.HTTPNotFound()
コード例 #15
0
ファイル: api.py プロジェクト: nextgis/nextgisweb
def _item_delete(request, tus):
    fnd, fnm = request.env.file_upload.get_filename(request.matchdict['id'])
    if not isfile(fnm):
        raise exc.HTTPNotFound()

    unlink(fnd)
    unlink(fnm)

    if tus:
        return _tus_response(204)
    else:
        return Response(
            json.dumpb(None),
            content_type='application/json',
        )
コード例 #16
0
def run_query_view(request):
    """
    Run a query
    :param request:
    :return:
    """
    query_name = request.matchdict['name']
    dashboard_id = request.matchdict['dashboard_id']
    query = session.query(Query).filter(Query.name == query_name, Query.dashboard_id == dashboard_id).first()
    if not query:
        raise exc.HTTPNotFound(json_body={'message': 'Query %s not found' % query_name})

    # format query with parameters and dashboard variables
    # run http or database query
    return format_run_query(request, query.query, request.json_body, dashboard_id, query.data_source)
コード例 #17
0
ファイル: views.py プロジェクト: Dimmus/cnx-authoring
def get_resource(request):
    """Acquisition of a resource item"""
    hash = request.matchdict['hash']
    resource = storage.get(hash=hash, type_=Resource)
    if resource is None:
        raise httpexceptions.HTTPNotFound()
    if not request.has_permission('view', resource):
        raise httpexceptions.HTTPForbidden()
    resp = request.response
    with resource.open() as data:
        resp.body = data.read()
    resp.content_type = resource.media_type
    if 'html' in resp.content_type:
        resp.content_type = 'application/octet-stream'
    return resp
コード例 #18
0
ファイル: files_handler.py プロジェクト: pfanguin/mf-chsdi3
 def read_file(self):
     try:
         if self.admin_id:
             return {
                 'fileId': self.file_id
             }
         else:
             data = self.s3_fileshandler.get_item(self.file_path)['Body'].read()
             return Response(
                 data,
                 content_type=self.item['ContentType'],
                 content_encoding=self.item['ContentEncoding']
             )
     except Exception as e:
         raise exc.HTTPNotFound('File %s not found %s' % (self.file_path, e))
コード例 #19
0
def archive_edit_config(request):
    archiveConfig = DBSession.query(ConfigArchive).get(request.matchdict['id'])
    if not archiveConfig:
        return exc.HTTPNotFound()
    device = DBSession.query(OpenWrt).get(archiveConfig.router_uuid)
    if not device:
        return exc.HTTPNotFound()
    conf = Uci()
    conf.load_tree(archiveConfig.configuration);
    if request.POST:
        configsToBeUpdated=[]
        newConfig = {}
        for key, val in request.POST.dict_of_lists().items():
            if key != "submitted":
                val[0] = val[0].replace("'", '"') # for better json recognition
                packagename, configname, optionname = key.split()
                if not (packagename in newConfig.keys()):
                    newConfig[packagename] = {}
                    newConfig[packagename]['values'] = {}
                if not (configname in newConfig[packagename]['values'].keys()):
                    newConfig[packagename]['values'][configname] = {}
                try:
                    savevalue = json.loads(val[0])
                except ValueError:
                    savevalue = val[0]
                newConfig[packagename]['values'][configname][optionname] = savevalue
        confToBeArchivedNew = ConfigArchive(datetime.now(),
                                            json.dumps(newConfig),
                                            archiveConfig.router_uuid,
                                            id_generator())
        DBSession.add(confToBeArchivedNew)
        return HTTPFound(location=request.route_url('confarchive'))
    return{ 'hiddenOptions' : ['.index','.type','.name','.anonymous'],
            'config'        : conf,
            'routerName'    : device.name,
            'date'          : archiveConfig.date}
コード例 #20
0
def delete(request, model):
    """
    Delete a script view
    :param request: HTTP Request
    :param model: SQLAlchemy model instance
    :return:
    """
    record_id = request.matchdict.get('id')
    record = session.query(model).filter(model.id == record_id).first()
    if not record:
        raise exc.HTTPNotFound(json_body={'message': 'Record not found.'})

    return session.query(model). \
        filter(model.id == record_id). \
        delete(synchronize_session='fetch')
コード例 #21
0
ファイル: RESTServices.py プロジェクト: Abenezer/eyouapp
def locate_area(request):
    from geopy.geocoders import Nominatim
    q = request.params['q']
    print(q)
    geolocator = Nominatim(format_string='%s, addis ababa',
                           timeout=10,
                           country_bias='Ethiopia')
    location = geolocator.geocode(q)
    if location == None:
        raise exc.HTTPNotFound()
    return {
        'address': location.address,
        'lat': location.latitude,
        'lon': location.longitude
    }
コード例 #22
0
    def structure_data(self, id=None):
        id = self.request.matchdict["id"]
        if id is None:
            raise exc.HTTPNotFound()
        data = model.meta.DBSession.query(tables.Structure)
        rec = data.get(int(id))

        if rec is None:
            raise exc.HTTPNotFound()
        records = model.meta.DBSession.query(tables.Structure)
        records = records.filter_by(_protein_id=rec.protein.id)
        if rec.ligand:
            records = records.filter_by(_ligand_id=rec.ligand.id)

        def page_url(page):
            return h.current_route_path(self.request,
                                        page=page,
                                        _query=self.request.GET)

        current_page = int(self.request.matchdict["page"])
        self.request.tmpl_context.paginator = paginate.Page(records,
                                                            current_page,
                                                            url=page_url)
        return {}
コード例 #23
0
ファイル: activity.py プロジェクト: kaydoh/h
    def _check_access_permissions(self):
        if not self.request.has_permission(Permission.Group.READ,
                                           context=self.context):
            show_join_page = self.request.has_permission(
                Permission.Group.JOIN, self.context)
            if not self.request.user:
                # Show a page which will prompt the user to login to join.
                show_join_page = True

            if show_join_page:
                self.request.override_renderer = "h:templates/groups/join.html.jinja2"
                return {"group": self.group}

            raise httpexceptions.HTTPNotFound()

        return None
コード例 #24
0
    def get_file(self):
        # Get the requested tool
        tool, tid = self._get_tool()

        # Get the file information
        file_label = self.request.matchdict['file']
        if not file_label in tool.get_file_information():
            return exc.HTTPNotFound(detail='Tool %s has no such component %s' %
                                    (tool.name, file_label))
        file_content = getattr(tool, file_label)
        file_extension = tool.get_file_information()[file_label]['extension']

        return Response(content_type='application/force-download',
                        content_disposition='attachment; filename=%s_%s.%s' %
                        (tool.name, file_label, file_extension),
                        body=file_content)
コード例 #25
0
ファイル: schemas.py プロジェクト: jhonsnow456/bodhi
    def get(self) -> dict:
        """
        Retrieve and render a single message schema.

        This API responses to the ``/message_schemas/v1/<topic>`` endpoint.

        Returns:
            The requested message schema.
        """
        try:
            return pkg_resources.load_entry_point(
                'bodhi-messages', 'fedora.messages',
                f"{self.request.matchdict['topic']}.v1").body_schema
        except ImportError:
            # The user has requested a topic that does not exist
            raise httpexceptions.HTTPNotFound()
コード例 #26
0
ファイル: views.py プロジェクト: openstax/cnx-user
def get_user(request):
    id = request.matchdict['user_id']
    try:
        user = DBSession.query(User).filter(User.id == id).first()
    except DBAPIError:
        raise httpexceptions.HTTPServiceUnavailable(
            connection_error_message,
            content_type='text/plain',
        )
    if user is None:
        raise httpexceptions.HTTPNotFound()

    permissible = security.has_permission('view', user, request)
    if not permissible:
        raise httpexceptions.HTTPForbidden()
    return user
コード例 #27
0
def _get_page_in_book(page_uuid,
                      page_version,
                      book_uuid,
                      book_version,
                      latest=False):
    book_ident_hash = join_ident_hash(book_uuid, book_version)
    coltree = _get_content_json(ident_hash=book_ident_hash)['tree']
    if coltree is None:
        raise httpexceptions.HTTPNotFound()
    pages = list(flatten_tree_to_ident_hashes(coltree))
    page_ident_hash = join_ident_hash(page_uuid, page_version)
    if page_ident_hash in pages:
        return book_uuid, '{}:{}'.format(
            latest and book_uuid or book_ident_hash, page_uuid)
    # book not in page
    return page_uuid, page_ident_hash
コード例 #28
0
ファイル: accounts.py プロジェクト: Manuelinux/kubeh
    def get_with_prefilled_code(self):
        """Render the reset password form with a prefilled code."""
        code = self.request.matchdict["code"]

        # If valid, we inject the supplied it into the form as a hidden field.
        # Otherwise, we 404.
        try:
            user = ResetCode().deserialize(self.schema, code)
        except colander.Invalid:
            raise httpexceptions.HTTPNotFound()
        else:
            # N.B. the form field for the reset code is called 'user'. See the
            # comment in `~h.schemas.forms.accounts.ResetPasswordSchema` for details.
            self.form.set_appstruct({"user": user})
            self.form.set_widgets({"user": deform.widget.HiddenWidget()})

        return {"form": self.form.render(), "has_code": True}
コード例 #29
0
def profile_media_(request):
    name = request.matchdict['name']
    link_type = request.matchdict['link_type']
    userid = profile.resolve_by_username(name)
    media_items = media.get_user_media(userid)
    if not media_items.get(link_type):
        raise httpexceptions.HTTPNotFound()
    return Response(headerlist=[
        (
            'X-Accel-Redirect',
            str(media_items[link_type][0]['file_url']),
        ),
        (
            'Cache-Control',
            'max-age=0',
        ),
    ])
コード例 #30
0
    def itc_data(self, id=None):
        id = self.request.matchdict["id"]
        if id is None:
            raise exc.HTTPNotFound()
        records = model.meta.DBSession.query(
            tables.ITC).filter_by(_instrument_id=id)

        def page_url(page):
            return h.current_route_path(self.request,
                                        page=page,
                                        _query=self.request.GET)

        current_page = int(self.request.matchdict["page"])
        self.request.tmpl_context.paginator = paginate.Page(records,
                                                            current_page,
                                                            url=page_url)
        return {}