Python flask.request.data() Examples

The following are 30 code examples of flask.request.data(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.request , or try the search function .
Example #1
Source File: app.py    From wechatpy with MIT License 7 votes vote down vote up
def wechat():
    signature = request.args.get("msg_signature", "")
    timestamp = request.args.get("timestamp", "")
    nonce = request.args.get("nonce", "")

    crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId)
    if request.method == "GET":
        echo_str = request.args.get("echostr", "")
        try:
            echo_str = crypto.check_signature(signature, timestamp, nonce, echo_str)
        except InvalidSignatureException:
            abort(403)
        return echo_str
    else:
        try:
            msg = crypto.decrypt_message(request.data, signature, timestamp, nonce)
        except (InvalidSignatureException, InvalidCorpIdException):
            abort(403)
        msg = parse_message(msg)
        if msg.type == "text":
            reply = create_reply(msg.content, msg).render()
        else:
            reply = create_reply("Can not handle this for now", msg).render()
        res = crypto.encrypt_message(reply, nonce, timestamp)
        return res 
Example #2
Source File: webhook.py    From ServerSan with Apache License 2.0 7 votes vote down vote up
def create():
    try:
        d = json.loads(request.data)
    except ValueError:
        return json.dumps({'status': 1, 'info': 'request failed.'})

    current_ts = time.time()
    _id = False
    d.update(timestamp=current_ts)

    perm = ts_can_insert(d.get('auth'), current_ts) and token_can_insert(d.get('auth'))

    if perm:
        _id = col.insert_one(d).inserted_id
    if _id:
        return json.dumps({'status': 0, 'info': 'success'})
    else:
        return json.dumps({'status': 2, 'info': 'op too frequent or invalid token.'}) 
Example #3
Source File: did.py    From rucio with Apache License 2.0 6 votes vote down vote up
def get(self, scope, name):
        """
        Return all associated rules of a file.

        .. :quickref: AssociatedRules; List associated rules of DID.

        :resheader Content-Type: application/x-json-stream
        :param scope: The scope of the data identifier.
        :param name: The name of the data identifier.
        :status 200: DID found
        :status 401: Invalid Auth Token
        :status 404: DID not found
        :status 406: Not Acceptable
        :status 500: Database Exception
        :returns: List of associated rules.
        """
        try:
            data = ""
            for rule in list_associated_replication_rules_for_file(scope=scope, name=name):
                data += dumps(rule, cls=APIEncoder) + '\n'
            return Response(data, content_type="application/x-json-stream")
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            return error, 500 
Example #4
Source File: router.py    From maple-file with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def delete(self, pk):
        '''
        删除图片
        '''
        user = request.user
        image = Image.query.filter_by(id=pk, user=user).get_or_404('图片不存在')
        serializer = ImageSerializer(image)
        img_path = os.path.join(current_app.config['UPLOAD_FOLDER_ROOT'],
                                image.url)
        # 删除原图
        if os.path.exists(img_path):
            os.remove(img_path)
        # 删除缩略图
        thumb_path = os.path.join(current_app.config['UPLOAD_FOLDER_ROOT'],
                                  image.url.replace('photo', 'thumb'))
        if os.path.exists(thumb_path):
            os.remove(thumb_path)
        image.delete()
        return HTTP.OK(data=serializer.data) 
Example #5
Source File: router.py    From maple-file with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def put(self, pk):
        '''
        修改图片信息
        '''
        post_data = request.data
        user = request.user
        name = post_data.pop('name', None)
        description = post_data.pop('description', None)
        image = Image.query.filter_by(id=pk, user=user).get_or_404('图片不存在')
        if name is not None:
            image.name = name
            image.url = os.path.join(image.path, name)
        if description is not None:
            image.description = description
        image.save()
        serializer = ImageSerializer(image)
        return HTTP.OK(data=serializer.data) 
Example #6
Source File: lifetime_exception.py    From rucio with Apache License 2.0 6 votes vote down vote up
def get(self):
        """
        Retrieve all exceptions.

        .. :quickref: LifetimeException; Get all exceptions.

        :resheader Content-Type: application/x-json-stream
        :status 200: OK.
        :status 401: Invalid Auth Token.
        :status 404: Lifetime Exception Not Found.
        :status 406: Not Acceptable.
        :status 500: Internal Error.
        """
        try:
            data = ""
            for exception in list_exceptions():
                data += dumps(exception, cls=APIEncoder) + '\n'
            return Response(data, content_type="application/x-json-stream")
        except LifetimeExceptionNotFound as error:
            return generate_http_error_flask(404, 'LifetimeExceptionNotFound', error.args[0])
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            return error, 500 
Example #7
Source File: router.py    From maple-file with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get(self):
        '''
        获取图片列表
        '''
        query_dict = request.data
        user = request.user
        page, number = self.page_info
        keys = ['name', 'description']
        order_by = gen_order_by(query_dict, keys)
        filter_dict = gen_filter_dict(query_dict, keys, user=user)
        album = query_dict.pop('album', None)
        if album is not None:
            filter_dict.update(album__id=album)
        images = Image.query.filter_by(
            **filter_dict).order_by(*order_by).paginate(page, number)
        serializer = ImageSerializer(images.items, True)
        pageinfo = PageInfo(images)
        return HTTP.OK(data=serializer.data, pageinfo=pageinfo) 
Example #8
Source File: router.py    From maple-file with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def put(self, pk):
        '''
        修改相册
        '''
        post_data = request.data
        user = request.user
        name = post_data.pop('name', None)
        description = post_data.pop('description', None)
        album = Album.query.filter_by(id=pk, user=user).get_or_404('相册不存在')
        if name is not None:
            album.name = name
        if description is not None:
            album.description = description
        album.save()
        serializer = AlbumSerializer(album)
        album.delete()
        return HTTP.OK(data=serializer.data) 
Example #9
Source File: subscription.py    From rucio with Apache License 2.0 6 votes vote down vote up
def get(self, account=None, name=None):
        """
        Retrieve a subscription.

        .. :quickref: Subscription; Get subscriptions.

        :param account: The account name.
        :param name: The subscription name.
        :resheader Content-Type: application/x-json-stream
        :status 200: OK.
        :status 401: Invalid Auth Token.
        :status 404: Subscription Not Found.
        :status 406: Not Acceptable.
        :status 500: Internal Error.
        :returns: Line separated list of dictionaries with subscription information.
        """
        try:
            data = ""
            for subscription in list_subscriptions(name=name, account=account):
                data += dumps(subscription, cls=APIEncoder) + '\n'
            return Response(data, content_type="application/x-json-stream")
        except SubscriptionNotFound as error:
            return generate_http_error_flask(404, 'SubscriptionNotFound', error.args[0])
        except Exception as error:
            return error, 500 
Example #10
Source File: router.py    From maple-file with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def post(self):
        '''
        新建相册
        '''
        post_data = request.data
        user = request.user
        name = post_data.pop('name', None)
        description = post_data.pop('description', None)
        if name is None:
            return HTTP.BAD_REQUEST(message='相册名称不能为空')
        album = Album(name=name, user=user)
        if description is not None:
            album.description = description
        album.save()
        serializer = AlbumSerializer(album)
        return HTTP.OK(data=serializer.data) 
Example #11
Source File: replica.py    From rucio with Apache License 2.0 6 votes vote down vote up
def get(self, scope, name):
        """
        List dataset replicas.

        .. :quickref: DatasetReplicas; List dataset replicas.

        :query deep: Flag to ennable lookup at the file level.
        :resheader Content-Type: application/x-json-stream
        :status 200: OK.
        :status 401: Invalid auth token.
        :status 406: Not Acceptable.
        :status 500: Internal Error.
        :returns: A dictionary containing all replicas information.
        """
        deep = request.args.get('deep', False)
        try:
            data = ""
            for row in list_dataset_replicas(scope=scope, name=name, deep=deep):
                data += dumps(row, cls=APIEncoder) + '\n'
            return Response(data, content_type='application/x-json-stream')
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            return error, 500 
Example #12
Source File: app.py    From dataiku-contrib with Apache License 2.0 6 votes vote down vote up
def get_token():
    
    # Read in the existing conf
    dss = dataiku.api_client()
    project = dss.get_project(dataiku.default_project_key())
    variables = project.get_variables()["standard"]
    conf = variables.get("powerbi-settings", None)   
    
    # Decrypt
    key = request.args.get("api-key")
    pbi = {}
    pbi["username"]      = conf["username"]
    pbi["password"]      = decrypt_string(conf["password"], key)
    pbi["client_id"]     = conf["client_id"]
    pbi["client_secret"] = decrypt_string(conf["client_secret"], key)
    pbi["resource"]      = conf["resource"]
    pbi["grant_type"]    = conf["grant_type"]
    pbi["scope"]         = conf["scope"]
    
    # Get the token
    response = requests.post('https://login.microsoftonline.com/common/oauth2/token', data=pbi)
    o = {}
    o["token"] = response.json().get("access_token") 
    
    return json.dumps(o) 
Example #13
Source File: app.py    From dataiku-contrib with Apache License 2.0 6 votes vote down vote up
def display_new_token():    
    data = {
        "username"     : request.args.get("powerbi-username"),
        "password"     : request.args.get("powerbi-password"),
        "client_id"    : request.args.get("powerbi-client-id"),
        "client_secret": request.args.get("powerbi-client-secret"),
        "resource"     : request.args.get("powerbi-resource",   "https://analysis.windows.net/powerbi/api"),
        "grant_type"   : request.args.get("powerbi-grant-type", "password"),
        "scope"        : request.args.get("powerbi-scope",      "openid")
    }
    response = requests.post('https://login.microsoftonline.com/common/oauth2/token', data=data)
    o = {}
    #o["powerbi-auth-response"] = response.json()
    o["powerbi-access-token"] = response.json().get("access_token")    
    return json.dumps(o)


# Helper functions to interact with DSS Project Variables 
Example #14
Source File: views.py    From social-relay with GNU Affero General Public License v3.0 6 votes vote down vote up
def receive_public():
    if not request.data:
        return abort(404)

    # Queue to rq for processing
    public_queue.enqueue("workers.receive.process", request.data, timeout=app.config.get("RELAY_WORKER_TIMEOUT"))

    # Log statistics
    log_receive_statistics(request.remote_addr)

    # return 200 whatever
    data = {
        'result': 'ok',
    }
    js = json.dumps(data)
    return Response(js, status=200, mimetype='application/json') 
Example #15
Source File: subscription.py    From rucio with Apache License 2.0 6 votes vote down vote up
def get(self, name=None):
        """
        Retrieve a subscription by name.

        .. :quickref: SubscriptionName; Get subscriptions by name.

        :param name: The subscription name.
        :resheader Content-Type: application/x-json-stream
        :status 200: OK.
        :status 401: Invalid Auth Token.
        :status 404: Subscription Not Found.
        :status 406: Not Acceptable.
        :status 500: Internal Error.
        :returns: Line separated list of dictionaries with subscription information.
        """
        try:
            data = ""
            for subscription in list_subscriptions(name=name):
                data += dumps(subscription, cls=APIEncoder) + '\n'
            return Response(data, content_type="application/x-json-stream")
        except SubscriptionNotFound as error:
            return generate_http_error_flask(404, 'SubscriptionNotFound', error.args[0])
        except Exception as error:
            return error, 500 
Example #16
Source File: rule.py    From rucio with Apache License 2.0 6 votes vote down vote up
def get(self, rule_id):
        """ get locks for a given rule_id.

        .. :quickref: ReplicaLocks; get locks by rule id

        :status 200: Rule found
        :status 406: Not Acceptable
        :status 500: Database Exception
        :returns: JSON dict containing informations about the requested user.
        """
        try:
            locks = get_replica_locks_for_rule_id(rule_id)
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            return error, 500

        data = ""
        for lock in locks:
            data += dumps(lock, cls=APIEncoder) + '\n'

        return Response(data, content_type="application/x-json-stream") 
Example #17
Source File: rule.py    From rucio with Apache License 2.0 6 votes vote down vote up
def get(self, rule_id):
        """ get history for a given rule_id.

        .. :quickref: RuleHistory; get rule history by id

        :resheader Content-Type: application/x-json-stream
        :status 200: Rule found
        :status 406: Not Acceptable
        :status 500: Database Exception
        :returns: JSON dict containing informations about the requested user.
        """
        try:
            history = list_replication_rule_history(rule_id)
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            return error, 500

        data = ""
        for hist in history:
            data += dumps(hist, cls=APIEncoder) + '\n'
        return Response(data, content_type="application/x-json-stream") 
Example #18
Source File: did.py    From rucio with Apache License 2.0 5 votes vote down vote up
def delete(self, scope, name):
        """
        Detach data identifiers from data identifiers.

        .. :quickref: DIDs; Detach DID from DID.

        :param scope: Scope of the DID to detach from.
        :param name: Name of the DID to detach from.
        :<json dicts data: Must contain key 'dids' with list of dids to detach.
        :status 200: DIDs successfully detached
        :status 401: Invalid Auth Token
        :status 404: DID not found
        :status 500: Database Exception
        """

        try:
            json_data = loads(request.data)
            if 'dids' in json_data:
                dids = json_data['dids']
        except ValueError:
            return generate_http_error_flask(400, 'ValueError', 'Cannot decode json parameter list')

        try:
            detach_dids(scope=scope, name=name, dids=dids, issuer=request.environ.get('issuer'))
        except UnsupportedOperation as error:
            return generate_http_error_flask(409, 'UnsupportedOperation', error.args[0])
        except DataIdentifierNotFound as error:
            return generate_http_error_flask(404, 'DataIdentifierNotFound', error.args[0])
        except AccessDenied as error:
            return generate_http_error_flask(401, 'AccessDenied', error.args[0])
        except Exception as error:
            print(format_exc())
            return error, 500

        return "OK", 200 
Example #19
Source File: did.py    From rucio with Apache License 2.0 5 votes vote down vote up
def get(self, scope, name):
        """
        Returns the contents history of a data identifier.

        .. :quickref: AttachementHistory; List the content history of a DID.

        :resheader Content-Type: application/x-json-stream
        :param scope: The scope of the data identifier.
        :param name: The name of the data identifier.
        :status 200: DID found
        :status 401: Invalid Auth Token
        :status 404: DID not found
        :status 406: Not Acceptable
        :status 500: Database Exception
        :returns: Stream of dictionarys with DIDs
        """
        try:
            data = ""
            for did in list_content_history(scope=scope, name=name):
                data += render_json(**did) + '\n'
            return Response(data, content_type="application/x-json-stream")
        except DataIdentifierNotFound as error:
            return generate_http_error_flask(404, 'DataIdentifierNotFound', error.args[0])
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            return error, 500 
Example #20
Source File: did.py    From rucio with Apache License 2.0 5 votes vote down vote up
def get(self, scope, name):
        """ List all replicas of a data identifier.

        .. :quickref: Files; List replicas of DID.

        :resheader Content-Type: application/x-json-stream
        :param scope: The scope of the data identifier.
        :param name: The name of the data identifier.
        :query long: Flag to trigger long output
        :status 200: DID found
        :status 401: Invalid Auth Token
        :status 404: DID not found
        :status 406: Not Acceptable
        :status 500: Database Exception
        :returns: A dictionary containing all replicas information.
        """
        long = False

        if "long" in request.args:
            long = True
        try:
            data = ""
            for file in list_files(scope=scope, name=name, long=long):
                data += dumps(file) + "\n"
            return Response(data, content_type="application/x-json-stream")
        except DataIdentifierNotFound as error:
            return generate_http_error_flask(404, 'DataIdentifierNotFound', error.args[0])
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            return error, 500 
Example #21
Source File: replica.py    From rucio with Apache License 2.0 5 votes vote down vote up
def put(self):
        """
        Update a file replicas state at a given RSE.

        .. :quickref: Replicas; update replicas state.

        :<json string rse: The RSE name.
        :<json list files: list of dicts with 'scope', 'name' and 'state'.
        :status 201: Replica successfully updated.
        :status 400: Cannot decode json parameter list.
        :status 401: Invalid auth token.
        :status 500: Internal Error.
        """
        json_data = request.data
        try:
            parameters = parse_response(json_data)
        except ValueError:
            return generate_http_error_flask(400, 'ValueError', 'Cannot decode json parameter list')

        try:
            update_replicas_states(rse=parameters['rse'], files=parameters['files'], issuer=request.environ.get('issuer'))
        except AccessDenied as error:
            return generate_http_error_flask(401, 'AccessDenied', error.args[0])
        except UnsupportedOperation as error:
            return generate_http_error_flask(500, 'UnsupportedOperation', error.args[0])
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            return error, 500
        return 'OK', 200 
Example #22
Source File: did.py    From rucio with Apache License 2.0 5 votes vote down vote up
def post(self):
        """
        Attach DIDs to DIDs

        .. :quickref: Attachements; Attach DIDs to DIDs.
        """

        # To be moved in a common processor

        attachments, ignore_duplicate = [], False
        try:
            json_data = loads(request.data)
            if type(json_data) is dict:
                attachments = json_data.get('attachments')
                ignore_duplicate = json_data.get('ignore_duplicate')
            elif type(json_data) is list:
                attachments = json_data
        except ValueError:
            return generate_http_error_flask(400, 'ValueError', 'Cannot decode json parameter list')

        try:
            attach_dids_to_dids(attachments=attachments, ignore_duplicate=ignore_duplicate, issuer=request.environ.get('issuer'))
        except DataIdentifierNotFound as error:
            return generate_http_error_flask(404, 'DataIdentifierNotFound', error.args[0])
        except DuplicateContent as error:
            return generate_http_error_flask(409, 'DuplicateContent', error.args[0])
        except DataIdentifierAlreadyExists as error:
            return generate_http_error_flask(409, 'DataIdentifierAlreadyExists', error.args[0])
        except AccessDenied as error:
            return generate_http_error_flask(401, 'AccessDenied', error.args[0])
        except UnsupportedOperation as error:
            return generate_http_error_flask(409, 'UnsupportedOperation', error.args[0])
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            return error, 500

        return "Created", 201 
Example #23
Source File: rule.py    From rucio with Apache License 2.0 5 votes vote down vote up
def get(self, rule_id):
        """ get rule information for given rule id.

        .. :quickref: Rule; get rule info

        :returns: JSON dict containing informations about the requested user.
        :status 200: Rule found
        :status 406: Not Acceptable
        :status 410: Invalid Auth Token
        :status 404: no rule found for id
        """
        try:
            estimate_ttc = False
            json_data = request.data
            params = loads(json_data)
            if 'estimate_ttc' in params:
                estimate_ttc = params['estimate_ttc']
        except ValueError:
            estimate_ttc = False
        try:
            rule = get_replication_rule(rule_id, estimate_ttc=estimate_ttc)
        except RuleNotFound as error:
            return generate_http_error_flask(404, 'RuleNotFound', error.args[0])
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            return error, 500

        return Response(render_json(**rule), content_type="application/json") 
Example #24
Source File: lifetime_exception.py    From rucio with Apache License 2.0 5 votes vote down vote up
def get(self, exception_id):
        """
        Retrieve an exception.

        .. :quickref: LifetimeExceptionId; Get an exceptions.

        :param exception_id: The exception identifier.
        :resheader Content-Type: application/x-json-stream
        :status 200: OK.
        :status 401: Invalid Auth Token.
        :status 404: Lifetime Exception Not Found.
        :status 406: Not Acceptable.
        :status 500: Internal Error.
        :returns: List of exceptions.
        """
        try:
            data = ""
            for exception in list_exceptions(exception_id):
                data += dumps(exception, cls=APIEncoder) + '\n'

            return Response(data, content_type="application/x-json-stream")
        except LifetimeExceptionNotFound as error:
            return generate_http_error_flask(404, 'LifetimeExceptionNotFound', error.args[0])
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            return error, 500 
Example #25
Source File: replica.py    From rucio with Apache License 2.0 5 votes vote down vote up
def post(self):
        """
        Set a tombstone on a list of replicas.

        .. :quickref: Tombstone; Set a tombstone on a list of replicas.

        :<json string replicas: list fo replicas
        :resheader Content-Type: application/x-json-string
        :status 201: Created.
        :status 401: Invalid auth token.
        :status 404: ReplicaNotFound.
        :status 500: Internal Error.
        """

        json_data = request.data
        replicas = []

        try:
            params = parse_response(json_data)
            if 'replicas' in params:
                replicas = params['replicas']
        except ValueError:
            return generate_http_error_flask(400, 'ValueError', 'Cannot decode json parameter list')

        try:
            for replica in replicas:
                set_tombstone(replica['rse'], replica['scope'], replica['name'], issuer=request.environ.get('issuer'))
        except ReplicaNotFound as error:
            return generate_http_error_flask(404, 'ReplicaNotFound', error.args[0])
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            return error, 500
        return 'Created', 201 
Example #26
Source File: replica.py    From rucio with Apache License 2.0 5 votes vote down vote up
def get(self):
        """
        Return a summary of the bad replicas by incident.

        .. :quickref: BadReplicasSummary; List bad replicas by incident.

        :query rse_expression: The RSE expression.
        :query from_date: The start date.
        :query to_date: The end date.
        :resheader Content-Type: application/x-json-stream
        :status 200: OK.
        :status 401: Invalid auth token.
        :status 406: Not Acceptable.
        :status 500: Internal Error.
        :returns: List of bad replicas by incident.
        """
        result = []
        rse_expression = request.args.get('rse_expression', None)
        from_date = request.args.get('from_date', None)
        to_date = request.args.get('to_date', None)

        if from_date:
            from_date = datetime.strptime(from_date, "%Y-%m-%d")
        if to_date:
            to_date = datetime.strptime(to_date, "%Y-%m-%d")

        try:
            result = get_bad_replicas_summary(rse_expression=rse_expression, from_date=from_date, to_date=to_date)
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            return error, 500
        data = ""
        for row in result:
            data += dumps(row, cls=APIEncoder) + '\n'

        return Response(data, content_type='application/x-json-stream') 
Example #27
Source File: replica.py    From rucio with Apache License 2.0 5 votes vote down vote up
def post(self):
        """
        Declare a list of suspicious replicas.

        .. :quickref: SuspiciousReplicas; Declare suspicious replicas.

        :<json string pfns: The list of PFNs.
        :<json string reason: The reason of the loss.
        :resheader Content-Type: application/x-json-string
        :status 201: Created.
        :status 400: Cannot decode json parameter list.
        :status 401: Invalid auth token.
        :status 404: Replica not found.
        :status 500: Internal Error.
        :returns: A list of not successfully declared files.
        """
        json_data = request.data
        pfns = []
        try:
            params = parse_response(json_data)
            if 'pfns' in params:
                pfns = params['pfns']
            if 'reason' in params:
                reason = params['reason']
        except ValueError:
            return generate_http_error_flask(400, 'ValueError', 'Cannot decode json parameter list')

        not_declared_files = {}
        try:
            not_declared_files = declare_suspicious_file_replicas(pfns=pfns, reason=reason, issuer=request.environ.get('issuer'))
        except ReplicaNotFound as error:
            return generate_http_error_flask(404, 'ReplicaNotFound', error.args[0])
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            return error, 500
        return Response(dumps(not_declared_files), status=201, content_type='application/x-json-stream') 
Example #28
Source File: replica.py    From rucio with Apache License 2.0 5 votes vote down vote up
def post(self):
        """
        Declare a list of bad replicas.

        .. :quickref: BadReplicasStates; Declare bad replicas.

        :<json string pfns: The list of PFNs.
        :<json string reason: The reason of the loss.
        :resheader Content-Type: application/x-json-string
        :status 201: Created.
        :status 400: Cannot decode json parameter list.
        :status 401: Invalid auth token.
        :status 404: Replica not found.
        :status 500: Internal Error.
        :returns: A list of not successfully declared files.
        """
        json_data = request.data
        pfns = []

        try:
            params = parse_response(json_data)
            if 'pfns' in params:
                pfns = params['pfns']
            if 'reason' in params:
                reason = params['reason']
        except ValueError:
            return generate_http_error_flask(400, 'ValueError', 'Cannot decode json parameter list')

        not_declared_files = {}
        try:
            not_declared_files = declare_bad_file_replicas(pfns=pfns, reason=reason, issuer=request.environ.get('issuer'))
        except ReplicaNotFound as error:
            return generate_http_error_flask(404, 'ReplicaNotFound', error.args[0])
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            return error, 500
        return Response(dumps(not_declared_files), status=201, content_type='application/x-json-stream') 
Example #29
Source File: replica.py    From rucio with Apache License 2.0 5 votes vote down vote up
def delete(self):
        """
        Delete file replicas at a given RSE.

        .. :quickref: Replicas; Delete replica at RSE.

        :<json string rse: The RSE name.
        :<json list files: list of dicts with 'scope', 'name'.
        :<json bool ignore_availability: Flag to ignore the RSE blacklisting.
        :status 200: Replica successfully deleted.
        :status 400: Cannot decode json parameter list.
        :status 401: Invalid auth token.
        :status 404: RSE not found.
        :status 404: Replica not found.
        :status 500: Internal Error.
        """
        json_data = request.data
        try:
            parameters = parse_response(json_data)
        except ValueError:
            return generate_http_error_flask(400, 'ValueError', 'Cannot decode json parameter list')

        try:
            delete_replicas(rse=parameters['rse'], files=parameters['files'], issuer=request.environ.get('issuer'), ignore_availability=parameters.get('ignore_availability', False))
        except AccessDenied as error:
            return generate_http_error_flask(401, 'AccessDenied', error.args[0])
        except RSENotFound as error:
            return generate_http_error_flask(404, 'RSENotFound', error.args[0])
        except ResourceTemporaryUnavailable as error:
            return generate_http_error_flask(503, 'ResourceTemporaryUnavailable', error.args[0])
        except ReplicaNotFound as error:
            return generate_http_error_flask(404, 'ReplicaNotFound', error.args[0])
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            return error, 500
        return 'OK', 200 
Example #30
Source File: app.py    From wechatpy with MIT License 5 votes vote down vote up
def wechat():
    signature = request.args.get("signature", "")
    timestamp = request.args.get("timestamp", "")
    nonce = request.args.get("nonce", "")
    encrypt_type = request.args.get("encrypt_type", "raw")
    msg_signature = request.args.get("msg_signature", "")
    try:
        check_signature(TOKEN, signature, timestamp, nonce)
    except InvalidSignatureException:
        abort(403)
    if request.method == "GET":
        echo_str = request.args.get("echostr", "")
        return echo_str

    # POST request
    if encrypt_type == "raw":
        # plaintext mode
        msg = parse_message(request.data)
        if msg.type == "text":
            reply = create_reply(msg.content, msg)
        else:
            reply = create_reply("Sorry, can not handle this for now", msg)
        return reply.render()
    else:
        # encryption mode
        from wechatpy.crypto import WeChatCrypto

        crypto = WeChatCrypto(TOKEN, AES_KEY, APPID)
        try:
            msg = crypto.decrypt_message(request.data, msg_signature, timestamp, nonce)
        except (InvalidSignatureException, InvalidAppIdException):
            abort(403)
        else:
            msg = parse_message(msg)
            if msg.type == "text":
                reply = create_reply(msg.content, msg)
            else:
                reply = create_reply("Sorry, can not handle this for now", msg)
            return crypto.encrypt_message(reply.render(), nonce, timestamp)