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


Python web_exceptions.HTTPNotFound方法代码示例

本文整理汇总了Python中aiohttp.web_exceptions.HTTPNotFound方法的典型用法代码示例。如果您正苦于以下问题:Python web_exceptions.HTTPNotFound方法的具体用法?Python web_exceptions.HTTPNotFound怎么用?Python web_exceptions.HTTPNotFound使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在aiohttp.web_exceptions的用法示例。


在下文中一共展示了web_exceptions.HTTPNotFound方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: student

# 需要导入模块: from aiohttp import web_exceptions [as 别名]
# 或者: from aiohttp.web_exceptions import HTTPNotFound [as 别名]
def student(request: Request):
    app: Application = request.app
    student_id = int(request.match_info['id'])
    async with app['db'].acquire() as conn:
        student = await Student.get(conn, student_id)
        if not student:
            raise HTTPNotFound()
        marks = await Mark.get_for_student(conn, student_id)
        courses = await Course.get_many(conn)
    courses_marks = {c: list(ms) for c, ms
                     in groupby(marks, lambda m: m.course_id)}
    results = [
        (course, courses_marks.get(course.id))
        for course in courses
        if course.id in courses_marks
    ]
    return {'student': student, 'results': results} 
开发者ID:anxolerd,项目名称:dvpwa,代码行数:19,代码来源:views.py

示例2: review

# 需要导入模块: from aiohttp import web_exceptions [as 别名]
# 或者: from aiohttp.web_exceptions import HTTPNotFound [as 别名]
def review(request: Request):
    app: Application = request.app
    course_id = int(request.match_info['course_id'])
    async with app['db'].acquire() as conn:
        course = await Course.get(conn, course_id)
        if not course:
            raise HTTPNotFound()
        if request.method == 'POST':
            data = await request.post()
            review_text = data.get('review_text')
            if not review_text:
                return {
                    'course': course,
                    'errors': {
                        'review_text': 'this is required field',
                    },
                }
            await Review.create(conn, course_id, review_text)
            raise HTTPFound(f'/courses/{course_id}')
        return {'course': course, 'errors': {}} 
开发者ID:anxolerd,项目名称:dvpwa,代码行数:22,代码来源:views.py

示例3: evaluate

# 需要导入模块: from aiohttp import web_exceptions [as 别名]
# 或者: from aiohttp.web_exceptions import HTTPNotFound [as 别名]
def evaluate(request: Request):
    app: Application = request.app
    student_id = int(request.match_info['student_id'])
    course_id = int(request.match_info['course_id'])
    data = await request.post()
    async with app['db'].acquire() as conn:
        student = await Student.get(conn, student_id)
        course = await Course.get(conn, course_id)
        if not student or not course:
            raise HTTPNotFound()
        try:
            data = EVALUATE_SCHEMA.check_and_return(data)
        except DataError as e:
            return {'errors': e.as_dict(),
                    'course': course,
                    'student': student}
        await Mark.create(conn, student_id, course_id,
                          data['points'])
    raise HTTPFound(f'/courses/{course_id}') 
开发者ID:anxolerd,项目名称:dvpwa,代码行数:21,代码来源:views.py

示例4: getObjectIdByPath

# 需要导入模块: from aiohttp import web_exceptions [as 别名]
# 或者: from aiohttp.web_exceptions import HTTPNotFound [as 别名]
def getObjectIdByPath(app, obj_id, h5path, bucket=None, refresh=False):
    """ Find the object at the provided h5path location.
    If not found raise 404 error.
    """
    log.info(f"getObjectIdByPath obj_id: {obj_id} h5path: {h5path} refresh: {refresh}")
    if h5path.startswith("./"):
        h5path = h5path[2:]  # treat as relative path
    links = h5path.split('/')
    for link in links:
        if not link:
            continue  # skip empty link
        log.debug(f"getObjectIdByPath for objid: {obj_id} got link: {link}")
        if getCollectionForId(obj_id) != "groups":
            # not a group, so won't have links
            msg = f"h5path: {h5path} not found"
            log.warn(msg)
            raise HTTPNotFound()
        req = getDataNodeUrl(app, obj_id)
        req += "/groups/" + obj_id + "/links/" + link
        log.debug("get LINK: " + req)
        params = {}
        if bucket:
            params["bucket"] = bucket
        link_json = await http_get(app, req, params=params)
        log.debug("got link_json: " + str(link_json))
        if link_json["class"] != 'H5L_TYPE_HARD':
            # don't follow soft/external links
            msg = f"h5path: {h5path} not found"
            log.warn(msg)
            raise HTTPInternalServerError()
        obj_id = link_json["id"]
    # if we get here, we've traveresed the entire path and found the object
    return obj_id 
开发者ID:HDFGroup,项目名称:hsds,代码行数:35,代码来源:servicenode_lib.py

示例5: getRootInfo

# 需要导入模块: from aiohttp import web_exceptions [as 别名]
# 或者: from aiohttp.web_exceptions import HTTPNotFound [as 别名]
def getRootInfo(app, root_id, bucket=None):
    """ Get extra information the root collection. """
    # Gather additional info on the domain
    log.debug(f"getRootInfo {root_id}")

    if not isSchema2Id(root_id):
        log.info(f"no dataset details not available for schema v1 id: {root_id} returning null results")
        return None

    s3_key = getS3Key(root_id)

    parts = s3_key.split('/')
    # dset_key is in the format  db/<root>/d/<dset>/.dataset.json
    # get the key for the root info object as: db/<root>/.info.json
    if len(parts) != 3:
        log.error(f"Unexpected s3key format: {s3_key}")
        return None

    info_key = f"db/{parts[1]}/.info.json"

    try:
        info_json = await getStorJSONObj(app, info_key, bucket=bucket)
    except HTTPNotFound:
        log.warn(f"info.json not found for key: {info_key}")
        return None

    return info_json 
开发者ID:HDFGroup,项目名称:hsds,代码行数:29,代码来源:servicenode_lib.py

示例6: fetch

# 需要导入模块: from aiohttp import web_exceptions [as 别名]
# 或者: from aiohttp.web_exceptions import HTTPNotFound [as 别名]
def fetch(self, domain):
        log.debug(f"FolderCrawler - fetch for domain: {domain} bucket: {self._bucket}")
        domain_key = self._bucket + domain
        try:
            domain_json = await getDomainJson(self._app, domain_key, reload=True)
            log.debug(f"FolderCrawler - {domain} got domain_json: {domain_json}")
            if domain_json:
                domain_rsp = await get_domain_response(self._app, domain_json, verbose=self._verbose, bucket=self._bucket)
                if "limits" in domain_rsp:
                    # don't return limits for multi-domain responses
                    del domain_rsp["limits"]
                if "version" in domain_rsp:
                    del domain_rsp["version"]
                log.debug(f"FolderCrawler - {domain} get domain_rsp: {domain_rsp}")
                # mixin domain name
                self._domain_dict[domain] = domain_rsp
                if self._get_root and "root" in domain_json:
                    root_id = domain_json["root"]
                    log.debug(f"fetching root json for {root_id}")
                    root_json = await getObjectJson(self._app, root_id, include_links=False, include_attrs=True, bucket=self._bucket)
                    log.debug(f"got root_json: {root_json}")
                    self._group_dict[root_id] = root_json
            else:
                log.warn(f"FolderCrawler - no domain found for {domain}")
        except HTTPNotFound:
            # One of the dmains not found, but continue through the list
            log.warn(f"fetch result - not found error for: {domain}")
        except HTTPGone:
            log.warn(f"fetch result - domain: {domain} has been deleted")
        except HTTPInternalServerError:
            log.error(f"fetch result - internal error fetching: {domain}")
        except HTTPForbidden:
            log.warn(f"fetch result - access not allowed for: {domain}")
        except HTTPBadRequest:
            log.error(f"fetch result - bad request for: {domain}")
        except HTTPServiceUnavailable:
            log.warn(f"fetch result - service unavailable for domain: {domain}")
        except Exception as e:
            log.error(f"fetch result - unexpected exception for domain {domain}: exception of type {type(e)}, {e}") 
开发者ID:HDFGroup,项目名称:hsds,代码行数:41,代码来源:domain_sn.py

示例7: get_info

# 需要导入模块: from aiohttp import web_exceptions [as 别名]
# 或者: from aiohttp.web_exceptions import HTTPNotFound [as 别名]
def get_info(app, url):
    """
    Invoke the /info request on the indicated url and return the response
    """
    req = url + "/info"
    log.info(f"get_info({url})")
    try:
        log.debug("about to call http_get")
        rsp_json = await http_get(app, req)
        log.debug("called http_get")
        if "node" not in rsp_json:
            log.error("Unexpected response from node")
            return None

    except OSError as ose:
        log.warn(f"OSError for req: {req}: {ose}")
        return None

    except HTTPInternalServerError as hpe:
        log.warn(f"HTTPInternalServerError for req {req}: {hpe}")
        # node has gone away?
        return None

    except HTTPNotFound as nfe:
        log.warn(f"HTTPNotFound error for req {req}: {nfe}")
        # node has gone away?
        return None

    except TimeoutError as toe:
        log.warn(f"Timeout error for req: {req}: {toe}")
        # node has gone away?
        return None
    except HTTPGone as hg:
        log.warn("Timeout error for req: {}: {}".format(req, str(hg)))
        # node has gone away?
        return None
    except:
        log.warn("uncaught exception in get_info")

    return rsp_json 
开发者ID:HDFGroup,项目名称:hsds,代码行数:42,代码来源:basenode.py

示例8: DELETE_Group

# 需要导入模块: from aiohttp import web_exceptions [as 别名]
# 或者: from aiohttp.web_exceptions import HTTPNotFound [as 别名]
def DELETE_Group(request):
    """HTTP DELETE method for /groups/
    """
    log.request(request)
    app = request.app
    params = request.rel_url.query
    group_id = get_obj_id(request)

    if not isValidUuid(group_id, obj_class="group"):
        log.error(f"Unexpected group_id: {group_id}")
        raise HTTPInternalServerError()

    if "bucket" in params:
        bucket = params["bucket"]
    else:
        bucket = None

    log.info(f"DELETE group: {group_id} bucket: {bucket}")

    # verify the id exist
    obj_found = await check_metadata_obj(app, group_id, bucket=bucket)
    if not obj_found:
        log.debug(f"delete called on non-exsistet obj: {group_id}")
        raise HTTPNotFound()

    log.debug("deleting group: {}".format(group_id))

    notify=True
    if "Notify" in params and not params["Notify"]:
        notify=False
    await delete_metadata_obj(app, group_id, bucket=bucket, notify=notify)

    resp_json = {  }

    resp = json_response(resp_json)
    log.response(request, resp=resp)
    return resp 
开发者ID:HDFGroup,项目名称:hsds,代码行数:39,代码来源:group_dn.py

示例9: GET_Link

# 需要导入模块: from aiohttp import web_exceptions [as 别名]
# 或者: from aiohttp.web_exceptions import HTTPNotFound [as 别名]
def GET_Link(request):
    """HTTP GET method to return JSON for a link
    """
    log.request(request)
    app = request.app
    params = request.rel_url.query
    group_id = get_obj_id(request)
    log.info(f"GET link: {group_id}")

    if not isValidUuid(group_id, obj_class="group"):
        log.error(f"Unexpected group_id: {group_id}")
        raise HTTPInternalServerError()

    link_title = request.match_info.get('title')

    validateLinkName(link_title)

    if "bucket" in params:
        bucket = params["bucket"]
    else:
        bucket = None

    group_json = await get_metadata_obj(app, group_id, bucket=bucket)
    log.info(f"for id: {group_id} got group json: {group_json}")
    if "links" not in group_json:
        log.error(f"unexpected group data for id: {group_id}")
        raise HTTPInternalServerError()

    links = group_json["links"]
    if link_title not in links:
        log.warn(f"Link name {link_title} not found in group: {group_id}")
        raise HTTPNotFound()

    link_json = links[link_title]

    resp = json_response(link_json)
    log.response(request, resp=resp)
    return resp 
开发者ID:HDFGroup,项目名称:hsds,代码行数:40,代码来源:link_dn.py

示例10: DELETE_Dataset

# 需要导入模块: from aiohttp import web_exceptions [as 别名]
# 或者: from aiohttp.web_exceptions import HTTPNotFound [as 别名]
def DELETE_Dataset(request):
    """HTTP DELETE method for dataset
    """
    log.request(request)
    app = request.app
    params = request.rel_url.query
    dset_id = request.match_info.get('id')
    log.info(f"DELETE dataset: {dset_id}")

    if not isValidUuid(dset_id, obj_class="dataset"):
        log.error(f"Unexpected dataset id: {dset_id}")
        raise HTTPInternalServerError()

    if "bucket" in params:
        bucket = params["bucket"]
    else:
        bucket = None

    # verify the id  exist
    obj_found = await check_metadata_obj(app, dset_id, bucket=bucket)
    if not obj_found:
        raise HTTPNotFound()

    log.debug(f"deleting dataset: {dset_id}")

    notify=True
    if "Notify" in params and not params["Notify"]:
        notify=False
    await delete_metadata_obj(app, dset_id, bucket=bucket, notify=notify)

    resp_json = {  }

    resp = json_response(resp_json)
    log.response(request, resp=resp)
    return resp 
开发者ID:HDFGroup,项目名称:hsds,代码行数:37,代码来源:dset_dn.py

示例11: delete_object

# 需要导入模块: from aiohttp import web_exceptions [as 别名]
# 或者: from aiohttp.web_exceptions import HTTPNotFound [as 别名]
def delete_object(self, key, bucket=None):
        """ Deletes the object at the given key
        """
        if not bucket:
            log.error("delete_object - bucket not set")
            raise HTTPInternalServerError()

        start_time = time.time()
        log.debug(f"azureBlobClient.delete_object({bucket}/{key} start: {start_time}")
        try:
            async with self._client.get_container_client(container=bucket) as container_client:
                await container_client.delete_blob(blob=key)
            finish_time = time.time()
            log.info(f"azureBlobClient.delete_object({key} bucket={bucket}) start={start_time:.4f} finish={finish_time:.4f} elapsed={finish_time-start_time:.4f}")

        except CancelledError as cle:
            self._azure_stats_increment("error_count")
            msg = f"azureBlobClient.CancelledError for delete_object {key}: {cle}"
            log.error(msg)
            raise HTTPInternalServerError()
        except Exception as e:
            if isinstance(e, AzureError):
                if e.status_code == 404:
                    msg = f"azureBlobClient.key: {key} not found "
                    log.warn(msg)
                    raise HTTPNotFound()
                elif e.status_code in (401, 403):
                    msg = f"azureBlobClient.access denied for delete key: {key}"
                    log.info(msg)
                    raise HTTPForbidden()
                else:
                    self._azure_stats_increment("error_count")
                    log.error(f"azureBlobClient.got unexpected AzureError for delete_object {key}: {e.message}")
                    raise HTTPInternalServerError()
            else:
                log.error(f"azureBlobClient.Unexpected exception for put_object {key}: {e}")
                raise HTTPInternalServerError() 
开发者ID:HDFGroup,项目名称:hsds,代码行数:39,代码来源:azureBlobClient.py

示例12: http_post

# 需要导入模块: from aiohttp import web_exceptions [as 别名]
# 或者: from aiohttp.web_exceptions import HTTPNotFound [as 别名]
def http_post(app, url, data=None, params=None):
    log.info(f"http_post('{url}', {data})")
    client = get_http_client(app)
    rsp_json = None
    timeout = config.get("timeout")

    try:
        async with client.post(url, json=data, params=params, timeout=timeout ) as rsp:
            log.info(f"http_post status: {rsp.status}")
            if rsp.status == 200:
                pass  # ok
            elif rsp.status == 201:
                pass # also ok
            elif rsp.status == 204: # no data
                return None
            elif rsp.status == 404:
                log.info(f"POST  reqest HTTPNotFound error for url: {url}")
            elif rsp.status == 410:
                log.info(f"POST  reqest HTTPGone error for url: {url}")
            elif rsp.status == 503:
                log.warn(f"503 error for http_get_Json {url}")
                raise HTTPServiceUnavailable()

            else:
                log.warn(f"POST request error for url: {url} - status: {rsp.status}")
                raise HTTPInternalServerError()
            rsp_json = await rsp.json()
            log.debug(f"http_post({url}) response: {rsp_json}")
    except ClientError as ce:
        log.error(f"Error for http_post({url}): {ce} ")
        raise HTTPInternalServerError()
    except CancelledError as cle:
        log.error(f"CancelledError for http_post({url}): {cle}")
        raise HTTPInternalServerError()
    return rsp_json 
开发者ID:HDFGroup,项目名称:hsds,代码行数:37,代码来源:httpUtil.py

示例13: put_object

# 需要导入模块: from aiohttp import web_exceptions [as 别名]
# 或者: from aiohttp.web_exceptions import HTTPNotFound [as 别名]
def put_object(self, key, data, bucket=None):
        """ Write data to given key.
            Returns client specific dict on success
        """
        if not bucket:
            log.error("put_object - bucket not set")
            raise HTTPInternalServerError()

        start_time = time.time()
        log.debug(f"s3Client.put_object({bucket}/{key} start: {start_time}")
        try:
            rsp = await self._client.put_object(Bucket=bucket, Key=key, Body=data)
            finish_time = time.time()
            log.info(f"s3Client.put_object({key} bucket={bucket}) start={start_time:.4f} finish={finish_time:.4f} elapsed={finish_time-start_time:.4f} bytes={len(data)}")
            s3_rsp = {"etag": rsp["ETag"], "size": len(data), "lastModified": int(finish_time)}
        except ClientError as ce:
            response_code = ce.response["Error"]["Code"]
            if response_code == "NoSuchBucket":
                msg = f"s3_bucket: {bucket} not found"
                log.warn(msg)
                raise HTTPNotFound()
            else:
                self._s3_stats_increment("error_count")
                msg = f"Error putting s3 obj {key}: {ce}"
                log.error(msg)
                raise HTTPInternalServerError()
        except CancelledError as cle:
            #s3_stats_increment(app, "error_count")
            msg = f"CancelledError for put s3 obj {key}: {cle}"
            log.error(msg)
            raise HTTPInternalServerError()
        except Exception as e:
            #s3_stats_increment(app, "error_count")
            msg = f"Unexpected Exception {type(e)} putting s3 obj {key}: {e}"
            log.error(msg)
            raise HTTPInternalServerError()
        if data and len(data) > 0:
            self._s3_stats_increment("bytes_out", inc=len(data))
        log.debug(f"s3Client.put_object {key} complete, s3_rsp: {s3_rsp}")
        return s3_rsp 
开发者ID:HDFGroup,项目名称:hsds,代码行数:42,代码来源:s3Client.py

示例14: delete_object

# 需要导入模块: from aiohttp import web_exceptions [as 别名]
# 或者: from aiohttp.web_exceptions import HTTPNotFound [as 别名]
def delete_object(self, key, bucket=None):
        """ Deletes the object at the given key
        """
        if not bucket:
            log.error("delete_object - bucket not set")
            raise HTTPInternalServerError()

        start_time = time.time()
        log.debug(f"s3Client.delete_object({bucket}/{key} start: {start_time}")
        try:
            await self._client.delete_object(Bucket=bucket, Key=key)
            finish_time = time.time()
            log.info(f"s3Client.delete_object({key} bucket={bucket}) start={start_time:.4f} finish={finish_time:.4f} elapsed={finish_time-start_time:.4f}")

        except ClientError as ce:
            # key does not exist?
            key_found = await self.isS3Obj(key)
            if not key_found:
                log.warn(f"delete on s3key {key} but not found")
                raise HTTPNotFound()
            # else some other error
            self._s3_stats_increment("error_count")
            msg = f"Error deleting s3 obj: {ce}"
            log.error(msg)
            raise HTTPInternalServerError()
        except CancelledError as cle:
            self._s3_stats_increment("error_count")
            msg = f"CancelledError deleting s3 obj {key}: {cle}"
            log.error(msg)
            raise HTTPInternalServerError()
        except Exception as e:
            self._s3_stats_increment("error_count")
            msg = f"Unexpected Exception {type(e)} deleting s3 obj {key}: {e}"
            log.error(msg)
            raise HTTPInternalServerError() 
开发者ID:HDFGroup,项目名称:hsds,代码行数:37,代码来源:s3Client.py

示例15: get_key_stats

# 需要导入模块: from aiohttp import web_exceptions [as 别名]
# 或者: from aiohttp.web_exceptions import HTTPNotFound [as 别名]
def get_key_stats(self, key, bucket=None):
        if not await self.is_object(key, bucket):
            log.warn(f"get_key_stats - key: {key} not found")
            raise HTTPNotFound()
        filepath = self._getFilePath(bucket, key)
        key_stats = self._getFileStats(filepath)

        return key_stats 
开发者ID:HDFGroup,项目名称:hsds,代码行数:10,代码来源:fileClient.py


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