Beispiel #1
0
def plaintext(request):
    """Test type 6: Plaintext"""
    return Response(text='Hello, World!')
Beispiel #2
0
 async def get_hello(self, request):
     return Response(text="world")
Beispiel #3
0
async def req_ok(request):
    return Response(text='ok')
Beispiel #4
0
def test_nonstr_text_in_ctor():
    with pytest.raises(TypeError):
        Response(text=b'data')
Beispiel #5
0
def test_text_in_ctor_with_content_type_header():
    resp = Response(text='текст',
                    headers={'Content-Type': 'text/html; charset=koi8-r'})
    assert 'текст'.encode('koi8-r') == resp.body
    assert 'text/html' == resp.content_type
    assert 'koi8-r' == resp.charset
Beispiel #6
0
def test_ctor_charset_in_content_type():
    with pytest.raises(ValueError):
        Response(text='test test', content_type='text/plain; charset=utf-8')
Beispiel #7
0
def test_ctor_both_content_type_param_and_header():
    with pytest.raises(ValueError):
        Response(headers={'Content-Type': 'application/json'},
                 content_type='text/html')
Beispiel #8
0
async def handle_webhook(
    hass: HomeAssistantType, webhook_id: str, request: Request
) -> Response:
    """Handle webhook callback."""
    if webhook_id in hass.data[DOMAIN][DATA_DELETED_IDS]:
        return Response(status=410)

    config_entry = hass.data[DOMAIN][DATA_CONFIG_ENTRIES][webhook_id]

    device_name = config_entry.data[ATTR_DEVICE_NAME]

    try:
        req_data = await request.json()
    except ValueError:
        _LOGGER.warning("Received invalid JSON from mobile_app device: %s", device_name)
        return empty_okay_response(status=HTTP_BAD_REQUEST)

    if (
        ATTR_WEBHOOK_ENCRYPTED not in req_data
        and config_entry.data[ATTR_SUPPORTS_ENCRYPTION]
    ):
        _LOGGER.warning(
            "Refusing to accept unencrypted webhook from %s",
            device_name,
        )
        return error_response(ERR_ENCRYPTION_REQUIRED, "Encryption required")

    try:
        req_data = WEBHOOK_PAYLOAD_SCHEMA(req_data)
    except vol.Invalid as ex:
        err = vol.humanize.humanize_error(req_data, ex)
        _LOGGER.error(
            "Received invalid webhook from %s with payload: %s", device_name, err
        )
        return empty_okay_response()

    webhook_type = req_data[ATTR_WEBHOOK_TYPE]

    webhook_payload = req_data.get(ATTR_WEBHOOK_DATA, {})

    if req_data[ATTR_WEBHOOK_ENCRYPTED]:
        enc_data = req_data[ATTR_WEBHOOK_ENCRYPTED_DATA]
        webhook_payload = _decrypt_payload(config_entry.data[CONF_SECRET], enc_data)

    if webhook_type not in WEBHOOK_COMMANDS:
        _LOGGER.error(
            "Received invalid webhook from %s of type: %s", device_name, webhook_type
        )
        return empty_okay_response()

    _LOGGER.debug(
        "Received webhook payload from %s for type %s: %s",
        device_name,
        webhook_type,
        webhook_payload,
    )

    # Shield so we make sure we finish the webhook, even if sender hangs up.
    return await asyncio.shield(
        WEBHOOK_COMMANDS[webhook_type](hass, config_entry, webhook_payload)
    )
Beispiel #9
0
 def post(self):
     return Response()
Beispiel #10
0
async def simple(request):
    return Response(text="Simple answer")
Beispiel #11
0
async def change_body(request):
    resp = Response()
    resp.body = b"Body changed"
    resp.content_type = 'text/plain'
    return resp
Beispiel #12
0
 async def uploadfile(self, request: Request):
     name: str = str(request.query.get("name", "test"))
     self.files[name] = await self.readAll(request)
     return Response(text="")
Beispiel #13
0
    async def post(self) -> Response:
        request = self.request
        ctype = request.headers.get('content-type')

        logger.debug('Request Content-Type: %s', ctype)

        form: MultiDictProxy

        if ctype == 'application/json':
            try:
                data: Any = await request.json()
                if not isinstance(data, dict):
                    raise ValueError('Invalid request type')
            except ValueError as e:
                logger.warning('Invalid request: %s', e)
                raise HTTPBadRequest(reason='Invalid request') from e
            else:
                form = MultiDictProxy(MultiDict(cast(Dict, data)))

        elif ctype == 'application/x-www-form-urlencoded':
            form = await self.request.post()

        else:
            raise HTTPBadRequest(reason='Invalid content type')

        logger.debug('Form is: %s', form)

        user = await self.request.app['store'].users.create(
            **{
                'username': form.get('username'),
                'password': form.get('password'),
                'given_name': form.get('given_name'),
                'patronymic': form.get('patronymic'),
                'family_name': form.get('family_name')
            })
        await self.request.app['store'].users.put(user)

        if 'next' in form:
            response = Response(status=303,
                                reason='See Other',
                                charset='utf-8',
                                headers={
                                    'Location':
                                    '{}?{}'.format(
                                        form.get('next'),
                                        urlencode({'state': form.get('state')},
                                                  doseq=True))
                                })
        else:
            accepts = parse_accept(request.headers.get('Accept'))
            ctype = choice_content_type(accepts,
                                        ['application/json', 'text/plain'])
            logger.debug('Content-type for response is: %s', ctype)

            if ctype == 'application/json':
                user_dict = asdict(user)
                user_dict.pop('crypt')
                user_dict.pop('salt')
                response = json_response({
                    'meta': {
                        'status': 'ok'
                    },
                    'data': user_dict
                })

            else:
                response = Response(text='Login successful')

        self.set_cookie(self.request, response, user.get_id())

        return response
Beispiel #14
0
 async def post(self):
     data = await self.request.post()
     # if 'username' in data:
     session = await get_session(self.request)
     session['username'] = data['username']
     return Response(text='Chat')
Beispiel #15
0
def test_ctor_charset():
    resp = Response(text='текст', charset='koi8-r')

    assert 'текст'.encode('koi8-r') == resp.body
    assert 'koi8-r' == resp.charset
Beispiel #16
0
 def handler(request):
     return Response(request)  # pragma: no cover
Beispiel #17
0
def test_ctor_charset_default_utf8():
    resp = Response(text='test test', charset=None)

    assert 'utf-8' == resp.charset
Beispiel #18
0
def empty_okay_response(headers: Dict = None, status: int = 200) -> Response:
    """Return a Response with empty JSON object and a 200."""
    return Response(text='{}',
                    status=status,
                    content_type='application/json',
                    headers=headers)
Beispiel #19
0
def test_ctor_charset_without_text():
    resp = Response(content_type='text/plain', charset='koi8-r')

    assert 'koi8-r' == resp.charset
Beispiel #20
0
async def get_status(request: Request) -> Response:
    return Response(text="OK")
Beispiel #21
0
def test_ctor_both_charset_param_and_header():
    with pytest.raises(ValueError):
        Response(headers={'Content-Type': 'application/json'},
                 charset='koi8-r')
Beispiel #22
0
 def get(self, request, *args, **kwargs):
     agent = request.headers.get('user-agent', '')
     return Response(text="<H2>Agent: {}</H2>".format(agent))
Beispiel #23
0
def test_text_in_ctor_with_content_type():
    resp = Response(text='data', content_type='text/html')
    assert 'data' == resp.text
    assert 'text/html' == resp.content_type
Beispiel #24
0
 def post(self, request, *args, **kwargs):
     post = request.POST
     files = request.FILES
     return Response(text="<H2>POST: </H2>\n{}\n<H2>FILES: </H2>\n{}\n".format(post, files))
Beispiel #25
0
def test_text_with_empty_payload():
    resp = Response(status=200)
    assert resp.body is None
    assert resp.text is None
Beispiel #26
0
def dump_args_view(request, *args, **kwargs):
    body = u"<h3>Arguments: {}</h3><h3>Keywords: {}</h3>".format(args, kwargs)
    return Response(body=body, status=200)
Beispiel #27
0
async def plaintext(request):
    """
    Test 6
    """
    return Response(body=b'Hello, World!', content_type='text/plain')
Beispiel #28
0
def test_ctor_text_body_combined():
    with pytest.raises(ValueError):
        Response(body=b'123', text='test text')
Beispiel #29
0
async def html(request):
    """Return HTML content and a custom header."""
    content = "<b>HTML OK</b>"
    headers = {'x-time': f"{time.time()}"}
    return Response(text=content, content_type="text/html", headers=headers)
 async def error(self, request: Request):
     try:
         self.logReport(request, await request.json())
     except BaseException as e:
         self.logError(request, e)
     return Response()