예제 #1
0
파일: app.py 프로젝트: smokey42/PhotoBlog
    def __call__(self, environ, start_response):
        local.application = self
        request = MongoRequest(environ)
        local.url_adapter = adapter = url_map.bind_to_environ(environ)
        environ['mongo.db'] = self.db
        environ['mongo.fs'] = self.fs
        try:
            endpoint, values = adapter.match()
            handler = getattr(views, endpoint)
            data = handler(request, **values)

            # WSGI
            if callable(data):
                return data(environ, start_response)

            data = safe_keys(data)

            data['request'] = request

            # Templates
            template = self.env.get_template("%s.html" % endpoint)
            response = Response()
            response.content_type = "text/html"
            response.add_etag()
            # if DEBUG:
            #   response.make_conditional(request)
            data['endpoint'] = endpoint
            response.data = template.render(**data)
        except HTTPException, e:
            response = e
예제 #2
0
    def dispatch_request(self, request):
        # Process variables        
        self.var_dict = {
            'refresh_interval': self.cfg['refresh_interval'],
                        
            'python_version': version,
            'werkzeug_version': werkzeug.__version__,
            'jinja_version': jinja2.__version__,
            'buteo_version': self.version
        }

        # add data from plugins
        if self.enabled_plugins != []:
            for plugin in plugins.get_plugins():
                try:
                    data = plugin.get_data(self.cfg)
                except Exception as inst:
                    print ' * ERROR: %s. Skipping plugin %r.' % (inst, plugin.__class__.__name__)
                    continue
                
                for key in data:
                    if not key in self.var_dict:
                        self.var_dict[key] = data[key]
                        
        self.var_dict['exectime'] = round(time()-self.starttime, 4)                
              
        try:
            response = Response(mimetype='text/html')                           
            response.data = self.template.render(self.var_dict)            
            return response
            
        except HTTPException, e:
            return e
예제 #3
0
def application(request):

    response = Response(mimetype='text/html')

    try:
        # Only accept requests for rc.base_path
        if urlparse(request.url).path != rc.base_path:
            raise NotFound

        fields = request.form.to_dict()

        if request.method == 'GET':
            raise NoFormData
        elif request.method == 'POST':
            if not request.form:
                raise NoFormData
        else:
            raise BadRequest

        response.data = process_form(fields)

    except NoFormData as e:
        response.data = render_page()

    except MissingFields as e:
        response.data = render_page(
            fields=fields, message='All fields on a line must be filled out.')

    except TooFewDebts as e:
        response.data = render_page(
            fields=fields, message='Two or more debts must be provided.')

    except NegativeNumbers as e:
        response.data = render_page(fields=fields,
                                    message='All numbers must be positive.')

    except DuplicateNames as e:
        response.data = render_page(
            fields=fields,
            message='To avoid confusion, all debts must have unique names.')

    except RisingBalance as e:
        response.data = render_page(
            fields=fields,
            message=
            "Debt '%s' does not have a large enough payment to reduce the balance."
            % e.args[0])

    except ValueError as e:
        response.data = render_page(
            fields=fields,
            message='Balance, payment, and APR must be numeric.')

    except HTTPException as e:
        return e

    return response
예제 #4
0
파일: views.py 프로젝트: mzp/home-image
def miku(request):
  data = request.files['image'].stream.read()
  img =  HomeImage.split(images.Image(data))[0]
  png = img.execute_transforms(output_encoding=images.PNG)
  r = Response()
  r.content_type = 'image/png'
  r.data = png
  return r
예제 #5
0
def serve_file(file_name: str, content: str) -> Response:
    content_type, _ = mimetypes.guess_type(file_name)

    resp = Response()
    resp.direct_passthrough = True
    resp.data = content
    if content_type is not None:
        resp.headers['Content-Type'] = content_type
    resp.freeze()
    return resp
예제 #6
0
def serve_content(file_handle: TextIO, content_type):
    file_handle.seek(0)
    content = file_handle.read()

    resp = Response()
    resp.content_type = content_type
    resp.status_code = 200
    resp.data = content
    resp.freeze()

    return resp
예제 #7
0
def serve_file(file_name: str, content: bytes) -> Response:
    """Construct and cache a Response from a static file."""
    content_type, _ = mimetypes.guess_type(file_name)

    resp = Response()
    resp.direct_passthrough = True
    resp.data = content
    if content_type is not None:
        resp.headers["Content-Type"] = content_type
    resp.freeze()
    return resp
예제 #8
0
def message(request, name):
    response = Response()
    path = os.path.join(datadir, str(name))
    
    if request.method == 'HEAD':
        pass # we only need to return headers
        
    elif request.method == 'GET':
        try:
            response.data = open(path, 'r').read()
        except IOError, e:
            print e
            raise NotFound()
예제 #9
0
def random_bytes(request, n):
    """Returns n random bytes generated with given seed."""
    n = min(n, 100 * 1024)  # set 100KB limit

    params = CaseInsensitiveDict(request.args.items())
    if 'seed' in params:
        random.seed(int(params['seed']))

    response = Response()

    # Note: can't just use os.urandom here because it ignores the seed
    response.data = bytearray(random.randint(0, 255) for i in range(n))
    response.content_type = 'application/octet-stream'
    return response
예제 #10
0
def application(request):

    response = Response(mimetype='text/html')

    try:
        # Only accept requests for rc.base_path
        if urlparse.urlparse(request.url).path != rc.base_path:
            raise NotFound

        fields = request.form.to_dict()

        if request.method == 'GET':
            raise NoFormData
        elif request.method == 'POST':
            if not request.form:
                raise NoFormData
        else:
            raise BadRequest

        response.data = process_form(fields)

    except NoFormData, e:
        response.data = render_page()
예제 #11
0
def serve_spec(
    site: str,
    target: EndpointTarget,
    url: str,
    content_type: str,
    serializer: Callable[[Dict[str, Any]], str],
) -> Response:
    data = generate_data(target=target)
    data.setdefault('servers', [])
    add_once(data['servers'], {'url': url, 'description': f"Site: {site}"})
    response = Response(status=200)
    response.data = serializer(data)
    response.content_type = content_type
    response.freeze()
    return response
예제 #12
0
def serve_spec(
    site: str,
    url: str,
    content_type: str,
    serializer: Callable[[Dict[str, Any]], str],
) -> Response:
    data = generate_data()
    data.setdefault('servers', [])
    data['servers'].append({
        'url': url,
        'description': f"Site: {site}",
    })
    response = Response(status=200)
    response.data = serializer(data)
    response.content_type = content_type
    response.freeze()
    return response
예제 #13
0
def test_wrapper_internals():
    """Test internals of the wrappers"""
    from werkzeug import Request
    req = Request.from_values(data={'foo': 'bar'}, method='POST')
    req._load_form_data()
    assert req.form.to_dict() == {'foo': 'bar'}

    # second call does not break
    req._load_form_data()
    assert req.form.to_dict() == {'foo': 'bar'}

    # check reprs
    assert repr(req) == "<Request 'http://localhost/' [POST]>"
    resp = Response()
    assert repr(resp) == '<Response 0 bytes [200 OK]>'
    resp.data = 'Hello World!'
    assert repr(resp) == '<Response 12 bytes [200 OK]>'
    resp.response = iter(['Test'])
    assert repr(resp) == '<Response streamed [200 OK]>'

    # unicode data does not set content length
    response = Response([u'Hällo Wörld'])
    headers = response.get_wsgi_headers(create_environ())
    assert 'Content-Length' not in headers

    response = Response(['Hällo Wörld'])
    headers = response.get_wsgi_headers(create_environ())
    assert 'Content-Length' in headers

    # check for internal warnings
    print 'start'
    filterwarnings('error', category=Warning)
    response = Response()
    environ = create_environ()
    response.response = 'What the...?'
    assert_raises(Warning, lambda: list(response.iter_encoded()))
    assert_raises(Warning, lambda: list(response.get_app_iter(environ)))
    response.direct_passthrough = True
    assert_raises(Warning, lambda: list(response.iter_encoded()))
    assert_raises(Warning, lambda: list(response.get_app_iter(environ)))
    resetwarnings()
예제 #14
0
    def __call__(self, environ, start_response):
        path_info = environ['PATH_INFO']
        path = re.sub(self.prefix, '', path_info)
        prefix = path_info[:-len(path)]
        if prefix.endswith("/ui"):
            prefix = prefix[:-3]

        if path == "/":
            path = "/index.html"

        if path == "/index.html":
            with open(swagger_ui_3_path + path) as fh:
                content = fh.read()
            content = content.replace(
                "https://petstore.swagger.io/v2/swagger.json",
                prefix + "/openapi.yaml")
            resp = Response()
            resp.content_type = 'text/html'
            resp.status_code = 200
            resp.data = content
            resp.freeze()
            return resp(environ, start_response)

        return serve_file(swagger_ui_3_path + path)(environ, start_response)
예제 #15
0
          resdata = {'jsonrpc':'2.0',
                     'id':None,
                     'error':{'code':INVALID_REQUEST,
                              'message':errors[INVALID_REQUEST]}}
        else:
          resdata = [d for d in (self.process(d) for d in data) 
                     if d is not None]
            

    response = Response(content_type="application/json")

    if resdata:
      response.headers["Cache-Control"] = "no-cache"
      response.headers["Pragma"] = "no-cache"
      response.headers["Expires"] = "-1"
      response.data = json.dumps(resdata)
    return response(environ, start_response)


def getmod(modname):
  try:
    __import__(modname)
  except ImportError, e:
    logging.warn("import failed: %s." % e)
    return None
  mod = sys.modules[modname]
  return mod


def HTTPExceptionMiddleware(app):
  def wrap(environ, start_response):
예제 #16
0
          resdata = {'jsonrpc':'2.0',
                     'id':None,
                     'error':{'code':INVALID_REQUEST,
                              'message':errors[INVALID_REQUEST]}}
        else:
          resdata = [d for d in (self.process(d) for d in data) 
                     if d is not None]
            

    response = Response(content_type="application/json")

    if resdata:
      response.headers["Cache-Control"] = "no-cache"
      response.headers["Pragma"] = "no-cache"
      response.headers["Expires"] = "-1"
      response.data = json.dumps(resdata)
    return response(environ, start_response)


def getmod(modname):
  try:
    __import__(modname)
  except ImportError, e:
    logging.warn("import failed: %s." % e)
    return None
  mod = sys.modules[modname]
  return mod


def HTTPExceptionMiddleware(app):
  def wrap(environ, start_response):
예제 #17
0
def range_request(request, numbytes):
    """Streams n random bytes generated with given seed, at given chunk size per packet."""

    if numbytes <= 0 or numbytes > (100 * 1024):
        response = Response(headers={
            'ETag': 'range%d' % numbytes,
            'Accept-Ranges': 'bytes'
        })
        response.status_code = 404
        response.data = 'number of bytes must be in the range (0, 10240]'
        return response

    params = CaseInsensitiveDict(request.args.items())
    if 'chunk_size' in params:
        chunk_size = max(1, int(params['chunk_size']))
    else:
        chunk_size = 10 * 1024

    duration = float(params.get('duration', 0))
    pause_per_byte = duration / numbytes

    request_headers = get_headers(request)
    first_byte_pos, last_byte_pos = get_request_range(request_headers,
                                                      numbytes)
    range_length = (last_byte_pos + 1) - first_byte_pos

    if first_byte_pos > last_byte_pos or first_byte_pos not in xrange(
            0, numbytes) or last_byte_pos not in xrange(0, numbytes):
        response = Response(
            headers={
                'ETag': 'range%d' % numbytes,
                'Accept-Ranges': 'bytes',
                'Content-Range': 'bytes */%d' % numbytes,
                'Content-Length': '0',
            })
        response.status_code = 416
        return response

    def generate_bytes():
        chunks = bytearray()

        for i in xrange(first_byte_pos, last_byte_pos + 1):

            # We don't want the resource to change across requests, so we need
            # to use a predictable data generation function
            chunks.append(ord('a') + (i % 26))
            if len(chunks) == chunk_size:
                yield (bytes(chunks))
                time.sleep(pause_per_byte * chunk_size)
                chunks = bytearray()

        if chunks:
            time.sleep(pause_per_byte * len(chunks))
            yield (bytes(chunks))

    content_range = 'bytes %d-%d/%d' % (first_byte_pos, last_byte_pos,
                                        numbytes)
    response_headers = {
        'Content-Type': 'application/octet-stream',
        'ETag': 'range%d' % numbytes,
        'Accept-Ranges': 'bytes',
        'Content-Length': str(range_length),
        'Content-Range': content_range
    }

    response = Response(generate_bytes(), headers=response_headers)

    if (first_byte_pos == 0) and (last_byte_pos == (numbytes - 1)):
        response.status_code = 200
    else:
        response.status_code = 206

    return response
예제 #18
0
    def __call__(self, request):
        try:

            response = Response(mimetype="text/html")
            req_url = request.path
            msg = ""

            if request.method == "POST":
                if req_url.startswith("/add"):
                    goterror = False
                    id = self._get_id_from_path(req_url[4:])
                    params = []
                    config = {}
                    form = request.form

                    typename = form.get("typename", "")
                    typeerror = check_typename(typename)
                    if typeerror:
                        goterror = True

                    n = 0
                    checker = ParamChecker()
                    while True:
                        k = "param%d_" % (n,)
                        nk = k + "name"
                        vk = k + "value"
                        if nk not in form and vk not in form:
                            break

                        name = form.get(nk, "")
                        value = form.get(vk, "")

                        if name or value:
                            type = form.get(k + "type", "string")
                            params.append(checker.doparam(name, type, value))
                            if params[-1][-1]:
                                goterror = True
                            else:
                                config[name] = params[-1][2]
                        n += 1
                    if goterror:
                        msg = "Illegal input"
                    else:
                        try:
                            t1C.add(id, config.get("name", None), typename, config)
                            return redirect(id)
                        except Exception, e:
                            self.logger.exception("error")
                            msg = "An error occured: %s" % (e,)
                else:
                    req_url = self._get_id_from_path(req_url)
                    # raise Exception(req_url)
                    entity = t1C.get_entity(req_url)

                    old = entity.config
                    config = {}

                    for k, v in request.form.iteritems():
                        print "%s - %s" % (k, v)
                        if "-" not in k:
                            continue

                        type, _, name = k.partition("-")
                        if type == "boolean":
                            v = v.lower().startswith("t")
                        elif type == "integer":
                            v = int(v)
                        elif type == "float":
                            v = float(v)
                        elif type == "reference":
                            raise NotImplementedError()
                        if name not in old or old[name] != v:
                            config[name] = v

                    if config:
                        entity.update(config)
                        msg = "Update successful"
                    else:
                        msg = "No values changed, nothing to do"

            if req_url.startswith("/add/"):
                id = req_url[5:]
                if request.method != "POST":
                    params = [("", "", "", None) for _ in range(10)]
                    typename = ""
                    typeerror = None
                t_test = self.template_lookup.get_template("add.html")
                response.data = t_test.render_unicode(
                    url=self.__make_url,
                    request=request,
                    params=params,
                    id=id,
                    typename=typename,
                    types=types,
                    typeerror=typeerror,
                    msg=escape(msg),
                    log=(),
                )
            elif req_url.startswith("/del/"):
                id = req_url[5:]
                t1C.delete(id)
                parent = id.rpartition("/")

                return redirect(parent[0] + parent[1])
            else:
                if req_url.startswith("/show"):
                    req_url = req_url[5:]
                if req_url.startswith("/"):
                    pspos = req_url.find("./")
                    if pspos >= 0 and pspos <= req_url[1:].find("/"):
                        req_url = req_url[1:]
                        # raise Exception("huhu", req_url)
                elif not req_url:
                    req_url = "/"
                if req_url.endswith("/"):
                    try:
                        self.logger.debug("listing: " + req_url)
                        instances = t1C.list_entities(req_url)
                    except NoAdapterFoundError:
                        instances = False
                    except Exception, e:
                        instances = escape(errorstr(e))
                    template = self.template_lookup.get_template("list.html")
                    add_url = not req_url.startswith("/") and req_url or req_url[1:]
                    response.data = template.render_unicode(
                        url=self.__make_url,
                        request=request,
                        list=instances,
                        req_url=req_url,
                        msg=escape(msg),
                        add_url=add_url,
                    )
                else: