示例#1
0
文件: app.py 项目: ushahidi/SiCDS
 def __call__(self, req):
     resp = None
     success = False
     try:
         if req.path_info not in self._routes:
             raise exc.HTTPNotFound
         if req.method != 'POST':
             raise exc.HTTPMethodNotAllowed(explanation='Only POST allowed')
         if req.content_length > self.REQMAXBYTES:
             req.logged_body = req.body_file.read(self.REQMAXBYTES) + '...'
             raise exc.HTTPRequestEntityTooLarge(explanation='Request max '
                 'size is {0} bytes'.format(self.REQMAXBYTES))
         reqjson = loads(req.body)
         req.logged_body = reqjson
         handler = self._routes[req.path_info]
         respjson = handler(self, reqjson)
         resp = Response(body=dumps(respjson), content_type='application/json')
         resp.logged_body = respjson
         success = True
     except Exception as e:
         if isinstance(e, exc.HTTPException):
             resp = e
         elif isinstance(e, (JSONDecodeError, SchemaError)):
             resp = exc.HTTPBadRequest(explanation=repr(e))
         else:
             resp = exc.HTTPInternalServerError(explanation=repr(e))
         resp.logged_body = resp.explanation
     finally:
         try:
             self.log(req, resp, success)
         except Exception as e:
             resp = exc.HTTPInternalServerError(explanation='Log failure: {0}\n'
                 'req: {1}\nresp: {2}'.format(repr(e), getattr(req, 'logged_body', None),
                 getattr(resp, 'logged_body', None)))
         return resp
示例#2
0
文件: wsgi.py 项目: ericgj/fungi
def build_error_response(e):
    # Exception -> HTTPError

    try:
        log.error('build_error_response: %s', unicode(e), extra={'error': e})
        if isinstance(e, exc.HTTPError) or isinstance(e, exc.HTTPRedirection):
            return e
        else:
            tmpl = '${explanation}<br/><br/><pre>${detail}</pre>${html_comment}'
            return exc.HTTPInternalServerError(
                detail=str(e), body_template=tmpl)  # Note: assumes ASCII repr

    except Exception as e_:
        return exc.HTTPInternalServerError(
            detail="Error in building error response", comment=str(e_))
示例#3
0
def reg(ctx, request: PigWeb.Request):
    payload = request.json
    print(payload, type(payload))
    email = payload.get('email')

    query = session.query(User).filter(User.email == email).first()
    if query:
        raise exc.HTTPConflict()

    user = User()
    try:
        user.name = payload['name']
        user.email = email
        user.password = bcrypt.hashpw(payload['password'].encode(),
                                      bcrypt.gensalt())
    except Exception as e:
        print(e)
        raise exc.HTTPBadRequest()

    session.add(user)
    try:
        session.commit()
        return jsonify(user={
            'id': user.id,
            'name': user.name
        },
                       token=gen_token(user.id))
    except Exception as e:
        session.rollback()
        raise exc.HTTPInternalServerError()
示例#4
0
    def _migrate_live(self, req, id, body):
        """Permit admins to (live) migrate a server to a new host."""
        context = req.environ["nova.context"]
        authorize(context, 'migrateLive')

        try:
            block_migration = body["os-migrateLive"]["block_migration"]
            disk_over_commit = body["os-migrateLive"]["disk_over_commit"]
            host = body["os-migrateLive"]["host"]
        except (TypeError, KeyError):
            msg = _("host, block_migration and disk_over_commit must "
                    "be specified for live migration.")
            raise exc.HTTPBadRequest(explanation=msg)

        try:
            block_migration = strutils.bool_from_string(block_migration,
                                                        strict=True)
            disk_over_commit = strutils.bool_from_string(disk_over_commit,
                                                         strict=True)
        except ValueError as err:
            raise exc.HTTPBadRequest(explanation=six.text_type(err))

        instance = common.get_instance(self.compute_api,
                                       context,
                                       id,
                                       want_objects=True)
        try:
            self.compute_api.live_migrate(context, instance, block_migration,
                                          disk_over_commit, host)
        except (exception.NoValidHost, exception.ComputeServiceUnavailable,
                exception.InvalidHypervisorType, exception.InvalidCPUInfo,
                exception.UnableToMigrateToSelf,
                exception.DestinationHypervisorTooOld,
                exception.InvalidLocalStorage, exception.InvalidSharedStorage,
                exception.HypervisorUnavailable,
                exception.MigrationPreCheckError,
                exception.LiveMigrationWithOldNovaNotSafe) as ex:
            raise exc.HTTPBadRequest(explanation=ex.format_message())
        except exception.InstanceNotFound as e:
            raise exc.HTTPNotFound(explanation=e.format_message())
        except exception.InstanceIsLocked as e:
            raise exc.HTTPConflict(explanation=e.format_message())
        except exception.InstanceInvalidState as state_error:
            common.raise_http_conflict_for_instance_invalid_state(
                state_error, 'os-migrateLive', id)
        except Exception:
            if host is None:
                msg = _("Live migration of instance %s to another host "
                        "failed") % id
            else:
                msg = _("Live migration of instance %(id)s to host %(host)s "
                        "failed") % {
                            'id': id,
                            'host': host
                        }
            LOG.exception(msg)
            # Return messages from scheduler
            raise exc.HTTPInternalServerError(explanation=msg)

        return webob.Response(status_int=202)
示例#5
0
文件: comment.py 项目: skyddv/blog
def add_comment(ctx, request):
    try:
        payload = request.json()
        pid = payload['post']
        ref_id = payload.get('ref')
        content = payload['content']
    except Exception as e:
        raise exc.HTTPBadRequest(e)

    post = Post.query.filter(Post.id == pid).first_or_404(
        'post {} not found'.format(pid))
    ref = None
    if ref_id is not None:
        ref = Comment.query.filter(Comment.id == ref_id).first()
    comment = Comment(content=content,
                      user=request.principal.id,
                      ref=ref.id,
                      post=pid,
                      timestamp=datetime.datetime.now())
    db.session.add(comment)
    try:
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        raise exc.HTTPInternalServerError(e)
    return jsonify(
        code=200,
        comment=comment.dictify(exclude={'user.password', 'user.catalogs'}))
示例#6
0
    def create_plan_by_template(self, req, body):

        LOG.debug("Create a plan by template")

        if not self.is_valid_body(body, 'plan'):
            msg = _("Incorrect request body format.")
            raise exc.HTTPBadRequest(explanation=msg)

        context = req.environ['conveyor.context']

        tpl_param = body['plan'].get('template')
        if not tpl_param:
            msg = _('No template found in body.')
            raise exc.HTTPBadRequest(explanation=msg)

        template = self._convert_template_to_json(tpl_param)

        plan_type = template.get('plan_type')

        if not plan_type:
            msg = _("Template must have 'plan_type' field.")
            raise exc.HTTPBadRequest(explanation=msg)

        try:
            plan_name = body['plan'].get('plan_name', None)
            plan = self._plan_api.create_plan_by_template(context,
                                                          template,
                                                          plan_name=plan_name)
            return {"plan": plan}
        except Exception as e:
            LOG.error(unicode(e))
            raise exc.HTTPInternalServerError(explanation=unicode(e))
示例#7
0
文件: post.py 项目: PubFork/Myrepo
def list(ctx,request:YuHeLg.Request):
    page = vaildate(request.params,"page",int,1,lambda x,y:x if x >0 and x<101 else y)
    size = vaildate(request.params,"size",int,20,lambda x,y:x if x >0 and x<101 else y)

    #size 这里是运行浏览器端改变的,但是要控制范围。也可以不让浏览器端改变

    query = session.query(Post)
    try:
        user_id = vaildate({"user_id":request.vars.id},"user_id",int,-1,lambda x,y:x if x >0 else y )
    except:
        user_id = -1

    if user_id>0:
        query = query.filter(Post.author_id == user_id)

    try:
        count = query.count()
        posts = query.order_by(Post.id.desc()).limit(size).offset((page-1)*size).all() #offset偏移量丛集开始取

        return jsonify(posts=[{
            "post_id":post.id,
            "title":post.title
        } for post in posts],
        page_infos={
            "page":page,
            "size":size,
            "count":count,
            "pages":math.ceil(count/size)
        })
    except Exception as e:
        print(e)
        raise exc.HTTPInternalServerError()
示例#8
0
    def create(self, req, body):
        """Create a new backup."""
        LOG.debug(_('Creating new backup %s'), body)
        if not self.is_valid_body(body, 'backup'):
            raise exc.HTTPBadRequest()

        context = req.environ['cinder.context']

        try:
            backup = body['backup']
            volume_id = backup['volume_id']
        except KeyError:
            msg = _("Incorrect request body format")
            raise exc.HTTPBadRequest(explanation=msg)
        container = backup.get('container', None)
        name = backup.get('name', None)
        description = backup.get('description', None)

        LOG.audit(_("Creating backup of volume %(volume_id)s in container"
                    " %(container)s"),
                  {'volume_id': volume_id, 'container': container},
                  context=context)

        try:
            new_backup = self.backup_api.create(context, name, description,
                                                volume_id, container)
        except exception.InvalidVolume as error:
            raise exc.HTTPBadRequest(explanation=error.msg)
        except exception.VolumeNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)
        except exception.ServiceNotFound as error:
            raise exc.HTTPInternalServerError(explanation=error.msg)

        retval = self._view_builder.summary(req, dict(new_backup.iteritems()))
        return retval
示例#9
0
 def json_engine(self, req):  # pylint: disable=R0201,W0613
     """ Return torrent engine data.
     """
     try:
         return stats.engine_data(config.engine)
     except (error.LoggableError, xmlrpc.ERRORS), torrent_exc:
         raise exc.HTTPInternalServerError(str(torrent_exc))
示例#10
0
文件: leak.py 项目: saaj/dozer
    def __call__(self, environ, start_response):
        assert not environ['wsgi.multiprocess'], (
            "Dozer middleware is not usable in a "
            "multi-process environment")
        req = Request(environ)
        req.base_path = req.application_url + self.path
        if (req.path_info.startswith(self.path+'/')
            or req.path_info == self.path):
            req.script_name += self.path
            req.path_info = req.path_info[len(self.path):]
            try:
                return self.dowse(req)(environ, start_response)
            except Exception as ex:
                error_text = traceback.format_exc()

                acceptable_offers = req.accept.acceptable_offers(
                    offers=['text/html', 'application/json']
                )
                match = acceptable_offers[0][0] if acceptable_offers else None
                if match != 'application/json':
                    # Strangely, webob.exc.WSGIHTTPException.plain_body replaces newlines
                    # to spaces for plain/text, but replaces "<br/>" tags to newlines.
                    error_text = error_text.replace('\n', '<br/>')

                return exc.HTTPInternalServerError(
                    str(ex), body_template=error_text
                )(environ, start_response)
        else:
            return self.app(environ, start_response)
示例#11
0
    def handle_exception(self, request, e, exc_info=None):
        """
        Handles an exception within the application.
        If a corresponding handler is registered with the application
        we call that otherwise a generic message is displayed.
        """
        from webob import exc
        if isinstance(e, exc.HTTPException):
            if isinstance(e, exc.HTTPServerError):
                logger.error('HTTP Server Error: "%s"' % e, exc_info=1)
            status = e.code
        else:
            # If in debug mode show the debug error page.
            if self.config['DEBUG']:
                # Raise the error for the debugger.
                if exc_info[1] is e:
                    # If the exception is the original exception raise it.
                    # so the debugger shows the right traceback.
                    raise exc_info[0], exc_info[1], exc_info[2]
                else:
                    # The exception passed is different from the exc_info
                    # so just re-raise it.
                    raise e

            # Otherwise return a normal HttpInternalServerError
            logger.error('Internal Server Error: "%s"' % e, exc_info=1)
            status = 500
            e = exc.HTTPInternalServerError()

        handler = self._error_handlers.get(status)
        if handler:
            return self.make_response(request, handler(e))
        else:
            return self.make_response(request, e)
示例#12
0
文件: post.py 项目: PubFork/Myrepo
def pub(ctx,request:YuHeLg.Request):
    payload = request.json
    post = Post()
    try:
        post.title = payload.get("title")
        post.author_id = request.user.id
        post.postdate = datetime.datetime.now()
        cont = Content()
        cont.content = payload.get("content")
        post.content = cont
        tags = payload["tags"]
    except Exception as e:
        print(e)
        raise exc.HTTPBadRequest()

    taglist = re.split('[\s,]',tags)
    for tag in taglist:
        t = session.query(Tag).filter(Tag.tag == tag).first()
        if t is None:
            t = Tag()
            t.tag = tag
            session.add(t)
        pt = Post_tag()
        pt.tag = t
        pt.post = post
        session.add(pt)

    session.add(post)
    try:
        session.commit()
        return jsonify(post_id=post.id)
    except:
        session.rollback()
        raise exc.HTTPInternalServerError()
示例#13
0
def list(ctx, request: EmulateWeb.Request):
    '''query blogs in database, user can set the page and the number of blogs in each page'''

    # try:
    #     page = int(request.params.get('page', 1))
    #     page = page if page > 0 else 1
    # except:
    #     page = 1
    page = getparam(request.params, 'page', int, 1, lambda x, y: x
                    if x > 0 else y)
    size = getparam(request.params, 'size', int, 10, lambda x, y: x
                    if x > 0 and x < 31 else y)

    try:
        count = session.query(PostBlog).count()
        blogs = session.query(PostBlog).order_by(
            PostBlog.id.desc()).limit(size).offset(size * (page - 1)).all()
        return jsonify(blogs=[{
            'blog_id': blog.id,
            'title': blog.title,
        } for blog in blogs],
                       page_info={
                           'page': page,
                           'size': size,
                           'count': count,
                           'pages': math.ceil(count / size)
                       })
    except Exception as e:
        print(e)
        raise exc.HTTPInternalServerError()
示例#14
0
    def start_handle_request(self, app, environ, start_response, services_service):
        websocket = self.create_websocket(environ)
        if websocket is not None:
            environ.pop('set_websocket')(websocket, environ)

        request = app.create_request(environ)

        try:
            request.params, request.url
        except UnicodeDecodeError:
            response = exc.HTTPClientError()
        else:
            try:
                if websocket is not None:
                    def start_response(status, headers, sr=start_response):
                        sr(status, headers + [('Content-length', '0')])

                response = services_service(
                    super(Publisher, self).start_handle_request,
                    app,
                    request=request,
                    start_response=start_response,
                    response=app.create_response(request),
                    websocket=websocket
                )

                if websocket is not None:
                    response = self.websocket_app(['binary'], handler_cls=self.websocket_handler)
            except exc.HTTPException as e:
                response = e
            except Exception:
                self.logger.critical('Unhandled exception', exc_info=True)
                response = exc.HTTPInternalServerError()

        return [] if response is None else response(environ, start_response)
示例#15
0
    def action(self, req, tenant_id, stack_name, stack_id, body=None):
        """Performs a specified action on a stack.

        The body is expecting to contain exactly one item whose key specifies
        the action.
        """
        body = body or {}
        if len(body) < 1:
            raise exc.HTTPBadRequest(_("No action specified"))

        if len(body) > 1:
            raise exc.HTTPBadRequest(_("Multiple actions specified"))

        ac = next(six.iterkeys(body))
        if ac not in self.ACTIONS:
            raise exc.HTTPBadRequest(_("Invalid action %s specified") % ac)

        do_action = getattr(self, ac, None)
        if do_action is None:
            raise exc.HTTPInternalServerError(_("Unexpected action %s") % ac)

        do_action(req,
                  tenant_id=tenant_id,
                  stack_name=stack_name,
                  stack_id=stack_id,
                  body=body)
示例#16
0
    def instances_show(self, req, protectable_type, protectable_id):
        """Return a instance about the given protectable_type and id."""

        context = req.environ['karbor.context']
        params = req.params.copy()
        utils.check_filters(params)
        parameters = params.get("parameters", None)

        LOG.info("Show the instance of a given protectable type: %s",
                 protectable_type)

        if parameters is not None:
            if not isinstance(parameters, dict):
                msg = _("The parameters must be a dict.")
                raise exception.InvalidInput(reason=msg)

        protectable_types = self._get_all(context)

        if protectable_type not in protectable_types:
            msg = _("Invalid protectable type provided.")
            raise exception.InvalidInput(reason=msg)

        context.can(protectable_policy.INSTANCES_GET_POLICY)
        try:
            instance = self.protection_api.show_protectable_instance(
                context,
                protectable_type,
                protectable_id,
                parameters=parameters)
        except exception.ProtectableResourceNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)
        except Exception as err:
            raise exc.HTTPInternalServerError(explanation=six.text_type(err))

        if instance is None:
            msg = _("The instance doesn't exist.")
            raise exc.HTTPInternalServerError(explanation=msg)

        dependents = self.protection_api.list_protectable_dependents(
            context, protectable_id, protectable_type,
            instance.get("name", None))
        instance["dependent_resources"] = dependents

        retval_instance = self._view_builder.detail(req, instance)
        return retval_instance
示例#17
0
 def __call__(self, environ, start_response):
     req = Request(environ)
     method = req.method
     try:
         handle_method = getattr(self, 'handle_'+method)
     except:
         raise exc.HTTPInternalServerError('No %s method on resource: %s' %(method,object))
     resp = handle_method(req)
     return resp(environ, start_response)