當前位置: 首頁>>代碼示例>>Python>>正文


Python exceptions.BadRequest方法代碼示例

本文整理匯總了Python中werkzeug.exceptions.BadRequest方法的典型用法代碼示例。如果您正苦於以下問題:Python exceptions.BadRequest方法的具體用法?Python exceptions.BadRequest怎麽用?Python exceptions.BadRequest使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在werkzeug.exceptions的用法示例。


在下文中一共展示了exceptions.BadRequest方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: on_json_loading_failed

# 需要導入模塊: from werkzeug import exceptions [as 別名]
# 或者: from werkzeug.exceptions import BadRequest [as 別名]
def on_json_loading_failed(self, e):
        """Called if :meth:`get_json` parsing fails and isn't silenced. If
        this method returns a value, it is used as the return value for
        :meth:`get_json`. The default implementation raises a
        :class:`BadRequest` exception.

        .. versionchanged:: 0.10
           Raise a :exc:`BadRequest` error instead of returning an error
           message as JSON. If you want that behavior you can add it by
           subclassing.

        .. versionadded:: 0.8
        """
        if current_app is not None and current_app.debug:
            raise BadRequest('Failed to decode JSON object: {0}'.format(e))

        raise BadRequest() 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:19,代碼來源:wrappers.py

示例2: on_json_loading_failed

# 需要導入模塊: from werkzeug import exceptions [as 別名]
# 或者: from werkzeug.exceptions import BadRequest [as 別名]
def on_json_loading_failed(self, e):
        """Called if decoding of the JSON data failed.  The return value of
        this method is used by :meth:`get_json` when an error occurred.  The
        default implementation just raises a :class:`BadRequest` exception.

        .. versionchanged:: 0.10
           Removed buggy previous behavior of generating a random JSON
           response.  If you want that behavior back you can trivially
           add it by subclassing.

        .. versionadded:: 0.8
        """
        ctx = _request_ctx_stack.top
        if ctx is not None and ctx.app.config.get('DEBUG', False):
            raise BadRequest('Failed to decode JSON object: {0}'.format(e))
        raise BadRequest() 
開發者ID:jpush,項目名稱:jbox,代碼行數:18,代碼來源:wrappers.py

示例3: parse_protobuf

# 需要導入模塊: from werkzeug import exceptions [as 別名]
# 或者: from werkzeug.exceptions import BadRequest [as 別名]
def parse_protobuf(self, proto_type):
        """Parse the data into an instance of proto_type."""
        if 'protobuf' not in self.environ.get('CONTENT_TYPE', ''):
            raise BadRequest('Not a Protobuf request')

        obj = proto_type()
        try:
            obj.ParseFromString(self.data)
        except Exception:
            raise BadRequest("Unable to parse Protobuf request")

        # Fail if not all required fields are set
        if self.protobuf_check_initialization and not obj.IsInitialized():
            raise BadRequest("Partial Protobuf request")

        return obj 
開發者ID:jpush,項目名稱:jbox,代碼行數:18,代碼來源:wrappers.py

示例4: validate_json

# 需要導入模塊: from werkzeug import exceptions [as 別名]
# 或者: from werkzeug.exceptions import BadRequest [as 別名]
def validate_json(f):
    """Validate that the call is JSON."""
    @wraps(f)
    def wrapper(*args, **kw):
        instance = args[0]
        try:
            if request.get_json() is None:
                ret_dict = instance._create_ret_object(instance.FAILURE,
                                                       None, True,
                                                       instance.MUST_JSON)
                instance.logger.error(instance.MUST_JSON)
                return jsonify(ret_dict), 400
        except BadRequest:
            ret_dict = instance._create_ret_object(instance.FAILURE, None,
                                                   True,
                                                   instance.MUST_JSON)
            instance.logger.error(instance.MUST_JSON)
            return jsonify(ret_dict), 400
        instance.logger.debug("JSON is valid")
        return f(*args, **kw)
    return wrapper 
開發者ID:istresearch,項目名稱:scrapy-cluster,代碼行數:23,代碼來源:rest_service.py

示例5: _decode_jwt_from_json

# 需要導入模塊: from werkzeug import exceptions [as 別名]
# 或者: from werkzeug.exceptions import BadRequest [as 別名]
def _decode_jwt_from_json(request_type):
    if request.content_type != 'application/json':
        raise NoAuthorizationError('Invalid content-type. Must be application/json.')

    if request_type == 'access':
        token_key = config.json_key
    else:
        token_key = config.refresh_json_key

    try:
        encoded_token = request.json.get(token_key, None)
        if not encoded_token:
            raise BadRequest()
    except BadRequest:
        raise NoAuthorizationError('Missing "{}" key in json data.'.format(token_key))

    return encoded_token, None 
開發者ID:vimalloc,項目名稱:flask-jwt-extended,代碼行數:19,代碼來源:view_decorators.py

示例6: plug_vip

# 需要導入模塊: from werkzeug import exceptions [as 別名]
# 或者: from werkzeug.exceptions import BadRequest [as 別名]
def plug_vip(self, vip):
        # Catch any issues with the subnet info json
        try:
            net_info = flask.request.get_json()
            assert type(net_info) is dict
            assert 'subnet_cidr' in net_info
            assert 'gateway' in net_info
            assert 'mac_address' in net_info
        except Exception:
            raise exceptions.BadRequest(
                description='Invalid subnet information')
        return self._plug.plug_vip(vip,
                                   net_info['subnet_cidr'],
                                   net_info['gateway'],
                                   net_info['mac_address'],
                                   net_info.get('mtu'),
                                   net_info.get('vrrp_ip'),
                                   net_info.get('host_routes')) 
開發者ID:openstack,項目名稱:octavia,代碼行數:20,代碼來源:server.py

示例7: parse

# 需要導入模塊: from werkzeug import exceptions [as 別名]
# 或者: from werkzeug.exceptions import BadRequest [as 別名]
def parse(cls, content_range):
        """
        Parse Content-Range header.
        Format is "bytes 0-524287/2000000".
        """
        range_type, range_count = content_range.split(' ', 1)
        # There are no other types then "bytes"
        if range_type != 'bytes':
            raise BadRequest

        range_count, range_complete = range_count.split('/', 1)
        range_begin, range_end = range_count.split('-', 1)

        range_begin = int(range_begin)
        range_end = int(range_end)
        range_complete = int(range_complete)

        if range_begin <= range_end < range_complete:
            return ContentRange(range_begin, range_end, range_complete)

        raise BadRequest 
開發者ID:bepasty,項目名稱:bepasty-server,代碼行數:23,代碼來源:http.py

示例8: test_contentrange_parse

# 需要導入模塊: from werkzeug import exceptions [as 別名]
# 或者: from werkzeug.exceptions import BadRequest [as 別名]
def test_contentrange_parse():
    r = ContentRange.parse('bytes 0-0/2')
    assert r.begin == 0
    assert r.end == 0
    assert r.complete == 2
    assert r.size == 1
    assert not r.is_complete

    r = ContentRange.parse('bytes 0-1/2')
    assert r.begin == 0
    assert r.end == 1
    assert r.complete == 2
    assert r.size == 2
    assert r.is_complete

    with pytest.raises(BadRequest):
        ContentRange.parse('test 0-1/2')

    with pytest.raises(BadRequest):
        ContentRange.parse('bytes 1-0/2')

    with pytest.raises(BadRequest):
        ContentRange.parse('bytes 0-2/2') 
開發者ID:bepasty,項目名稱:bepasty-server,代碼行數:25,代碼來源:test_http.py

示例9: test_verify_authorized_decorator_ignores_raised_exception

# 需要導入模塊: from werkzeug import exceptions [as 別名]
# 或者: from werkzeug.exceptions import BadRequest [as 別名]
def test_verify_authorized_decorator_ignores_raised_exception(self):
        def do_authorize_stuff():
            post = Post(1)
            return self.pundit.authorize(post)

        @self.app.route('/test_authorize_admin_get')
        @verify_authorized
        def admin_get_post():
            g.user = {'id': 1, 'role': 'admin'}
            raise BadRequest()
            is_authorized = do_authorize_stuff()
            if is_authorized:
                return 'Success', 200
            else:
                return 'Forbidden', 403
        resp = self.client.get('/test_authorize_admin_get')
        eq_(resp.status_code, 400) 
開發者ID:anurag90x,項目名稱:flask-pundit,代碼行數:19,代碼來源:test_usage.py

示例10: test_verify_either_decorator_success_with_authorize

# 需要導入模塊: from werkzeug import exceptions [as 別名]
# 或者: from werkzeug.exceptions import BadRequest [as 別名]
def test_verify_either_decorator_success_with_authorize(self):
        def do_authorize_stuff():
            post = Post(1)
            return self.pundit.authorize(post)

        @self.app.route('/test_authorize_admin_get')
        @verify_authorized_or_policy_scoped
        def admin_get_post():
            g.user = {'id': 1, 'role': 'admin'}
            raise BadRequest()
            is_authorized = do_authorize_stuff()
            if is_authorized:
                return 'Success', 200
            else:
                return 'Forbidden', 403
        resp = self.client.get('/test_authorize_admin_get')
        eq_(resp.status_code, 400) 
開發者ID:anurag90x,項目名稱:flask-pundit,代碼行數:19,代碼來源:test_usage.py

示例11: post

# 需要導入模塊: from werkzeug import exceptions [as 別名]
# 或者: from werkzeug.exceptions import BadRequest [as 別名]
def post(self):
        """Generate audio embedding from input data"""
        result = {'status': 'error'}

        args = input_parser.parse_args()

        if not re.match("audio/.*wav", str(args['audio'].mimetype)):
            e = BadRequest()
            e.data = {'status': 'error', 'message': 'Invalid file type/extension'}
            raise e

        audio_data = args['audio'].read()

        # Getting the predictions
        preds = self.model_wrapper.predict(audio_data)

        # Aligning the predictions to the required API format
        result['embedding'] = preds.tolist()
        result['status'] = 'ok'

        return result 
開發者ID:IBM,項目名稱:MAX-Audio-Embedding-Generator,代碼行數:23,代碼來源:predict.py

示例12: _process_POST

# 需要導入模塊: from werkzeug import exceptions [as 別名]
# 或者: from werkzeug.exceptions import BadRequest [as 別名]
def _process_POST(self):
        original_url = self._make_absolute_url(request.args['original_url'])
        shortcut = request.form['shortcut'].strip()

        if not (set(shortcut) <= CUSTOM_SHORTCUT_ALPHABET):
            raise BadRequest('Invalid shortcut')

        result = register_shortcut(original_url, shortcut, session.user)

        if result.get('error'):
            kwargs = {'success': False, 'msg': self._get_error_msg(result)}
        else:
            kwargs = {'success': True, 'shorturl': result['short_url']}

        return jsonify_template('ursh_custom_shortener_page.html', render_plugin_template,
                                event=self.event, ursh_host=self.ursh_host, shortcut=shortcut,
                                original_url=original_url, submitted=True, **kwargs) 
開發者ID:indico,項目名稱:indico-plugins,代碼行數:19,代碼來源:controllers.py

示例13: sign

# 需要導入模塊: from werkzeug import exceptions [as 別名]
# 或者: from werkzeug.exceptions import BadRequest [as 別名]
def sign(dataset):
    dataset = get_dataset(dataset)
    require.dataset.update(dataset)
    data = request_data()
    if not data.get('file_name'):
        raise BadRequest("You need to give a file name")
    data['mime_type'] = data.get('mime_type') or 'application/octet-stream'
    # create a stub:
    source = extract_fileobj(dataset, fh=StringIO(),
                             file_name=data['file_name'],
                             mime_type=data['mime_type'])

    # generate a policy document to replace with actual content:
    res = generate_s3_upload_policy(source, data['file_name'],
                                    data['mime_type'])
    return jsonify(res) 
開發者ID:openspending,項目名稱:spendb,代碼行數:18,代碼來源:source.py

示例14: mapping_spotify

# 需要導入模塊: from werkzeug import exceptions [as 別名]
# 或者: from werkzeug.exceptions import BadRequest [as 別名]
def mapping_spotify():
    """Endpoint for getting MusicBrainz entities mapped to a Spotify URI."""
    uri = request.args.get("spotify_uri")
    if uri is None:
        raise BadRequest("`spotify_uri` argument is missing.")
    if not uri.startswith("spotify:album:"):
        raise BadRequest("Incorrect Spotify URI. Only albums are supported right now.")

    conn = psycopg2.connect(**current_app.config["PG_INFO"])
    cur = conn.cursor()

    cur.execute("""
        SELECT mbid::text
          FROM mapping
         WHERE is_deleted = FALSE AND spotify_uri = %s
    """, (uri,))

    return jsonify({
        "mappings": [row[0] for row in cur.fetchall()],
    }) 
開發者ID:metabrainz,項目名稱:mbspotify,代碼行數:22,代碼來源:views.py

示例15: mapping_jsonp

# 需要導入模塊: from werkzeug import exceptions [as 別名]
# 或者: from werkzeug.exceptions import BadRequest [as 別名]
def mapping_jsonp(mbid):
    if not validate_uuid(mbid):
        raise BadRequest("Incorrect MBID (UUID).")

    conn = psycopg2.connect(**current_app.config["PG_INFO"])
    cur = conn.cursor()

    cur.execute("SELECT mbid, spotify_uri "
                "FROM mapping "
                "WHERE is_deleted = FALSE AND mbid = %s",
                (mbid,))
    if not cur.rowcount:
        return jsonify({})
    # TODO: Return all mappings to a specified MBID (don't forget to update userscript).
    row = cur.fetchone()
    return jsonify({mbid: row[1]}) 
開發者ID:metabrainz,項目名稱:mbspotify,代碼行數:18,代碼來源:views.py


注:本文中的werkzeug.exceptions.BadRequest方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。