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 File: rl_data.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 14 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 File: auth.py    From hydrus with 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 File: views_main.py    From everyclass-server with 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 File: app.py    From botbuilder-python with 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 #5
Source File: app.py    From botbuilder-python with 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 #6
Source File: app.py    From botbuilder-python with 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 #7
Source File: response.py    From py-flask-jsontools with 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 #8
Source File: zmirror.py    From zmirror with 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 #9
Source File: app.py    From botbuilder-python with 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 File: custom_func.sample.py    From zmirror with 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 #11
Source File: result.py    From pyspider with 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 #12
Source File: app.py    From botbuilder-python with 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 File: main.py    From botbuilder-python with 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 #14
Source File: zmirror.py    From zmirror with 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 #15
Source File: bot_app.py    From botbuilder-python with MIT License 5 votes vote down vote up
def messages(self) -> Response:
        """Main bot message handler that listens for incoming requests."""

        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 self.bot.on_turn(turn_context)

        try:
            task = self.loop.create_task(
                self.adapter.process_activity(activity, auth_header, aux_func)
            )
            self.loop.run_until_complete(task)
            return Response(status=201)
        except Exception as exception:
            raise exception 
Example #16
Source File: keras_web.py    From Jtyoui with MIT License 5 votes vote down vote up
def subscribe():
    def gen():
        q = Queue()
        subscriptions.append(q)
        try:
            while True:
                result = q.get()
                event = ServerSentEvent(str(result))
                yield event.encode()
        except GeneratorExit:
            subscriptions.remove(q)

    return Response(gen(), mimetype="text/event-stream") 
Example #17
Source File: webserver_sub.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def root():
    """Show simple text."""
    return flask.Response(b'qutebrowser test webserver, '
                          b'<a href="/user-agent">user agent</a>') 
Example #18
Source File: app.py    From botbuilder-python with MIT License 5 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:
        print("about to create task")
        print("about to run until complete")
        run_coroutine(ADAPTER.process_activity(activity, auth_header, BOT.on_turn))
        print("is now complete")
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #19
Source File: webserver_sub.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def redirect_later_continue():
    """Continue a redirect-later request."""
    if _redirect_later_event is None:
        return flask.Response(b'Timed out or no redirect pending.')
    else:
        _redirect_later_event.set()
        return flask.Response(b'Continued redirect.') 
Example #20
Source File: app.py    From botbuilder-python with MIT License 5 votes vote down vote up
def test() -> Response:
    return APP.test() 
Example #21
Source File: app.py    From botbuilder-python with MIT License 5 votes vote down vote up
def messages() -> Response:
    return APP.messages() 
Example #22
Source File: api.py    From lyrebird-api-coverage with MIT License 5 votes vote down vote up
def clear_result():
    ResultHandler().clear_cache_result()
    # 获取基准文件
    base_dict = BaseDataHandler().get_base_source()
    # 初始化正常会进行数据的处理:覆盖率初始化 & API LIST初始化
    if not isinstance(base_dict, Response):
        mergeAlgorithm.first_result_handler(base_dict)
        mergeAlgorithm.coverage_arithmetic(base_dict)
    lyrebird.publish('api_coverage', 'operation', name='clear_result')
    return context.make_ok_response()

# 导入base json文件
# /importBase 
Example #23
Source File: api.py    From lyrebird-api-coverage with MIT License 5 votes vote down vote up
def get_coverage():
    return Response(stream_with_context(generate(app_context.coverage)), content_type='application/json')

# 保存测试数据在本地
#  /saveResult 
Example #24
Source File: api.py    From lyrebird-api-coverage with MIT License 5 votes vote down vote up
def get_test_data():
    return Response(stream_with_context(generate({'test_data': app_context.merge_list})), content_type='application/json')

# 获取内存里保存的测试覆盖率信息
# /getCoverage 
Example #25
Source File: views.py    From comport with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def demographics_csv(department_id):
    department = Department.get_by_id(department_id)
    if not department:
        abort(404)
    return Response(department.get_demographic_csv(), mimetype="text/csv")


# <<<<<<<< PUBLIC ENDPOINTS >>>>>>>>>> 
Example #26
Source File: views.py    From comport with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ois_csv(department_id):
    department = Department.get_by_id(department_id)
    if not department:
        abort(404)
    return Response(department.get_ois_csv(), mimetype="text/csv") 
Example #27
Source File: views.py    From comport with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def assaults_csv(department_id):
    department = Department.get_by_id(department_id)
    if not department:
        abort(404)
    return Response(department.get_assaults_csv(), mimetype="text/csv") 
Example #28
Source File: views.py    From comport with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pursuits_csv(department_id):
    department = Department.get_by_id(department_id)
    if not department:
        abort(404)
    return Response(department.get_pursuits_csv(), mimetype="text/csv") 
Example #29
Source File: views.py    From comport with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def complaints_csv(department_id):
    department = Department.get_by_id(department_id)
    if not department:
        abort(404)
    return Response(department.get_complaint_csv(), mimetype="text/csv") 
Example #30
Source File: views.py    From comport with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def use_of_force_csv(department_id):
    department = Department.get_by_id(department_id)
    if not department:
        abort(404)
    return Response(department.get_uof_csv(), mimetype="text/csv")