Exemple #1
0
    def _render(elem, level, first, use_level):
        tag = get_alias(elem.tag)
        attrib = [
            '{}={}'.format(get_alias(k), bstr(quoteattr(v), 'utf-8'))
            for k, v in sorted(elem.attrib.items())
        ]
        attrib = ((' ' + ' '.join(attrib)) if attrib else '').decode('utf-8')
        if first:
            ns = ' ' + ' '.join(
                'xmlns{}={}'.format((':' + v) if v else v, quoteattr(k))
                for k, v in ns_aliases.items())
        else:
            ns = ''

        if use_level:
            nl = '\n' + ident * level
        else:
            nl = ''

        txt = elem.text
        txt = escape(txt) if txt and txt.strip() else ''

        tail = txt
        has_children = False
        for child in elem:
            if not has_children:
                out.write(u'{}<{}{}{}>{}'.format(nl, tag, ns, attrib,
                                                 txt).encode('utf-8'))
            has_children = True
            _render(child, level + 1, False, not tail)
            tail = child.tail
            tail = escape(txt) if tail and tail.strip() else ''
            if tail:
                out.write(bstr(tail, 'utf-8'))

        if has_children:
            if not tail:
                nl = '\n' + ident * level
            else:
                nl = ''

            out.write(u'{}</{}>'.format(nl, tag, txt).encode('utf-8'))
        else:
            if txt:
                out.write(u'{}<{}{}{}>{}</{}>'.format(nl, tag, ns, attrib, txt,
                                                      tag).encode('utf-8'))
            else:
                out.write(u'{}<{}{}{}/>'.format(nl, tag, ns, attrib,
                                                txt).encode('utf-8'))

        return txt
Exemple #2
0
    def _render(elem, level, first, use_level):
        tag = get_alias(elem.tag)
        attrib = ['{}={}'.format(get_alias(k), sstr(quoteattr(v), 'utf-8'))
                  for k, v in sorted(elem.attrib.items())]
        attrib = ustr((' ' + ' '.join(attrib)) if attrib else '', 'utf-8')
        if first:
            ns = ' ' + ' '.join('xmlns{}={}'.format((':' + v) if v else v, quoteattr(k))
                                for k, v in ns_aliases.items())
        else:
            ns = ''

        if use_level:
            nl = '\n' + ident * level
        else:
            nl = ''

        txt = elem.text
        txt = escape(txt) if txt and txt.strip() else ''

        tail = txt
        has_children = False
        for child in elem:
            if not has_children:
                out.write(u'{}<{}{}{}>{}'.format(nl, tag, ns, attrib, txt).encode('utf-8'))
            has_children = True
            _render(child, level+1, False, not tail)
            tail = child.tail
            tail = escape(txt) if tail and tail.strip() else ''
            if tail:
                out.write(bstr(tail, 'utf-8'))

        if has_children:
            if not tail:
                nl = '\n' + ident * level
            else:
                nl = ''

            out.write(u'{}</{}>'.format(nl, tag, txt).encode('utf-8'))
        else:
            if txt:
                out.write(u'{}<{}{}{}>{}</{}>'.format(nl, tag, ns, attrib, txt, tag).encode('utf-8'))
            else:
                out.write(u'{}<{}{}{}/>'.format(nl, tag, ns, attrib, txt).encode('utf-8'))

        return txt
Exemple #3
0
def encode_multipart(fields, files, boundary=None):
    r"""Encode dict of form fields and dict of files as multipart/form-data.
    Return tuple of (body_string, headers_dict). Each value in files is a dict
    with required keys 'filename' and 'content', and optional 'mimetype' (if
    not specified, tries to guess mime type or uses 'application/octet-stream').

    >>> body, headers = encode_multipart({'FIELD': 'VALUE'},
    ...                                  {'FILE': {'filename': 'F.TXT', 'content': 'CONTENT'}},
    ...                                  boundary='BOUNDARY')
    >>> print('\n'.join(repr(l) for l in body.split('\r\n')))
    '--BOUNDARY'
    'Content-Disposition: form-data; name="FIELD"'
    ''
    'VALUE'
    '--BOUNDARY'
    'Content-Disposition: form-data; name="FILE"; filename="F.TXT"'
    'Content-Type: text/plain'
    ''
    'CONTENT'
    '--BOUNDARY--'
    ''
    >>> print(sorted(headers.items()))
    [('Content-Length', '193'), ('Content-Type', 'multipart/form-data; boundary=BOUNDARY')]
    >>> len(body)
    193
    """
    def escape_quote(s):
        return bstr(s).replace(b'"', b'\\"')

    if boundary is None:
        boundary = ''.join(random.choice(_BOUNDARY_CHARS) for i in range(30)).encode('latin1')
    lines = []

    for name, value in fields:
        lines.extend((
            b'--%s' % boundary,
            b'Content-Disposition: form-data; name="%s"' % escape_quote(name),
            b'',
            bstr(value, 'utf-8'),
        ))

    for name, value in files:
        filename = value['filename']
        if 'mimetype' in value:
            mimetype = value['mimetype']
        else:
            mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
        lines.extend((
            b'--%s' % boundary,
            b'Content-Disposition: form-data; name="%s"; filename="%s"' % (
                    escape_quote(name), escape_quote(filename)),
            b'Content-Type: %s' % (bstr(mimetype)),
            b'',
            value['content'],
        ))

    lines.extend((
        b'--%s--' % boundary,
        b'',
    ))
    body = b'\r\n'.join(lines)

    headers = {
        b'Content-Type': b'multipart/form-data; boundary=%s' % boundary,
        b'Content-Length': bstr(str(len(body))),
    }

    return (body, headers)
Exemple #4
0
 def escape_quote(s):
     return bstr(s).replace(b'"', b'\\"')
Exemple #5
0
def basic_auth(user, password):
    from base64 import b64encode
    return b'Authorization: Basic ' + b64encode(b'%s:%s' %
                                                (bstr(user), bstr(password)))
Exemple #6
0
def http():
    lines = vim.current.buffer[:]
    line, _ = vim.current.window.cursor
    line -= 1

    headers, templates = get_headers_and_templates(lines, line)
    pwd_func = lambda p: vfunc.inputsecret('{}: '.format(p))
    input_func = lambda p: vfunc.input('{}: '.format(p))
    try:
        method, url, query, body, tlist, rend = prepare_request(
            lines, line, headers, input_func, pwd_func)
    except PrepareException as e:
        echoerr(str(e))
        return

    rctx = RequestContext()
    rctx.request(method, url, query, body, headers)

    cwin = vim.current.window

    win, buf = make_scratch('__vial_http_req__', title='Request')
    rlines = rctx.raw_request.splitlines()

    hlines = []
    for r in rctx.history[:-1]:
        hlines.append(
            bstr('Redirect {} from {}'.format(r.status, r.request[1]),
                 'utf-8'))
    if hlines:
        hlines.append(b'----------------')

    buf[:] = hlines + rlines
    win.cursor = 1, 0

    win, buf = make_scratch('__vial_http_hdr__', title='Response headers')
    if PY2:
        buf[:] = [r.rstrip('\r\n') for r in rctx.response.msg.headers]
    else:
        buf[:] = [
            '{}: {}'.format(*r).encode('utf-8')
            for r in rctx.response.msg._headers
        ]

    win.cursor = 1, 0

    size = len(rctx.content)

    win, buf = make_scratch('__vial_http_raw__', title='Raw Response')
    buf[:] = rctx.content.splitlines()
    win.cursor = 1, 0

    if PY2:
        rcontent_type = rctx.response.msg.gettype()
    else:
        rcontent_type = rctx.response.msg.get_content_type()

    content, ctype, jdata = format_content(rcontent_type, rctx.content)

    win, buf = make_scratch('__vial_http__')
    win.options['statusline'] = 'Response: {} {} {}ms {}ms {}'.format(
        rctx.response.status, rctx.response.reason, rctx.ctime, rctx.rtime,
        sizeof_fmt(size))
    vim.command('set filetype={}'.format(ctype))
    buf[:] = content.splitlines(False)
    win.cursor = 1, 0

    focus_window(cwin)

    def set_cookies(*args):
        cookies = rctx.cookies
        args = args or sorted(cookies.keys())
        return 'Cookie: ' + ';'.join('{}={}'.format(k, cookies[k])
                                     for k in args)

    ctx = {
        'body': content,
        'json': jdata,
        'headers': Headers(rctx.response.getheaders()),
        'cookies': rctx.cookies,
        'rcookies': rctx.rcookies,
        'set_cookies': set_cookies
    }

    for t in tlist:
        if t in templates:
            lines = render_template(templates[t], **ctx).splitlines()
        else:
            lines = ['ERROR: template {} not found'.format(t)]
        vfunc.append(rend + 1, [''] + lines)
        rend += 1 + len(lines)
Exemple #7
0
def basic_auth(user, password):
    from base64 import b64encode
    return b'Authorization: Basic ' + b64encode(b'%s:%s' % (bstr(user), bstr(password)))
Exemple #8
0
def http():
    lines = vim.current.buffer[:]
    line, _ = vim.current.window.cursor
    line -= 1

    headers, templates = get_headers_and_templates(lines, line)
    pwd_func = lambda p: vfunc.inputsecret('{}: '.format(p))
    input_func = lambda p: vfunc.input('{}: '.format(p))
    try:
        method, url, query, body, tlist, rend = prepare_request(lines, line, headers, input_func, pwd_func)
    except PrepareException as e:
        echoerr(str(e))
        return

    rctx = RequestContext()
    rctx.request(method, url, query, body, headers)

    cwin = vim.current.window

    win, buf = make_scratch('__vial_http_req__', title='Request')
    rlines = rctx.raw_request.splitlines()

    hlines = []
    for r in rctx.history[:-1]:
        hlines.append(bstr('Redirect {} from {}'.format(
            r.status, r.request[1]), 'utf-8'))
    if hlines:
        hlines.append(b'----------------')

    buf[:] = hlines + rlines
    win.cursor = 1, 0

    win, buf = make_scratch('__vial_http_hdr__', title='Response headers')
    if PY2:
        buf[:] = [r.rstrip('\r\n') for r in rctx.response.msg.headers]
    else:
        buf[:] = ['{}: {}'.format(*r).encode('utf-8') for r in rctx.response.msg._headers]

    win.cursor = 1, 0

    size = len(rctx.content)

    win, buf = make_scratch('__vial_http_raw__', title='Raw Response')
    buf[:] = rctx.content.splitlines()
    win.cursor = 1, 0

    if PY2:
        rcontent_type = rctx.response.msg.gettype()
    else:
        rcontent_type = rctx.response.msg.get_content_type()

    content, ctype, jdata = format_content(rcontent_type, rctx.content)

    win, buf = make_scratch('__vial_http__')
    win.options['statusline'] = 'Response: {} {} {}ms {}ms {}'.format(
        rctx.response.status, rctx.response.reason,
        rctx.ctime, rctx.rtime, sizeof_fmt(size))
    vim.command('set filetype={}'.format(ctype))
    buf[:] = content.splitlines(False)
    win.cursor = 1, 0

    focus_window(cwin)

    def set_cookies(*args):
        cookies = rctx.cookies
        args = args or sorted(cookies.keys())
        return 'Cookie: ' + ';'.join('{}={}'.format(k, cookies[k]) for k in args)

    ctx = {'body': content, 'json': jdata,
           'headers': Headers(rctx.response.getheaders()),
           'cookies': rctx.cookies,
           'rcookies': rctx.rcookies,
           'set_cookies': set_cookies}

    for t in tlist:
        if t in templates:
            lines = render_template(templates[t], **ctx).splitlines()
        else:
            lines = ['ERROR: template {} not found'.format(t)]
        vfunc.append(rend + 1, [''] + lines)
        rend += 1 + len(lines)
Exemple #9
0
def encode_multipart(fields, files, boundary=None):
    r"""Encode dict of form fields and dict of files as multipart/form-data.
    Return tuple of (body_string, headers_dict). Each value in files is a dict
    with required keys 'filename' and 'content', and optional 'mimetype' (if
    not specified, tries to guess mime type or uses 'application/octet-stream').

    >>> body, headers = encode_multipart({'FIELD': 'VALUE'},
    ...                                  {'FILE': {'filename': 'F.TXT', 'content': 'CONTENT'}},
    ...                                  boundary='BOUNDARY')
    >>> print('\n'.join(repr(l) for l in body.split('\r\n')))
    '--BOUNDARY'
    'Content-Disposition: form-data; name="FIELD"'
    ''
    'VALUE'
    '--BOUNDARY'
    'Content-Disposition: form-data; name="FILE"; filename="F.TXT"'
    'Content-Type: text/plain'
    ''
    'CONTENT'
    '--BOUNDARY--'
    ''
    >>> print(sorted(headers.items()))
    [('Content-Length', '193'), ('Content-Type', 'multipart/form-data; boundary=BOUNDARY')]
    >>> len(body)
    193
    """
    def escape_quote(s):
        return bstr(s).replace(b'"', b'\\"')

    if boundary is None:
        boundary = ''.join(random.choice(_BOUNDARY_CHARS)
                           for i in range(30)).encode('latin1')
    lines = []

    for name, value in fields:
        lines.extend((
            b'--%s' % boundary,
            b'Content-Disposition: form-data; name="%s"' % escape_quote(name),
            b'',
            bstr(value, 'utf-8'),
        ))

    for name, value in files:
        filename = value['filename']
        if 'mimetype' in value:
            mimetype = value['mimetype']
        else:
            mimetype = mimetypes.guess_type(
                filename)[0] or 'application/octet-stream'
        lines.extend((
            b'--%s' % boundary,
            b'Content-Disposition: form-data; name="%s"; filename="%s"' %
            (escape_quote(name), escape_quote(filename)),
            b'Content-Type: %s' % (bstr(mimetype)),
            b'',
            value['content'],
        ))

    lines.extend((
        b'--%s--' % boundary,
        b'',
    ))
    body = b'\r\n'.join(lines)

    headers = {
        b'Content-Type': b'multipart/form-data; boundary=%s' % boundary,
        b'Content-Length': bstr(str(len(body))),
    }

    return (body, headers)
Exemple #10
0
 def escape_quote(s):
     return bstr(s).replace(b'"', b'\\"')