Beispiel #1
0
def test_varargs(req, *args):
    var_info = {'len': len(args), 'uri_rule': req.uri_rule}
    var_info.update(req.groups)

    buff = get_header("Variable args test") + \
        (get_crumbnav(req),
         "<h2>Variables</h2>",
         "<table>") + \
        tuple("<tr><td>%s:</td><td>%s</td></tr>" %
              (key, html(val)) for key, val in var_info.items()) + \
        ("</table>",
         "<h2>Browser Headers</h2>",
         "<table>") + \
        tuple("<tr><td>%s:</td><td>%s</td></tr>" %
              (key, val) for key, val in req.headers.items()) + \
        ("</table>",
         "<h2>Request Variables </h2>",
         "<table>") + \
        tuple("<tr><td>%s:</td><td>%s</td></tr>" %
              (key, val) for key, val in get_variables(req)) + \
        ("</table>",) + \
        get_footer()

    response = Response()
    for line in buff:
        response.write(line + '\n')
    return response
Beispiel #2
0
def test_dynamic(req, variable=None):
    var_info = {
        'type': type(variable),
        'value': variable,
        'uri_rule': req.uri_rule
    }

    title = "Variable" if variable is not None else "Static"

    buff = get_header(title + " test") + \
        (get_crumbnav(req),
         "<h2>Variable</h2>",
         "<table>") + \
        tuple("<tr><td>%s:</td><td>%s</td></tr>" %
              (key, html(val)) for key, val in var_info.items()) + \
        ("</table>",
         "<h2>Browser Headers</h2>",
         "<table>") + \
        tuple("<tr><td>%s:</td><td>%s</td></tr>" %
              (key, val) for key, val in req.headers.items()) + \
        ("</table>",
         "<h2>Request Variables </h2>",
         "<table>") + \
        tuple("<tr><td>%s:</td><td>%s</td></tr>" %
              (key, val) for key, val in get_variables(req)) + \
        ("</table>",) + \
        get_footer()

    response = Response()
    for line in buff:
        response.write(line + '\n')
    return response
Beispiel #3
0
def test_upload(req):
    var_info = OrderedDict((
        ('form_keys', req.form.keys()),
        ('form_value_names',
         ', '.join(tuple(req.form[key].name for key in req.form.keys()))),
        ('form_value_types',
         ', '.join(tuple(req.form[key].type for key in req.form.keys()))),
        ('form_value_fnames', ', '.join(
            tuple(str(req.form[key].filename) for key in req.form.keys()))),
        ('form_value_lenghts',
         ', '.join(tuple(str(req.form[key].length)
                         for key in req.form.keys()))),
        ('form_value_files',
         ', '.join(tuple(str(req.form[key].file) for key in req.form.keys()))),
        ('form_value_lists', ', '.join(
            tuple('Yes' if req.form[key].list else 'No'
                  for key in req.form.keys()))),
    ))

    files = []
    for key in req.form.keys():
        if req.form[key].filename:
            files.append("<h2>%s</h2>" % req.form[key].filename)
            files.append("<i>%s</i>" % req.form[key].type)
            if req.form[key].type.startswith('text/'):
                files.append("<pre>%s</pre>" %
                             html(req.form.getvalue(key).decode('utf-8')))
            else:
                files.append("<pre>%s</pre>" %
                             encodebytes(req.form.getvalue(key)).decode())
            os.remove("./upload/%s" % (req.form[key].filename))

    buff = get_header('HTTP file upload test') + \
        (get_crumbnav(req),
         "<h2>Upload Form</h2>",
         '<form method="post" enctype="multipart/form-data">',
         '<input type="file" name="file_0"><br/>',
         '<input type="file" name="file_1"><br/>',
         '<input type="file" name="file_2"><br/>',
         '<input type="submit" name="btn" value="Upload">'
         '</form>',
         "<h2>Uploaded File</h2>",
         "<table>") + \
        tuple("<tr><td>%s:</td><td>%s</td></tr>" %
              (key, html(val)) for key, val in var_info.items()) + \
        ("</table>",) + \
        tuple(files) + \
        get_footer()

    response = Response()
    for line in buff:
        response.write(line + '\n')
    return response
Beispiel #4
0
def method_not_allowed(req, error=None):
    """ 405 Method Not Allowed server error handler. """
    if error:
        log.error(error)

    content = (
        "<!DOCTYPE html>\n"
        "<html>\n"
        " <head>\n"
        "  <title>405 - Method Not Allowed</title>\n"
        '  <meta http-equiv="content-type" '
        'content="text/html; charset=utf-8"/>\n'
        "  <style>\n"
        "   body {width: 80%%; margin: auto; padding-top: 30px;}\n"
        "   h1 {text-align: center; color: #707070;}\n"
        "   p {text-indent: 30px; margin-top: 30px; margin-bottom: 30px;}\n"
        "  </style>\n"
        " </head>\n"
        " <body>\n"
        "  <h1>405 - Method Not Allowed</h1>\n"
        "  <p>This method %s is not allowed to access <code>%s</code>\n"
        "   on this server.</p>\n"
        "  <hr>\n"
        "  <small><i>webmaster: %s </i></small>\n"
        " </body>\n"
        "</html>" % (req.method, req.uri, req.server_admin))
    return Response(content, status_code=HTTP_METHOD_NOT_ALLOWED)
Beispiel #5
0
def not_found(req, error=None):
    """ 404 - Page Not Found server error handler. """
    if error:
        log.error(error)

    content = (
        "<!DOCTYPE html>\n"
        "<html>\n"
        " <head>\n"
        "  <title>404 - Page Not Found</title>\n"
        '  <meta http-equiv="content-type" '
        'content="text/html; charset=utf-8"/>\n'
        "  <style>\n"
        "   body {width: 80%%; margin: auto; padding-top: 30px;}\n"
        "   h1 {text-align: center; color: #707070;}\n"
        "   p {text-indent: 30px; margin-top: 30px; margin-bottom: 30px;}\n"
        "  </style>\n"
        " </head>\n"
        " <body>\n"
        "  <h1>404 - Page Not Found</h1>\n"
        "  <p>Your reqeuest <code>%s</code> was not found.</p>\n"
        "  <hr>\n"
        "  <small><i>webmaster: %s </i></small>\n"
        " </body>\n"
        "</html>" % (req.uri, req.server_admin))
    return Response(content, status_code=HTTP_NOT_FOUND)
Beispiel #6
0
def forbidden(req, error=None):
    """ 403 - Forbidden Access server error handler. """
    if error:
        log.error(error)

    content = (
        "<!DOCTYPE html>\n"
        "<html>\n"
        " <head>\n"
        "  <title>403 - Forbidden Acces</title>\n"
        '  <meta http-equiv="content-type" '
        'content="text/html; charset=utf-8"/>\n'
        "  <style>\n"
        "   body {width: 80%%; margin: auto; padding-top: 30px;}\n"
        "   h1 {text-align: center; color: #ff0000;}\n"
        "   p {text-indent: 30px; margin-top: 30px; margin-bottom: 30px;}\n"
        "  </style>\n"
        " </head>\n"
        " <body>\n"
        "  <h1>403 - Forbidden Access</h1>\n"
        "  <p>You don't have permission to access <code>%s</code>\n"
        "   on this server.</p>\n"
        "  <hr>\n"
        "  <small><i>webmaster: %s </i></small>\n"
        " </body>\n"
        "</html>" % (req.uri, req.server_admin))
    return Response(content, status_code=HTTP_FORBIDDEN)
Beispiel #7
0
def bad_request(req, error=None):
    """ 400 Bad Request server error handler. """
    if error:
        log.error(error)
    content = (
        "<!DOCTYPE html>\n"
        "<html>\n"
        " <head>\n"
        "  <title>400 - Bad Request</title>\n"
        '  <meta http-equiv="content-type" '
        'content="text/html; charset=utf-8"/>\n'
        "  <style>\n"
        "   body {width: 80%%; margin: auto; padding-top: 30px;}\n"
        "   h1 {text-align: center; color: #707070;}\n"
        "   p {text-indent: 30px; margin-top: 30px; margin-bottom: 30px;}\n"
        "  </style>\n"
        " </head>\n"
        " <body>\n"
        "  <h1>400 - Bad Request</h1>\n"
        "  <p>Method %s for %s uri.</p>\n"
        "  <hr>\n"
        "  <small><i>webmaster: %s </i></small>\n"
        " </body>\n"
        "</html>" % (req.method, req.uri, req.server_admin))
    return Response(content, status_code=HTTP_BAD_REQUEST)
Beispiel #8
0
def cors_request(req):
    if req.uri.startswith("/p/"):
        return  # enndpoints for printers does not need CORS
    if req.method_number == state.METHOD_OPTIONS:
        res = Response(content_type="text/plain; charset=UTF-8",
                       headers=options_headers,
                       status_code=state.HTTP_NO_CONTENT)
        raise HTTPException(res)
Beispiel #9
0
def not_found(req):
    buff = (
        "<html>",
        "<head>",
        '<meta http-equiv="content-type" content="text/html; charset=utf-8"/>',
        "<title>404 - Page Not Found</title>",
        '<link rel="stylesheet" href="/style.css">',
        "</head>",
        "<body>",
        "<h1>404 - Page Not Found</h1>",
        get_crumbnav(req),
        "<p>Your reqeuest <code>%s</code> was not found.</p>" % req.uri,
    ) + get_footer()

    response = Response(status_code=state.HTTP_NOT_FOUND)
    for line in buff:
        response.write(line + '\n')
    return response
Beispiel #10
0
def unauthorized(req, realm=None, stale='', error=None):
    """Return 401 Unauthorized response."""
    if error:
        log.error(error)
    headers = None
    if req.app.auth_type == 'Digest':
        if not realm:
            raise RuntimeError("Digest: realm value must be set")

        nonce = get_token(req.secret_key,
                          req.user_agent,
                          timeout=req.app.auth_timeout)
        opaque = sha256(req.server_hostname.encode()).hexdigest()

        qop = req.app.auth_qop or ''
        if qop:
            qop = 'qop="%s",' % req.app.auth_qop

        header = ('Digest realm="{realm}",{qop}algorithm="{algorithm}",'
                  'nonce="{nonce}",opaque="{opaque}"'
                  ''.format(realm=realm,
                            qop=qop,
                            algorithm=req.app.auth_algorithm,
                            nonce=nonce,
                            opaque=opaque))
        if stale:
            header += ',stale=true'

        # Headers could be tuple, than each header value must be another
        # available authenticate method, for example SHA-256 algorithm.
        headers = {'WWW-Authenticate': header}

    content = (
        "<!DOCTYPE html>\n"
        "<html>\n"
        " <head>\n"
        "  <title>401 - Unauthorized</title>\n"
        '  <meta http-equiv="content-type" '
        'content="text/html; charset=utf-8"/>\n'
        "  <style>\n"
        "   body {width: 80%%; margin: auto; padding-top: 30px;}\n"
        "   h1 {text-align: center; color: #707070;}\n"
        "   p {text-indent: 30px; margin-top: 30px; margin-bottom: 30px;}\n"
        "  </style>\n"
        " </head>\n"
        " <body>\n"
        "  <h1>401 - Unauthorized</h1>\n"
        "  <p>Method %s for %s uri.</p>\n"
        "  <hr>\n"
        "  <small><i>webmaster: %s </i></small>\n"
        " </body>\n"
        "</html>" % (req.method, req.uri, req.server_admin))

    return Response(content, headers=headers, status_code=HTTP_UNAUTHORIZED)
Beispiel #11
0
def root(req):
    buff = get_header("Index") + (
        get_crumbnav(req),
        "<ul>",
        '<li><a href="%s">/</a> - This Page</li>' % req.construct_url('/'),
        '<li><a href="/test/static">/test/static</a> - Testing Static Page'
        '</li>',
        '<li><a href="/test/42">/test/&lt;variable:int&gt;</a>'
        ' - Testing regular:int Page</li>',
        '<li><a href="/test/3.14">/test/&lt;variable:float&gt;</a>'
        ' - Testing regular:float Page</li>',
        '<li><a href="/test/word">/test/&lt;variable:word&gt;</a>'
        ' - Testing regular:word Page</li>',
        '<li><a href="/test/[email protected]">/test/&lt;variable:user&gt;</a>'
        ' - Testing regular:user Page</li>',
        '<li><a href="/test/[grr]">/test/&lt;variable:re:.*&gt;</a>'
        ' - Testing regular:re Page</li>',
        '<li><a href="/test/one/too/three">'
        '/test/&lt;variable0&gt;/&lt;variable1&gt;/&lt;variable2&gt;</a>'
        ' - Testing variable args</li>',
        '<li><a href="/test/headers">/test/headers</a> - Testing Headers'
        '</li>',
        '<li><a href="/login">/login</a> - Create login session</li>',
        '<li><a href="/logout">/logout</a> - Destroy login session</li>',
        '<li><a href="/test/form">/test/form</a>'
        ' - Testing http form (only if you have login cookie / session)</li>',
        '<li><a href="/test/upload">/test/upload</a> - '
        'Testing file upload (only if you have login cookie / session)</li>',
        '<li><a href="/debug-info">/debug-info</a>'
        ' - Debug Page (only if poor_Debug is set)</li>',
        '<li><a href="/no-page">/no-page</a> - No Exist Page</li>',
        '<li><a href="/internal-server-error">/internal-server-error</a>'
        ' - Inernal Server Error</li>',
        "</ul>",
    ) + get_footer()
    response = Response()
    for line in buff:
        response.write(line + '\n')
    return response
Beispiel #12
0
def not_implemented(req, code=None, error=None):
    """ 501 Not Implemented server error handler. """
    if error:
        log.error(error)

    content = (
        "<!DOCTYPE html>\n"
        "<html>\n"
        " <head>\n"
        "  <title>501 - Not Implemented</title>\n"
        '  <meta http-equiv="content-type" '
        'content="text/html; charset=utf-8"/>\n'
        "  <style>\n"
        "   body {width: 80%; margin: auto; padding-top: 30px;}\n"
        "   h1 {text-align: center; color: #707070;}\n"
        "   p {text-indent: 30px; margin-top: 30px; margin-bottom: 30px;}\n"
        " </style>\n"
        " </head>\n"
        " <body>\n"
        "  <h1>501 - Not Implemented</h1>\n")

    if code:
        content += (
            "  <p>Your reqeuest <code>%s</code> returned not implemented\n"
            "   status code <code>%s</code>.</p>\n" % (req.uri, code))
        log.error('Your reqeuest %s returned not implemented status code %d',
                  req.uri, code)
    else:
        content += (" <p>Response for Your reqeuest <code>%s</code>\n"
                    "  is not implemented</p>" % req.uri)
    # endif

    content += ("  <hr>\n"
                "  <small><i>webmaster: %s </i></small>\n"
                " </body>\n"
                "</html>" % req.server_admin)

    return Response(content, status_code=HTTP_NOT_IMPLEMENTED)
Beispiel #13
0
def internal_server_error(req, **kwargs):
    """ More debug 500 Internal Server Error server handler.

    It was be called automatically when no handlers are not defined
    in dispatch_table.errors. If poor_Debug variable is to On, Tracaback
    will be generated.
    """
    assert kwargs is not None
    exc_type, exc_value, exc_traceback = exc_info()
    traceback = format_exception(exc_type, exc_value, exc_traceback)
    traceback = ''.join(traceback)
    log.error(traceback)
    traceback = traceback.split('\n')

    res = Response(status_code=HTTP_INTERNAL_SERVER_ERROR)

    res.write("<!DOCTYPE html>\n"
              "<html>\n"
              " <head>\n"
              "  <title>500 - Internal Server Error</title>\n"
              '  <meta http-equiv="content-type" '
              'content="text/html; charset=utf-8"/>\n'
              "  <style>\n"
              "   body {width: 80%; margin: auto; padding-top: 30px;}\n"
              "    h1 {text-align: center; color: #707070;}\n"
              "    pre .line1 {background: #e0e0e0}\n"
              "  </style>\n"
              " </head>\n"
              " <body>\n"
              "  <h1>500 - Internal Server Error</h1>\n")

    if req.debug:
        res.write("  <h2>Response detail</h2>\n"
                  "  remote host: <b><code>{req.remote_host}</code></b><br/>\n"
                  "  remote addr: <b><code>{req.remote_addr}</code></b><br/>\n"
                  "  method: <b><code>{req.method}</code></b><br/>\n"
                  "  uri: <b><code>{req.uri}</code></b><br/>\n"
                  "  uri_rule: <b><code>{req.uri_rule}</code></b><br/>\n"
                  "  uri_handler: <b><code>{uri_handler}</code></b><br/>\n"
                  "".format(req=req,
                            uri_handler=html_escape(str(req.uri_handler))))

        res.write("  <h2>Exception Traceback</h2>\n" "  <pre>\n")

        # Traceback
        for i, line in enumerate(traceback):
            traceback_line = html_escape(line)
            res.write('<span class="line%s">%s</span>\n' %
                      (i % 2, traceback_line))

        res.write(
            "  </pre>\n"
            "  <hr>\n"
            "  <small><i>%s / Poor WSGI for Python ,webmaster: %s</i></small>"
            "\n" % (req.server_software, req.server_admin))
    else:
        res.write("  <hr>\n"
                  "  <small><i>webmaster: %s </i></small>\n" %
                  req.server_admin)
    # endif

    res.write(" </body>\n" "</html>")

    return res
Beispiel #14
0
def test_form(req):
    # get_var_info = {'len': len(args)}
    var_info = OrderedDict((
        ('form_keys', req.form.keys()),
        ('form_values', ', '.join(
            tuple(str(req.form.getvalue(key)) for key in req.form.keys()))),
        ('form_getfirst',
         '%s,%s' % (req.form.getfirst('pname'), req.form.getfirst('px'))),
        ('form_getlist', '%s,%s' %
         (list(req.form.getlist('pname')), list(req.form.getlist('px')))),
        ('', ''),
        ('args_keys', req.args.keys()),
        ('args_values',
         ', '.join(tuple(str(req.args[key]) for key in req.args.keys()))),
        ('args_getfirst',
         '%s,%s' % (req.args.getfirst('gname'), req.args.getfirst('gx'))),
        ('args_getlist', '%s,%s' %
         (list(req.args.getlist('gname')), list(req.args.getlist('gx')))),
    ))

    buff = get_header("HTTP Form args test") + \
        (get_crumbnav(req),
         "<h2>Get Form</h2>",
         '<form method="get">',
         '<input type="text" name="gname" value="Ondřej"><br/>',
         '<input type="text" name="gsurname" value="Tůma"><br/>',
         '<input type="text" name="gx" value="1">'
         '<input type="text" name="gx" value="2">'
         '<input type="text" name="gx" value="3"><br/>',
         '<input type="submit" name="btn" value="Send">'
         '</form>',
         "<h2>Post Form</h2>",
         '<form method="post">',
         '<input type="text" name="pname" value="Ondřej"><br/>',
         '<input type="text" name="psurname" value="Tůma"><br/>',
         '<input type="text" name="px" value="8">'
         '<input type="text" name="px" value="7">'
         '<input type="text" name="px" value="6"><br/>',
         '<input type="submit" name="btn" value="Send">'
         '</form>',
         "<h2>Variables</h2>",
         "<table>") + \
        tuple("<tr><td>%s:</td><td>%s</td></tr>" %
              (key, html(val)) for key, val in var_info.items()) + \
        ("</table>",
         "<h2>Browser Headers</h2>",
         "<table>") + \
        tuple("<tr><td>%s:</td><td>%s</td></tr>" %
              (key, val) for key, val in req.headers.items()) + \
        ("</table>",
         "<h2>Request Variables </h2>",
         "<table>") + \
        tuple("<tr><td>%s:</td><td>%s</td></tr>" %
              (key, val) for key, val in get_variables(req)) + \
        ("</table>",) + \
        get_footer()

    response = Response()
    for line in buff:
        response.write(line + '\n')
    return response
Beispiel #15
0
    def test_abort_response(self):
        with pytest.raises(HTTPException) as err:
            abort(Response(status_code=400))

        assert isinstance(err.value.response, Response)
        assert err.value.response.status_code == 400
Beispiel #16
0
def response_kwargs(request):
    return Response(**request.param)
Beispiel #17
0
def login(req):
    cookie = PoorSession(req)
    cookie.data['login'] = True
    response = Response(status_code=204)
    cookie.header(response)
    return response