コード例 #1
0
ファイル: core.py プロジェクト: AaronLaw/omega
    def dispatch_request(self, urls, request):
        """Dispatch the incoming *request* to the given view function or class.

        If the "request" is a socket.io message, route it to the registered
        namespace.

        :param urls: The URLs parsed by binding the URL map to the environment.
        :param request: The current HTTP request.
        :type request :class:`werkzeug.Request`:
        """
        if request.path.startswith('/socket.io'):
            try:
                socketio_manage(request.environ, self._namespaces, request)
            except:
                print("Exception while handling socketio connection")
            return Response()
        else:
            response = urls.dispatch(
                lambda e, v: self._routes[e](
                    request, **v))
            if isinstance(response, (unicode, str)):
                headers = {'Content-type': 'text/html'}
                response = Response(response, headers=headers)
            if not response:
                headers = {'Content-type': 'text/html'}
                response = Response('404 Not Found', headers=headers)
                response.status_code = 404
            return response
コード例 #2
0
ファイル: basic.py プロジェクト: kalxas/pywps
def xml_response(doc):
    pywps_version_comment = '<!-- PyWPS %s -->\n' % __version__
    xml = lxml.etree.tostring(doc, pretty_print=True)
    response = Response(pywps_version_comment.encode('utf8') + xml,
                        content_type='text/xml')
    response.status_percentage = 100;
    return response
コード例 #3
0
ファイル: RankingWebServer.py プロジェクト: cms-dev/cms
    def wsgi_app(self, environ, start_response):
        route = self.router.bind_to_environ(environ)
        try:
            endpoint, args = route.match()
        except HTTPException as exc:
            return exc(environ, start_response)

        assert endpoint == "sublist"

        request = Request(environ)
        request.encoding_errors = "strict"

        if request.accept_mimetypes.quality("application/json") <= 0:
            raise NotAcceptable()

        result = list()
        for task_id in self.task_store._store.keys():
            result.extend(
                self.scoring_store.get_submissions(
                    args["user_id"], task_id
                ).values()
            )
        result.sort(key=lambda x: (x.task, x.time))
        result = list(a.__dict__ for a in result)

        response = Response()
        response.status_code = 200
        response.mimetype = "application/json"
        response.data = json.dumps(result)

        return response(environ, start_response)
コード例 #4
0
ファイル: __init__.py プロジェクト: justinabrahms/pisces
    def wsgi_app(self, environ, start_response):
        """
        Main WSGI Interface
        """
        request = Request(environ)
        for route in self._routes:
            log.debug("Attempting route: %s", route)
            method = route.match(request.path, request.method)
            if method is None:
                continue

            ### EEW. Not sure I like this.
            extra_params = self._extract_params_from_request(method, request)

            value_map = method(**extra_params)
            if value_map is not None:
                # for now, we're doing dict only
                response = Response(mimetype="application/json")

                # EEW. It doesn't get any better on the response.
                self.apply_consumer_mutations(value_map, response)
                json_dump = json.dumps(value_map)
                response.data = json_dump
                return response(environ, start_response)
        raise NotFound()
コード例 #5
0
ファイル: wsloader.py プロジェクト: codemartial/wsloader
    def __get_response(self, environ, args, kwargs, endpoint):
        if endpoint.__name__ == "service_check":
            result = endpoint(*args, **kwargs)
            response = Response(result['body'])
            response.status_code = result['status']
            return response

        response = {
            'server_info': {
                'http_headers': dict(EnvironHeaders(environ)),
                'response_id': 0,
                'arguments': repr(args) if args else repr(kwargs),
                'processing_time': 0.0
                },
            'response': {}
            }
        
        start_time = time.time()
        # Make the call
        result = endpoint(*args, **kwargs)
        
        # Send the API call response
        response['response'] = result
        response['server_info']['processing_time'] = 1000*(time.time() - start_time)
        try:
            response = json.dumps(response)
        except (TypeError, UnicodeError):
            return InternalServerError(description = "Could not encode service response")
                                    
        response = Response(response)
        response.headers['content-type'] = 'application/json'        
        return response
コード例 #6
0
ファイル: response.py プロジェクト: vhrspvl/vhrs-frappe
def send_private_file(path):
    path = os.path.join(frappe.local.conf.get(
        'private_path', 'private'), path.strip("/"))
    filename = os.path.basename(path)

    if frappe.local.request.headers.get('X-Use-X-Accel-Redirect'):
        path = '/protected/' + path
        response = Response()
        response.headers[b'X-Accel-Redirect'] = frappe.utils.encode(path)

    else:
        filepath = frappe.utils.get_site_path(path)
        try:
            f = open(filepath, 'rb')
        except IOError:
            raise NotFound

        response = Response(
            wrap_file(frappe.local.request.environ, f), direct_passthrough=True)

    # no need for content disposition and force download. let browser handle its opening.
    # response.headers.add(b'Content-Disposition', b'attachment', filename=filename.encode("utf-8"))

    response.mimetype = mimetypes.guess_type(
        filename)[0] or b'application/octet-stream'

    return response
コード例 #7
0
	def get_favicon(self, request):
		f = path.join(self.www_dp, 'icons', 'loris-icon.png')
		r = Response(file(f), content_type='image/x-icon')
		if self.enable_caching:
			r.add_etag()
			r.make_conditional(request)
		return r
コード例 #8
0
ファイル: api.py プロジェクト: vikvns/hackathon
def list_products():
    status = 200
    subcat = request.args['subcat']
    resp_json = random.sample(subcat_dict[subcat], 100)
    response = Response(json.dumps(resp_json), mimetype="application/json", status=status)
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response
コード例 #9
0
ファイル: response.py プロジェクト: ESS-LLP/frappe
def as_txt():
	response = Response()
	response.mimetype = 'text'
	response.charset = 'utf-8'
	response.headers["Content-Disposition"] = ("attachment; filename=\"%s.txt\"" % frappe.response['doctype'].replace(' ', '_')).encode("utf-8")
	response.data = frappe.response['result']
	return response
コード例 #10
0
ファイル: test_fixers.py プロジェクト: 2009bpy/werkzeug
    def test_proxy_fix(self):
        @Request.application
        def app(request):
            return Response('%s|%s' % (
                request.remote_addr,
                # do not use request.host as this fixes too :)
                request.environ['HTTP_HOST']
            ))
        app = fixers.ProxyFix(app, num_proxies=2)
        environ = dict(
            create_environ(),
            HTTP_X_FORWARDED_PROTO="https",
            HTTP_X_FORWARDED_HOST='example.com',
            HTTP_X_FORWARDED_FOR='1.2.3.4, 5.6.7.8',
            REMOTE_ADDR='127.0.0.1',
            HTTP_HOST='fake'
        )

        response = Response.from_app(app, environ)

        assert response.get_data() == b'1.2.3.4|example.com'

        # And we must check that if it is a redirection it is
        # correctly done:

        redirect_app = redirect('/foo/bar.hml')
        response = Response.from_app(redirect_app, environ)

        wsgi_headers = response.get_wsgi_headers(environ)
        assert wsgi_headers['Location'] == 'https://example.com/foo/bar.hml'
コード例 #11
0
ファイル: utils.py プロジェクト: 08haozi/uliweb
def redirect(location, code=302):
    """Return a response object (a WSGI application) that, if called,
    redirects the client to the target location.  Supported codes are 301,
    302, 303, 305, and 307.  300 is not supported because it's not a real
    redirect and 304 because it's the answer for a request with a request
    with defined If-Modified-Since headers.

    .. versionadded:: 0.6
       The location can now be a unicode string that is encoded using
       the :func:`iri_to_uri` function.

    :param location: the location the response should redirect to.
    :param code: the redirect status code. defaults to 302.
    """
    from werkzeug.wrappers import Response
    display_location = escape(location)
    if isinstance(location, text_type):
        from werkzeug.urls import iri_to_uri
        location = iri_to_uri(location)
    response = Response(
        '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'
        '<title>Redirecting...</title>\n'
        '<h1>Redirecting...</h1>\n'
        '<p>You should be redirected automatically to target URL: '
        '<a href="%s">%s</a>.  If not click the link.' %
        (escape(location), display_location), code, mimetype='text/html')
    response.headers['Location'] = location
    return response
コード例 #12
0
ファイル: gunicorn.py プロジェクト: SunDwarf/Kyoukai
    def run_application(self, environment: dict, start_response: typing.Callable) -> asyncio.Task:
        """
        Runs Kyoukai for the current request.

        This is **not** a coroutine - it returns a single item (a Task), which is awaited on to get 
        the response.

        :param environment: The WSGI environment to run this request with.
        :param start_response: A callable that can be used to start the response.
        :return: A new :class:`asyncio.Task` that can be awaited on to get a response from the \
        application.
        """
        is_async = environment.get("wsgi.async", False)

        if not is_async:
            # Damnit. Return a WSGI response that ells the user they're stupid.
            r = Response("<h1>Error</h1><br/>You did not use the <code>gaiohttp</code> "
                         "gunicorn worker. This is an "
                         "error! Please switch to the gaiohttp worker instead.")
            r.headers["Content-Type"] = "text/html; charset=utf-8"
            r.status_code = 500
            return r(environment, start_response)

        coro = self._run_application(environment, start_response)

        loop = asyncio.get_event_loop()
        t = loop.create_task(coro)

        environment["kyoukai.task"] = t

        return t
コード例 #13
0
ファイル: task_type_api.py プロジェクト: acube-unipi/oii-web
    def wsgi_app(self, environ, start_response):
        """Execute this instance as a WSGI application.

        See the PEP for the meaning of parameters. The separation of
        __call__ and wsgi_app eases the insertion of middlewares.

        """
        urls = self._url_map.bind_to_environ(environ)
        try:
            endpoint, args = urls.match()
        except HTTPException as exc:
            return exc

        assert endpoint == "get"

        request = Request(environ)
        request.encoding_errors = "strict"

        response = Response()

        result = dict()
        for task_type in self._task_types:
            result[task_type.__name__] = \
                list(p.describe() for p in task_type.ACCEPTED_PARAMETERS)

        response.status_code = 200
        response.mimetype = "application/json"
        response.data = json.dumps(result)

        return response
コード例 #14
0
ファイル: api.py プロジェクト: vikvns/hackathon
def refine():
    pog_ids = [];
    target_cat = request.args['target_cat']
    if target_cat == "top":
        if 'footwear_pog_id' in request.args:
            footwear_pog_id = request.args['footwear_pog_id']
            pog_ids = nn_dict[footwear_pog_id]['top']
        elif 'bottom_pog_id' in request.args:
            bottom_pog_id = request.args['bottom_pog_id']
            pog_ids = nn_dict[bottom_pog_id]['top']
    elif target_cat == "bottom":
        if 'footwear_pog_id' in request.args:
            footwear_pog_id = request.args['footwear_pog_id']
            pog_ids = nn_dict[footwear_pog_id]['bottom']     
        elif 'top_pog_id' in request.args:
            top_pog_id = request.args['top_pog_id']
            pog_ids = nn_dict[top_pog_id]['bottom']

    elif target_cat == "footwear":
        if 'bottom_pog_id' in request.args:
            bottom_pog_id = request.args['bottom_pog_id']
            pog_ids = nn_dict[bottom_pog_id]['footwear']
        elif 'top_pog_id' in request.args:
            top_pog_id = request.args['top_pog_id']
            pog_ids = nn_dict[top_pog_id]['footwear']

    data = {target_cat: [pog_dict[pog_id]['details'] for pog_id in pog_ids]}
    status = 200
    response = Response(json.dumps(data), mimetype="application/json", status=status)
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response
コード例 #15
0
ファイル: server.py プロジェクト: sinistersnare/PieCrust2
    def _try_special_request(self, environ, request):
        static_mount = '/__piecrust_static/'
        if request.path.startswith(static_mount):
            rel_req_path = request.path[len(static_mount):]
            mount = os.path.join(RESOURCES_DIR, 'server')
            full_path = os.path.join(mount, rel_req_path)
            try:
                response = self._make_wrapped_file_response(
                        environ, request, full_path)
                return response
            except OSError:
                pass

        debug_mount = '/__piecrust_debug/'
        if request.path.startswith(debug_mount):
            rel_req_path = request.path[len(debug_mount):]
            if rel_req_path == 'pipeline_status':
                from piecrust.serving.procloop import (
                        PipelineStatusServerSideEventProducer)
                provider = PipelineStatusServerSideEventProducer(
                        self._proc_loop.status_queue)
                it = ClosingIterator(provider.run(), [provider.close])
                response = Response(it)
                response.headers['Cache-Control'] = 'no-cache'
                if 'text/event-stream' in request.accept_mimetypes:
                    response.mimetype = 'text/event-stream'
                response.direct_passthrough = True
                response.implicit_sequence_conversion = False
                return response

        return None
コード例 #16
0
ファイル: api.py プロジェクト: vikvns/hackathon
def get_pog_info():
    pog_ids = request.args.getlist('pog_ids')
    resp_json = [pog_dict[pog_id]['details'] for pog_id in pog_ids]
    status = 200
    response = Response(json.dumps(resp_json), mimetype="application/json", status=status)
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response
コード例 #17
0
ファイル: ninja.py プロジェクト: dingweihua/l2py
 def index(self, request):
     # werkzeug have a low level session support,
     # you need send session id to browser cookie manually
     sid = request.cookies.get(self.COOKIE_NAME)
     if sid is None:
         # don't have a session id, create new session
         request.session = session_store.new()
     else:
         request.session = session_store.get_session(sid)
     if self.LUCKY_NUM_KEY in request.session:
         lucky_num = request.session[self.LUCKY_NUM_KEY]
     else:
         # random a new lucky number,
         # then store it in session
         # when user access again, will use the same lucky number
         lucky_num = random.randint(1, 10)
         request.session[self.LUCKY_NUM_KEY] = lucky_num
     response = Response('Hello, your lucky number is: %s' % (lucky_num,))
     if sid is None:
         # if the user don't have a session id,
         # don't forgot send session id to cookie
         response.set_cookie(self.COOKIE_NAME, request.session.sid)
     # and you should save session manually
     if request.session.should_save:
         session_store.set(request.session.sid, dict(request.session))
     return response
コード例 #18
0
    def __call__(self, environ, start_response):
        path = environ.get('PATH_INFO') or '/'
        method = environ.get('REQUEST_METHOD')
        request = Request(environ)
        response = Response()

        if method == 'POST': # trap all post requests for example
            content_type_header = request.headers.get('Content-Type')

            if not content_type_header:
                response.status_code = 405
                return response(environ, start_response)

            transport = TIOStreamTransport(request.stream, response.stream)
            if 'application/x-thrift' in content_type_header:
                protocol = TBinaryProtocol.TBinaryProtocol(transport)
            elif 'application/json' in content_type_header:
                protocol = TJSONProtocol.TJSONProtocol(transport)
            else:
                response.status_code = 405
                return response(environ, start_response)

            self.bb_processor.process(protocol, protocol)
            return response(environ, start_response)
        else:
            return self.app(environ, start_response)
コード例 #19
0
ファイル: web.py プロジェクト: jdotpy/watchtower
 def handle(self, request):
     request.app = self
     response = self.dashboard(request)
     if isinstance(response, str):
         response = Response(response)
     response.headers['Content-Type'] = 'text/html'
     return response
コード例 #20
0
ファイル: response.py プロジェクト: vhrspvl/vhrs-frappe
def as_binary():
    response = Response()
    response.mimetype = 'application/octet-stream'
    response.headers[b"Content-Disposition"] = (
        "filename=\"%s\"" % frappe.response['filename'].replace(' ', '_')).encode("utf-8")
    response.data = frappe.response['filecontent']
    return response
コード例 #21
0
ファイル: test.py プロジェクト: wrighting/cas_wsgi_middleware
def ignored_callback(environ, start_response):
    response = Response('{"Error":"NotAuthenticated"}')
#    response.status = '401 Unauthorized'
    response.status = '200 OK'
    response.headers['Content-Type'] = 'application/json'

    return response(environ, start_response)
コード例 #22
0
ファイル: RankingWebServer.py プロジェクト: alex-liao/cms
    def wsgi_app(self, environ, start_response):
        route = self.router.bind_to_environ(environ)
        try:
            endpoint, args = route.match()
        except HTTPException as exc:
            return exc

        request = Request(environ)
        request.encoding_errors = "strict"

        response = Response()
        response.headers[b'X-Frame-Options'] = b'SAMEORIGIN'

        try:
            if endpoint == "get":
                self.get(request, response, args["key"])
            elif endpoint == "get_list":
                self.get_list(request, response)
            elif endpoint == "put":
                self.put(request, response, args["key"])
            elif endpoint == "put_list":
                self.put_list(request, response)
            elif endpoint == "delete":
                self.delete(request, response, args["key"])
            elif endpoint == "delete_list":
                self.delete_list(request, response)
            else:
                raise RuntimeError()
        except HTTPException as exc:
            return exc

        return response
コード例 #23
0
 def test_date_no_clobber(self):
     r = Response()
     r.date = 0
     r.last_modified = 0
     v.add_date_fields(r)
     self.assertEquals(r.date.year, 1970)
     self.assertEquals(r.last_modified.year, 1970)
コード例 #24
0
ファイル: test_test.py プロジェクト: pallets/werkzeug
def cookie_app(environ, start_response):
    """A WSGI application which sets a cookie, and returns as a response any
    cookie which exists.
    """
    response = Response(environ.get("HTTP_COOKIE", "No Cookie"), mimetype="text/plain")
    response.set_cookie("test", "test")
    return response(environ, start_response)
コード例 #25
0
ファイル: soapyfy.py プロジェクト: Torlus/soapyfy
def application(request):
    if request.method == 'GET':
        path = list(filter((lambda x: len(x) > 0), re.split('/+', request.path)))
        if len(path) == 0:
            return view_root(request)
        elif len(path) >= 1 and path[0] == 'messages':
            if len(path) == 1:
                return view_messages_list(request)
            elif len(path) == 2:
                return view_message(request, path[1])
            elif len(path) == 3 and path[2] == 'editor':
                return edit_message(request, path[1])
            else:
                return NotFound()
        elif len(path) >= 1 and path[0] == 'services':
            if len(path) == 1:
                return view_services_list(request)
            elif len(path) == 2:
                return view_ports_list(request, path[1])
            elif len(path) == 3:
                return view_operations_list(request, path[1], path[2])
            else:
                return NotFound()
        else:
            return NotFound()
    elif request.method == 'POST':
        return Response('post')
    else:
        response = Response()
        response.status_code = 400
        return response
コード例 #26
0
def application(request):
    logger = logging.getLogger('presence_detection')
    logger.setLevel(logging.INFO)
    fh = logging.FileHandler(os.path.expanduser('~/presence2/log/presence_detection.log'),mode='a', encoding=None, delay=False)
    formatter = logging.Formatter('%(asctime)s - %(levelname)r - %(message)s')
    fh.setFormatter(formatter)
    logger.addHandler(fh)

    rsa_key='AAAAB3NzaC1yc2EAAAADAQABAAAAgwCjvHkbqL/V0ytnfa5pIak7bxBfj6nF4S7vy51ZG8LlWYAXcQ9WGfUGfhG+l1GW9hPeQzQbeRyNiQM+ufue/M9+JKCXTIugksAnN3W+NV/DeDcq9sKR9MiiNH3ZeNtGSyPGYjcLVmK6aSVTUoEO2yRrha9fiWBy5hb93UdmJX+QguC9'
    router_address='makerbar.berthartm.org'
    router_port = 2222
    stdin, stdout, stderr =get_router_mac_addresses(rsa_key,router_address,router_port)

    usermap = get_dict()
    attendance = set()
    for line in stdout:
        MAC = line[10:27]
        if MAC in usermap:
            attendance.add(usermap[MAC])
            logger.info('%s (%s) is at the MakerBar.' % (usermap[MAC],MAC))
        else:
            logger.info('Unknown user(%s) is at the MakerBar.' % MAC)

    output = ''
    for user in attendance:
        output += user + '\n'
    response = Response(output)
    if output == '':
        response.status_code = 204 # No content

    fh.close()
    return response
コード例 #27
0
ファイル: handle_base.py プロジェクト: AKST/wiki-timelapse
 def __build_response(self, output):
     res = Response(output)
     res.content_type = self.content_type
     res.expires = datetime.today() + timedelta(7)
     for header, value in self.__headers:
         res.headers[header] = value
     return res
コード例 #28
0
ファイル: controllers.py プロジェクト: hoangtk/metro-test
 def index(self, request, file_name, file_data):
     pdf_data = open(file_data,'rb').read()
     response = Response(pdf_data)
     response.headers['Content-Type'] = 'application/pdf'
     #response.headers['Content-Disposition'] = 'attachment; filename="%s.pdf"'%file_name
     response.headers['Content-Disposition'] = content_disposition(file_name, request)
     return response
コード例 #29
0
ファイル: web.py プロジェクト: petrushev/plate
 def response(self):
     try:
         return self._getStaticResponse()
     except (OSError, IOError):
         rs = Response('Not found')
         rs.status_code = 404
         return rs
コード例 #30
0
ファイル: test.py プロジェクト: poffdeluxe/werkzeug
def cookie_app(environ, start_response):
    """A WSGI application which sets a cookie, and returns as a ersponse any
    cookie which exists.
    """
    response = Response(environ.get('HTTP_COOKIE', 'No Cookie'),
                        mimetype='text/plain')
    response.set_cookie('test', 'test')
    return response(environ, start_response)
コード例 #31
0
 def render_template(self, template_name, **context):
     t = self.jinja_env.get_template(template_name)
     return Response(t.render(context), mimetype="text/html")
コード例 #32
0
 def paste_traceback(self, request, traceback):
     """Paste the traceback and return a JSON response."""
     paste_id = traceback.paste()
     return Response('{"url": "http://paste.pocoo.org/show/%s/", "id": %s}' % (paste_id, paste_id), mimetype='application/json')
コード例 #33
0
    def register_user_availability(self, request):
        data = json.loads(request.get_data(as_text=True))
        response = self.users_rpc.register_availability(data)

        return Response(status=response['status'], mimetype='text/plain')
コード例 #34
0
 def default(self, environ, start_response):
     resp = Response("\n".join(self.isso.keys()),
                     404,
                     content_type="text/plain")
     return resp(environ, start_response)
コード例 #35
0
 def execute_command(self, request, command, frame):
     """Execute a command in a console."""
     return Response(frame.console.eval(command), mimetype='text/html')
コード例 #36
0
 def app(request):
     return Response('%s|%s' % (
         request.remote_addr,
         # do not use request.host as this fixes too :)
         request.environ['HTTP_HOST']))
コード例 #37
0
def path_check_app(request):
    return Response('PATH_INFO: %s\nSCRIPT_NAME: %s' % (request.environ.get(
        'PATH_INFO', ''), request.environ.get('SCRIPT_NAME', '')))
コード例 #38
0
def multi_value_post_app(environ, start_response):
    req = Request(environ)
    assert req.form['field'] == 'val1', req.form['field']
    assert req.form.getlist('field') == ['val1', 'val2'], req.form.getlist('field')
    response = Response('ok')
    return response(environ, start_response)
コード例 #39
0
def external_subdomain_redirect_demo_app(environ, start_response):
    if 'test.example.com' in environ['HTTP_HOST']:
        response = Response('redirected successfully to subdomain')
    else:
        response = redirect('http://test.example.com/login')
    return response(environ, start_response)
コード例 #40
0
 def get_colors(self):
     custom_css = ''
     current_user = request.env['res.users'].sudo().search([('id', '=', request.context.get('uid'))])
     if current_user and current_user[0].company_color_theme:
         custom_css = current_user[0].company_color_theme.css
     return Response(str(custom_css), mimetype='text/css')
コード例 #41
0
def render_template(template, **context):
    return Response(jinja_env.get_template(template).render(**context),
                    mimetype='text/html')
コード例 #42
0
ファイル: leanengine.py プロジェクト: Ma233/python-sdk
    def dispatch_request(self, environ):
        request = environ['leanengine.request']
        app_params = environ['_app_params']
        adapter = self.url_map.bind_to_environ(request.environ)
        try:
            endpoint, values = adapter.match()
        except HTTPException as e:
            return e

        params = request.get_data(as_text=True)
        values['params'] = json.loads(params) if params != '' else {}

        try:
            if endpoint == 'cloud_function':
                result = {
                    'result':
                    dispatch_cloud_func(self.cloud_codes,
                                        app_params,
                                        decode_object=False,
                                        **values)
                }
            elif endpoint == 'rpc_function':
                result = {
                    'result':
                    dispatch_cloud_func(self.cloud_codes,
                                        app_params,
                                        decode_object=True,
                                        **values)
                }
            elif endpoint == 'cloud_hook':
                result = dispatch_cloud_hook(self.cloud_codes, app_params,
                                             **values)
            elif endpoint == 'on_verified':
                result = {
                    'result':
                    dispatch_on_verified(self.cloud_codes, app_params,
                                         **values)
                }
            elif endpoint == 'on_login':
                result = {
                    'result':
                    dispatch_on_login(self.cloud_codes, app_params, **values)
                }
            elif endpoint == 'ops_meta_data':
                from .authorization import MASTER_KEY
                if request.environ.get('_app_params',
                                       {}).get('master_key') != MASTER_KEY:
                    raise LeanEngineError(code=401, message='Unauthorized.')
                result = {'result': dispatch_ops_meta_data(self.cloud_codes)}
            elif endpoint == 'on_bigquery':
                result = {
                    'result':
                    dispatch_on_bigquery(self.cloud_codes, app_params,
                                         **values)
                }
            else:
                raise ValueError  # impossible
            return Response(json.dumps(result), mimetype='application/json')
        except LeanEngineError as e:
            return Response(json.dumps({
                'code': e.code,
                'error': e.message
            }),
                            status=e.code if e.code else 400,
                            mimetype='application/json')
        except Exception:
            print(traceback.format_exc(), file=sys.stderr)
            return Response(json.dumps({
                'code':
                141,
                'error':
                'Cloud Code script had an error.'
            }),
                            status=500,
                            mimetype='application/json')
コード例 #43
0
def test_expected_request_response(httpserver: HTTPServer):
    httpserver.expect_request("/foobar").respond_with_response(Response(JSON_STRING))
    assert requests.get(httpserver.url_for("/foobar")).json() == {'foo': 'bar'}
コード例 #44
0
 def __call__(self, environ, start_response):
     if wsgi.get_path_info(environ).startswith(self._prefixes):
         resp = Response(self._template, status=451, mimetype='text/html')
         return resp(environ, start_response)
     return self.application(environ, start_response)
コード例 #45
0
 def h_full_response(_):
     return Response(self.raw_data, status=requests.codes.OK)
コード例 #46
0
 def test_app(request):
     return Response(request.form.get('x', None))
コード例 #47
0
 def app(request):
     return Response(request.remote_addr)
コード例 #48
0
 def test_app(request):
     return Response(request.args['x'])
コード例 #49
0
 def test_cgi_root_fix_custom_app_root(self):
     app = fixers.CGIRootFix(path_check_app, app_root='/baz/poop/')
     response = Response.from_app(
         app, dict(create_environ(), SCRIPT_NAME='/foo', PATH_INFO='/bar'))
     self.assert_equal(response.get_data(),
                       b'PATH_INFO: /foo/bar\nSCRIPT_NAME: baz/poop')
コード例 #50
0
 def test_app(request):
     return Response(str(request.environ['werkzeug._foo']))
コード例 #51
0
 def application(request):
     return Response("", headers=[('X-Foo', 'bar')])
コード例 #52
0
 def test_app(request):
     response = Response(repr(sorted(request.cookies.items())))
     response.set_cookie(u'test1', b'foo')
     response.set_cookie(u'test2', b'bar')
     return response
コード例 #53
0
 def display_console(self, request):
     """Display a standalone shell."""
     if 0 not in self.frames:
         self.frames[0] = _ConsoleFrame(self.console_init_func())
     return Response(render_template('console.html'), mimetype='text/html')
コード例 #54
0
ファイル: wzrkzeug_module.py プロジェクト: zhubiaook/python
def application(environ, start_response):
    response = Response('Hello World!', mimetype='text/plain')
    return response(environ, start_response)
コード例 #55
0
 def get_source(self, request, frame):
     """Render the source viewer."""
     return Response(frame.render_source(), mimetype='text/html')
コード例 #56
0
ファイル: wzrkzeug_module.py プロジェクト: zhubiaook/python
 def dispatch_request(self, request):
     return Response('Hello World')
コード例 #57
0
    def get_user_availability(self, request, user_id):
        response = self.users_rpc.get_availability(user_id)

        return Response(json.dumps({'availability': response['availability']}),
                        status=response['status'],
                        mimetype='text/plain')
コード例 #58
0
ファイル: server.py プロジェクト: tef/rson-rpc
 def error_response(self, exception, trace):
     return Response(trace, status='500 not ok (%s)' % exception)
コード例 #59
0
 def on_logout(self, request):
     return Response(
         response="You are logged out.",
         status=401,
     )
コード例 #60
0
    def get_users_by_role(self, request, role):
        response = self.users_rpc.get_by_role(role)

        return Response(json.dumps({'users': response['users']}),
                        status=response['status'],
                        mimetype='text/plain')