Python flask.jsonify() Examples

The following are 30 code examples of flask.jsonify(). 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 , or try the search function .
Example #1
Source Project: video2commons   Author: toolforge   File: upload.py    License: GNU General Public License v3.0 15 votes vote down vote up
def upload():
    f = request.files['file']
    assert f, "Where's my file?"

    filekey = request.form.get('filekey') or str(uuid.uuid1())
    assert RE_ALLOWED_FILEKEYS.match('filekey'), 'Unacceptable file key'

    permpath = getpath(filekey)

    content_range = (f.headers.get('Content-Range') or
                     request.headers.get('Content-Range'))

    if content_range:
        result, kwargs = handle_chunked(f, permpath, content_range)
    else:
        result, kwargs = handle_full(f, permpath)

    kwargs['filekey'] = filekey

    return jsonify(result=result, **kwargs)


# Flask endpoint 
Example #2
Source Project: BASS   Author: Cisco-Talos   File: server.py    License: GNU General Public License v2.0 8 votes vote down vote up
def whitelist_add():
    log.info("whitelist_add called")
    try:
        file_ = request.files["file"]
        handle, filename = tempfile.mkstemp()
        os.close(handle)
        file_.save(filename)
        data = request.get_json()
        if data and "functions" in data:
            functions = data["functions"]
        else:
            functions = None
        bass.whitelist_add(filename, functions)
        os.unlink(filename)
    except KeyError:
        log.exception("")
        return make_response(jsonify(message = "Sample file 'file' missing in POST request"), 400)

    return jsonify(message = "OK") 
Example #3
Source Project: grlc   Author: CLARIAH   File: server.py    License: MIT License 8 votes vote down vote up
def query(user, repo, query_name, subdir=None, spec_url=None, sha=None, content=None):
    """Execute SPARQL query for a specific grlc-generated API endpoint"""
    glogger.info("-----> Executing call name at /{}/{}/{}/{} on commit {}".format(user, repo, subdir, query_name, sha))
    glogger.debug("Request accept header: " + request.headers["Accept"])

    requestArgs = request.args
    acceptHeader = request.headers['Accept']
    requestUrl = request.url
    formData = request.form

    query_response, status, headers = utils.dispatch_query(user, repo, query_name, subdir, spec_url,
                                                           sha=sha, content=content, requestArgs=requestArgs,
                                                           acceptHeader=acceptHeader,
                                                           requestUrl=requestUrl, formData=formData)
    if isinstance(query_response, list):
        query_response = jsonify(query_response)

    return make_response(query_response, status, headers)

### Server routes ### 
Example #4
Source Project: BASS   Author: Cisco-Talos   File: server.py    License: GNU General Public License v2.0 7 votes vote down vote up
def function_raw_hash_get():
    global Session
    session = Session()
    filename, file_ = request.files.items()[0]
    db = Database(pickle.load(file_))

    arch_name = db.architecture_name
    if arch_name == "metapc":
        arch_name = "x86"
    try:
        arch = session.query(Architecture).filter(Architecture.name == arch_name and \
                Architecture.bits == db.architecture_bits and \
                Architecture.little_endian == db.architecture_endianness == "little").one()
    except NoResultFound:
        return make_response(jsonify(message = "Architecture not found"), 404)
    
    try:
        func = next(db.functions)
    except StopIteration:
        return make_response(jsonify(message = "No function found in database"), 500)

    raw_hash = _function_calculate_raw_sha256(func)
    size = _function_get_size(func)

    try:
        function = session.query(Function).filter(Function.raw_sha256 == raw_hash and \
                Function.size == size and \
                Function.arch == arch.id).one()
        return make_response(jsonify(**json.loads(function.data)), 200)
    except NoResultFound:
        return make_response(jsonify(message = "Function not found"), 404) 
Example #5
Source Project: bounty_tools   Author: gradiuscypher   File: reconng.py    License: MIT License 7 votes vote down vote up
def run():

    # Setup the jsonrpclib for the recon-ng RPC server, stop the API if it cannot connect to the RPC server.
    try:
        client = jsonrpclib.Server('http://localhost:4141')
        sid = client.init()

        # Get the configuration from JSON POST
        content = request.get_json()
        target_module = content['module']
        target_domain = content['domain']
        print(target_domain, target_module)

        # Set the target domain
        client.add('domains', target_domain, sid)
        print(client.show('domains', sid))
        client.use(target_module, sid)

        # Execute the requested module and return the results
        results = client.run(sid)

        return jsonify(results)

    except:
        return traceback.format_exc(), 500 
Example #6
Source Project: grlc   Author: CLARIAH   File: sparql.py    License: MIT License 6 votes vote down vote up
def getResponseText(endpoint, query, requestedMimeType):
    """Returns the result and mimetype of executing the given query against 
    the given endpoint.

    Keyword arguments:
    endpoint - URL of sparql endpoint
    query    - SPARQL query to be executed
    requestedMimeType  Type of content requested. can be:
                'text/csv; q=1.0, */*; q=0.1'
                'application/json'
                etc.
    """
    retFormat = _mimeTypeToSparqlFormat(requestedMimeType)

    client = SPARQLWrapper(endpoint)
    client.setQuery(query)
    client.setReturnFormat(retFormat)
    client.setCredentials(static.DEFAULT_ENDPOINT_USER, static.DEFAULT_ENDPOINT_PASSWORD)
    result = client.queryAndConvert()

    if retFormat==JSON:
        result = jsonify(result)

    return result, MIME_FORMAT[retFormat] 
Example #7
Source Project: svviz   Author: svviz   File: web.py    License: MIT License 5 votes vote down vote up
def _hasPDFExport():
    if export.getExportConverter(dataHub.args, "pdf"):
        return jsonify({"haspdfexport":True})
    return jsonify({"haspdfexport":False}) 
Example #8
Source Project: svviz   Author: svviz   File: web.py    License: MIT License 5 votes vote down vote up
def _hasPNGExport():
    if export.getExportConverter(dataHub.args, "png"):
        return jsonify({"haspngexport":True})
    return jsonify({"haspngexport":False}) 
Example #9
Source Project: svviz   Author: svviz   File: web.py    License: MIT License 5 votes vote down vote up
def display():
    req = request.args.get('req', 0)

    if req == "progress":
        return jsonify(result="done")

    if req in ["alt", "ref", "amb"]:
        allele = req
        results = []
        for name, sample in dataHub.samples.items():
            # svg = open("{}.{}.svg".format(req, name)).read()
            track = sample.tracks[allele]
            track.render()
            svg = track.svg.asString("web")
            results.append({"name":name, "svg":svg})

        for annotation in dataHub.alleleTracks[allele]:
            track = dataHub.alleleTracks[allele][annotation]
            track.render(spacing=5)
            annoSVG = track.svg.asString("web")
            results.append({"name":annotation, "svg":annoSVG})

        return jsonify(results=results)


    if req == "counts":
        return jsonify(result=dataHub.getCounts())

    return jsonify(result="unknown request: {}".format(req)) 
Example #10
Source Project: hydrus   Author: HTTP-APIs   File: resources.py    License: MIT License 5 votes vote down vote up
def get(self) -> Response:
        """Return main entrypoint for the api."""
        return set_response_headers(jsonify(get_doc().entrypoint.get())) 
Example #11
Source Project: hydrus   Author: HTTP-APIs   File: resources.py    License: MIT License 5 votes vote down vote up
def get(self) -> Response:
        """Return the main hydra vocab."""
        return set_response_headers(jsonify(get_doc().generate())) 
Example #12
Source Project: hydrus   Author: HTTP-APIs   File: resources.py    License: MIT License 5 votes vote down vote up
def get(self) -> Response:
        """Return application main Entrypoint."""
        response = {"@context": get_doc().entrypoint.context.generate()}
        return set_response_headers(jsonify(response)) 
Example #13
Source Project: hydrus   Author: HTTP-APIs   File: resources.py    License: MIT License 5 votes vote down vote up
def get(self, id_: str, path: str) -> Response:
        """
        GET object with id = id_ from the database.
        :param id_ : Item ID
        :param path : Path for Item ( Specified in APIDoc @id)
        """
        id_ = str(id_)
        auth_response = check_authentication_response()
        if isinstance(auth_response, Response):
            return auth_response

        class_type = get_doc().collections[path]["collection"].class_.title
        # Get path of the collection-class
        class_path = get_doc().collections[path]["collection"].class_.path

        if checkClassOp(class_path, "GET"):
            # Check if class_type supports GET operation
            try:
                # Try getting the Item based on ID and Class type
                response = crud.get(
                    id_,
                    class_type,
                    api_name=get_api_name(),
                    session=get_session())

                response = finalize_response(class_path, response)
                return set_response_headers(
                    jsonify(hydrafy(response, path=path)))

            except (ClassNotFound, InstanceNotFound) as e:
                error = e.get_HTTP()
                return set_response_headers(jsonify(error.generate()), status_code=error.code)
        abort(405) 
Example #14
Source Project: hydrus   Author: HTTP-APIs   File: resources.py    License: MIT License 5 votes vote down vote up
def delete(self, id_: str, path: str) -> Response:
        """Delete object with id=id_ from database."""
        id_ = str(id_)
        auth_response = check_authentication_response()
        if isinstance(auth_response, Response):
            return auth_response

        class_type = get_doc().collections[path]["collection"].class_.title
        # Get path of the collection-class
        class_path = get_doc().collections[path]["collection"].class_.path

        if checkClassOp(class_path, "DELETE"):
            # Check if class_type supports PUT operation
            try:
                # Delete the Item with ID == id_
                crud.delete(id_, class_type, session=get_session())
                method = "DELETE"
                resource_url = "{}{}/{}/{}".format(
                    get_hydrus_server_url(), get_api_name(), path, id_)
                last_job_id = crud.get_last_modification_job_id(session=get_session())
                new_job_id = crud.insert_modification_record(method, resource_url,
                                                             session=get_session())
                send_sync_update(socketio=socketio, new_job_id=new_job_id,
                                 last_job_id=last_job_id, method=method,
                                 resource_url=resource_url)
                status_description = "Object with ID {} successfully deleted".format(id_)
                status = HydraStatus(code=200, title="Object successfully deleted.",
                                     desc=status_description)
                return set_response_headers(jsonify(status.generate()))

            except (ClassNotFound, InstanceNotFound) as e:
                error = e.get_HTTP()
                return set_response_headers(jsonify(error.generate()), status_code=error.code)

        abort(405) 
Example #15
Source Project: hydrus   Author: HTTP-APIs   File: resources.py    License: MIT License 5 votes vote down vote up
def delete(self, path: str) -> Response:
        """
        Method executed for DELETE requests.
        Used to delete a non-collection class.
        :param path - Path for Item ( Specified in APIDoc @id)
        """
        auth_response = check_authentication_response()
        if isinstance(auth_response, Response):
            return auth_response

        endpoint_ = checkEndpoint("DELETE", path)
        if not endpoint_['method']:
            abort(endpoint_['status'])
        elif path in get_doc().parsed_classes and "{}Collection".format(
                path) not in get_doc().collections:
            # No Delete Operation for collections
            try:
                class_type = get_doc().parsed_classes[path]['class'].title
                crud.delete_single(class_type, session=get_session())
                method = "DELETE"
                resource_url = "{}{}/{}".format(
                    get_hydrus_server_url(), get_api_name(), path)
                last_job_id = crud.get_last_modification_job_id(session=get_session())
                new_job_id = crud.insert_modification_record(method, resource_url,
                                                             session=get_session())
                send_sync_update(socketio=socketio, new_job_id=new_job_id,
                                 last_job_id=last_job_id, method=method,
                                 resource_url=resource_url)
                status = HydraStatus(code=200, title="Object successfully added")
                return set_response_headers(jsonify(status.generate()))
            except (ClassNotFound, InstanceNotFound) as e:
                error = e.get_HTTP()
                return set_response_headers(
                    jsonify(error.generate()), status_code=error.code) 
Example #16
Source Project: hydrus   Author: HTTP-APIs   File: resources.py    License: MIT License 5 votes vote down vote up
def delete(self, path, int_list):
        """
        To delete multiple objects
        :param path: endpoints
        :param int_list: Optional String containing ',' separated ID's
        :return:
        """
        auth_response = check_authentication_response()
        if isinstance(auth_response, Response):
            return auth_response
        class_type = get_doc().collections[path]["collection"].class_.title

        if checkClassOp(class_type, "DELETE"):
            # Check if class_type supports PUT operation
            try:
                # Delete the Item with ID == id_
                crud.delete_multiple(int_list, class_type, session=get_session())
                method = "DELETE"
                path_url = "{}{}/{}".format(
                    get_hydrus_server_url(), get_api_name(), path)
                last_job_id = crud.get_last_modification_job_id(session=get_session())
                id_list = int_list.split(',')
                for item in id_list:
                    resource_url = path_url + item
                    new_job_id = crud.insert_modification_record(method, resource_url,
                                                                 session=get_session())
                    send_sync_update(socketio=socketio, new_job_id=new_job_id,
                                     last_job_id=last_job_id, method=method,
                                     resource_url=resource_url)
                    last_job_id = new_job_id
                status_description = "Objects with ID {} successfully deleted".format(
                    id_list)
                status = HydraStatus(code=200, title="Objects successfully deleted",
                                     desc=status_description)
                return set_response_headers(jsonify(status.generate()))

            except (ClassNotFound, InstanceNotFound) as e:
                error = e.get_HTTP()
                return set_response_headers(jsonify(error.generate()), status_code=error.code)

        abort(405) 
Example #17
Source Project: hydrus   Author: HTTP-APIs   File: auth.py    License: MIT License 5 votes vote down vote up
def token_response(token: str) -> Response:
    """
    Return succesful token generation object
    """
    message = {200: "User token generated"}
    response = set_response_headers(jsonify(message), status_code=200,
                                    headers=[{'X-Authorization': token}])
    return response 
Example #18
Source Project: hydrus   Author: HTTP-APIs   File: auth.py    License: MIT License 5 votes vote down vote up
def failed_authentication(incorrect: bool) -> Response:
    """
    Return failed authentication object.
    """
    if not incorrect:
        message = {401: "Need credentials to authenticate"}
        realm = 'Basic realm="Login required"'
    else:
        message = {401: "Incorrect credentials"}
        realm = 'Basic realm="Incorrect credentials"'
    nonce = create_nonce(get_session())
    response = set_response_headers(jsonify(message), status_code=401,
                                    headers=[{'WWW-Authenticate': realm},
                                             {'X-Authentication': nonce}])
    return response 
Example #19
Source Project: hydrus   Author: HTTP-APIs   File: auth.py    License: MIT License 5 votes vote down vote up
def verify_user() -> Union[Response, None]:
    """
    Verify the credentials of the user and assign token.
    """
    try:
        auth = check_authorization(request, get_session())
        if auth is False:
            return failed_authentication(True)
        elif get_token():
            token = add_token(request, get_session())
            return token_response(token)
    except Exception as e:
        error = e.get_HTTP()  # type: HydraError
        return set_response_headers(jsonify(error.generate()), status_code=error.code)
    return None 
Example #20
Source Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: chapter9_6.py    License: MIT License 5 votes vote down vote up
def get_devices():
    return jsonify({'device': [device.get_url() 
                               for device in Device.query.all()]}) 
Example #21
Source Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: chapter9_6.py    License: MIT License 5 votes vote down vote up
def get_device(id):
    return jsonify(Device.query.get_or_404(id).export_data()) 
Example #22
Source Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: chapter9_6.py    License: MIT License 5 votes vote down vote up
def new_device():
    device = Device()
    device.import_data(request.json)
    db.session.add(device)
    db.session.commit()
    return jsonify({}), 201, {'Location': device.get_url()} 
Example #23
Source Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: chapter9_6.py    License: MIT License 5 votes vote down vote up
def edit_device(id):
    device = Device.query.get_or_404(id)
    device.import_data(request.json)
    db.session.add(device)
    db.session.commit()
    return jsonify({}) 
Example #24
Source Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: chapter9_7.py    License: MIT License 5 votes vote down vote up
def get_devices():
    return jsonify({'device': [device.get_url() 
                               for device in Device.query.all()]}) 
Example #25
Source Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: chapter9_7.py    License: MIT License 5 votes vote down vote up
def get_device_version(id):
    device = Device.query.get_or_404(id)
    hostname = device.hostname
    ip = device.mgmt_ip
    prompt = hostname+"#"
    result = show_version(hostname, prompt, ip, 'cisco', 'cisco')
    return jsonify({"version": str(result)}) 
Example #26
Source Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: chapter9_7.py    License: MIT License 5 votes vote down vote up
def get_role_version(device_role):
    device_id_list = [device.id for device in Device.query.all() if device.role == device_role]
    result = {}
    for id in device_id_list:
        device = Device.query.get_or_404(id)
        hostname = device.hostname
        ip = device.mgmt_ip
        prompt = hostname + "#"
        device_result = show_version(hostname, prompt, ip, 'cisco', 'cisco')
        result[hostname] = str(device_result)
    return jsonify(result) 
Example #27
Source Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: chapter9_7.py    License: MIT License 5 votes vote down vote up
def new_device():
    device = Device()
    device.import_data(request.json)
    db.session.add(device)
    db.session.commit()
    return jsonify({}), 201, {'Location': device.get_url()} 
Example #28
Source Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: chapter9_7.py    License: MIT License 5 votes vote down vote up
def edit_device(id):
    device = Device.query.get_or_404(id)
    device.import_data(request.json)
    db.session.add(device)
    db.session.commit()
    return jsonify({}) 
Example #29
Source Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: chapter9_5.py    License: MIT License 5 votes vote down vote up
def interface(hostname, interface_number):
    return jsonify(name=hostname, interface=interface_number) 
Example #30
Source Project: BASS   Author: Cisco-Talos   File: server.py    License: GNU General Public License v2.0 5 votes vote down vote up
def job_create():
    try:
        job = bass.create_job()
        return jsonify(message = "ok", job = job.json())
    except Exception as ex:
        return make_response(jsonify(message = str(ex), trace = traceback.format_exc()), 400)