Python flask.Response() Examples

The following are 30 code examples of flask.Response(). 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: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: rl_data.py    License: Apache License 2.0 12 votes vote down vote up
def make_web(queue):
    app = Flask(__name__)

    @app.route('/')
    def index():
        return render_template('index.html')

    def gen():
        while True:
            frame = queue.get()
            _, frame = cv2.imencode('.JPEG', frame)
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame.tostring() + b'\r\n')

    @app.route('/video_feed')
    def video_feed():
        return Response(gen(),
                        mimetype='multipart/x-mixed-replace; boundary=frame')

    try:
        app.run(host='0.0.0.0', port=8889)
    except:
        print('unable to open port') 
Example #2
Source Project: hydrus   Author: HTTP-APIs   File: auth.py    License: MIT License 8 votes vote down vote up
def check_authentication_response() -> Union[Response, None]:
    """
    Return the response as per the authentication requirements.
    """
    if get_authentication():
        if get_token():
            token = check_token(request, get_session())
            if not token:
                if request.authorization is None:
                    return failed_authentication(False)
                else:
                    return verify_user()
        elif request.authorization is None:
            return failed_authentication(False)
        else:
            return verify_user()
    else:
        return None 
Example #3
Source Project: everyclass-server   Author: everyclass   File: views_main.py    License: Mozilla Public License 2.0 7 votes vote down vote up
def exit_maintenance():
    config = get_config()
    auth = request.authorization
    if auth \
            and auth.username in config.MAINTENANCE_CREDENTIALS \
            and config.MAINTENANCE_CREDENTIALS[auth.username] == auth.password:
        try:
            os.remove(config.MAINTENANCE_FILE)  # remove maintenance file
        except OSError:
            return 'Not in maintenance mode. Ignore command.'
        open(os.path.join(os.getcwd(), 'reload'), "w+").close()  # uwsgi reload
        return 'success'
    else:
        return Response(
            'Could not verify your access level for that URL.\n'
            'You have to login with proper credentials', 401,
            {'WWW-Authenticate': 'Basic realm="Login Required"'}) 
Example #4
Source Project: zmirror   Author: aploium   File: custom_func.sample.py    License: MIT License 6 votes vote down vote up
def custom_prior_redirect_func(request, parse):
    """
    用于在 prior_request_redirect 阶段的自定义重定向

    若返回一个 flask.Response 对象, 则执行重定向, 直接返回这个 Response
    若返回None, 则不进行重定向

    不应该修改parse变量 (添加头和cookie除外)

    详见 `config_default.py` 中 `Custom Redirection` 部分

    :param request: flask request object
    :type request: Request
    :param parse: the zmirror parse variable
    :type parse: ZmirrorThreadLocal
    :rtype: Union[Response, None]
    """
    print(request.url, parse.remote_url)

    from flask import redirect

    # 如果你想重定向, 请使用这句
    # return redirect("/location/you/want/redirect/to")

    return None  # 不进行自定义重定向 
Example #5
Source Project: zmirror   Author: aploium   File: zmirror.py    License: MIT License 6 votes vote down vote up
def try_get_cached_response(url, client_header=None):
    """
    尝试从本地缓存中取出响应
    :param url: real url with query string
    :type client_header: dict
    :rtype: Union[Response, None]
    """
    # Only use cache when client use GET
    if local_cache_enable and parse.method == 'GET' and cache.is_cached(url):
        if client_header is not None and 'if-modified-since' in client_header and \
                cache.is_unchanged(url, client_header.get('if-modified-since', None)):
            dbgprint('FileCacheHit-304', url)
            return generate_304_response()
        else:
            cached_info = cache.get_info(url)
            if cached_info.get('without_content', True):
                # 关于 without_content 的解释, 请看update_content_in_local_cache()函数
                return None
            # dbgprint('FileCacheHit-200')
            resp = cache.get_obj(url)
            assert isinstance(resp, Response)
            parse.set_extra_resp_header('x-zmirror-cache', 'FileHit')
            return resp
    else:
        return None 
Example #6
Source Project: zmirror   Author: aploium   File: zmirror.py    License: MIT License 6 votes vote down vote up
def generate_our_response():
    """
    生成我们的响应
    :rtype: Response
    """
    # copy and parse remote response
    resp = copy_response(is_streamed=parse.streamed_our_response)

    if parse.time["req_time_header"] >= 0.00001:
        parse.set_extra_resp_header('X-Header-Req-Time', "%.4f" % parse.time["req_time_header"])
    if parse.time.get("start_time") is not None and not parse.streamed_our_response:
        # remote request time should be excluded when calculating total time
        parse.set_extra_resp_header('X-Body-Req-Time', "%.4f" % parse.time["req_time_body"])
        parse.set_extra_resp_header('X-Compute-Time',
                                    "%.4f" % (process_time() - parse.time["start_time"]))

    parse.set_extra_resp_header('X-Powered-By', 'zmirror/%s' % CONSTS.__VERSION__)

    if developer_dump_all_traffics and not parse.streamed_our_response:
        dump_zmirror_snapshot("traffic")

    return resp 
Example #7
Source Project: botbuilder-python   Author: microsoft   File: main.py    License: MIT License 6 votes vote down vote up
def messages():
    """Main bot message handler."""
    if "application/json" in request.headers["Content-Type"]:
        body = request.json
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = (
        request.headers["Authorization"] if "Authorization" in request.headers else ""
    )

    async def aux_func(turn_context):
        await BOT.on_turn(turn_context)

    try:
        task = LOOP.create_task(
            ADAPTER.process_activity(activity, auth_header, aux_func)
        )
        LOOP.run_until_complete(task)
        return Response(status=201)

    except Exception as exception:
        raise exception 
Example #8
Source Project: botbuilder-python   Author: microsoft   File: app.py    License: MIT License 6 votes vote down vote up
def messages():
    # Main bot message handler.
    if "application/json" in request.headers["Content-Type"]:
        body = request.json
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = (
        request.headers["Authorization"] if "Authorization" in request.headers else ""
    )

    try:
        task = LOOP.create_task(
            ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        )
        LOOP.run_until_complete(task)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #9
Source Project: botbuilder-python   Author: microsoft   File: app.py    License: MIT License 6 votes vote down vote up
def messages():
    # Main bot message handler.
    if "application/json" in request.headers["Content-Type"]:
        body = request.json
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = (
        request.headers["Authorization"] if "Authorization" in request.headers else ""
    )

    try:
        task = LOOP.create_task(
            ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        )
        LOOP.run_until_complete(task)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #10
Source Project: botbuilder-python   Author: microsoft   File: app.py    License: MIT License 6 votes vote down vote up
def messages():
    # Main bot message handler.
    if "application/json" in request.headers["Content-Type"]:
        body = request.json
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = (
        request.headers["Authorization"] if "Authorization" in request.headers else ""
    )

    try:
        task = LOOP.create_task(
            ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        )
        LOOP.run_until_complete(task)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #11
Source Project: botbuilder-python   Author: microsoft   File: app.py    License: MIT License 6 votes vote down vote up
def messages():
    # Main bot message handler.
    if "application/json" in request.headers["Content-Type"]:
        body = request.json
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = (
        request.headers["Authorization"] if "Authorization" in request.headers else ""
    )

    try:
        task = LOOP.create_task(
            ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        )
        LOOP.run_until_complete(task)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #12
Source Project: botbuilder-python   Author: microsoft   File: app.py    License: MIT License 6 votes vote down vote up
def messages():
    # Main bot message handler.
    if "application/json" in request.headers["Content-Type"]:
        body = request.json
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = (
        request.headers["Authorization"] if "Authorization" in request.headers else ""
    )

    try:
        task = LOOP.create_task(
            ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        )
        LOOP.run_until_complete(task)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #13
Source Project: py-flask-jsontools   Author: kolypto   File: response.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, response, status=None, headers=None, **kwargs):
        """ Init a JSON response
        :param response: Response data
        :type response: *
        :param status: Status code
        :type status: int|None
        :param headers: Additional headers
        :type headers: dict|None
        """
        # Store response
        self._response_data = self.preprocess_response_data(response)

        # PrettyPrint?
        try:
            indent = 2 if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr else None
        except RuntimeError:  # "RuntimeError: working outside of application context"
            indent = None

        # Init super
        super(JsonResponse, self).__init__(
            json.dumps(self._response_data, indent=indent),
            headers=headers, status=status, mimetype='application/json',
            direct_passthrough=True, **kwargs) 
Example #14
Source Project: pyspider   Author: binux   File: result.py    License: Apache License 2.0 6 votes vote down vote up
def dump_result(project, _format):
    resultdb = app.config['resultdb']
    # force update project list
    resultdb.get(project, 'any')
    if project not in resultdb.projects:
        return "no such project.", 404

    offset = int(request.args.get('offset', 0)) or None
    limit = int(request.args.get('limit', 0)) or None
    results = resultdb.select(project, offset=offset, limit=limit)

    if _format == 'json':
        valid = request.args.get('style', 'rows') == 'full'
        return Response(result_dump.dump_as_json(results, valid),
                        mimetype='application/json')
    elif _format == 'txt':
        return Response(result_dump.dump_as_txt(results),
                        mimetype='text/plain')
    elif _format == 'csv':
        return Response(result_dump.dump_as_csv(results),
                        mimetype='text/csv') 
Example #15
Source Project: svviz   Author: svviz   File: web.py    License: MIT License 5 votes vote down vote up
def do_export():
    format = request.form.get("format", "svg").lower()
    session["last_format"] = format

    filename = "export.{}".format(format)

    svg = dataHub.trackCompositor.render()

    converter = export.getExportConverter(dataHub.args, format)

    if format == "svg":
        mimetype = "image/svg+xml"
        data = svg
    elif format == "png":
        mimetype = "image/png"
        data = export.convertSVG(svg, "png", converter)
    elif format == "pdf":
        mimetype = "application/pdf"
        data = export.convertSVG(svg, "pdf", converter)
    else:
        raise Exception("unknown format")

    response = Response(data,
                        mimetype=mimetype,
                        headers={"Content-Disposition": "attachment;filename={}".format(filename)})

    return response 
Example #16
Source Project: svviz   Author: svviz   File: web.py    License: MIT License 5 votes vote down vote up
def displayIsizes(name):
    if not dataHub.samples[name].insertSizePlot:
        return None

    return Response(dataHub.samples[name].insertSizePlot, mimetype="image/png") 
Example #17
Source Project: svviz   Author: svviz   File: web.py    License: MIT License 5 votes vote down vote up
def get_dotplot(name):
    if name in dataHub.dotplots:
        return Response(dataHub.dotplots[name], mimetype="image/png")
    return None 
Example #18
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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
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 #25
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 #26
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 #27
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 #28
Source Project: hydrus   Author: HTTP-APIs   File: helpers.py    License: MIT License 5 votes vote down vote up
def set_response_headers(resp: Response,
                         ct: str = "application/ld+json",
                         headers: List[Dict[str, Any]]=[],
                         status_code: int = 200) -> Response:
    """Set the response headers."""
    resp.status_code = status_code
    for header in headers:
        resp.headers[list(header.keys())[0]] = header[list(header.keys())[0]]
    resp.headers['Content-type'] = ct
    link = "http://www.w3.org/ns/hydra/core#apiDocumentation"
    resp.headers['Link'] = '<{}{}/vocab>; rel="{}"'.format(
        get_hydrus_server_url(), get_api_name(), link)
    return resp 
Example #29
Source Project: everyclass-server   Author: everyclass   File: jsonable.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def to_json_response(obj) -> Response:
    resp = Response(to_json(obj), mimetype='application/json')
    resp.headers.add_header('Access-Control-Allow-Origin',
                            'https://everyclass.xyz' if is_production() else 'https://staging.everyclass.xyz')
    resp.headers.add_header('Access-Control-Allow-Credentials', 'true')
    # resp.headers.add_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
    return resp 
Example #30
Source Project: everyclass-server   Author: everyclass   File: views_main.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def enter_maintenance():
    config = get_config()
    auth = request.authorization
    if auth \
            and auth.username in config.MAINTENANCE_CREDENTIALS \
            and config.MAINTENANCE_CREDENTIALS[auth.username] == auth.password:
        open(config.MAINTENANCE_FILE, "w+").close()  # maintenance file
        open(os.path.join(os.getcwd(), 'reload'), "w+").close()  # uwsgi reload
        return 'success'
    else:
        return Response(
            'Could not verify your access level for that URL.\n'
            'You have to login with proper credentials', 401,
            {'WWW-Authenticate': 'Basic realm="Login Required"'})