예제 #1
0
    def dispatch(self, environ, start_response):
        try:
            local.request = Request(environ)
            local.response = Response()
            local.session = Session(local.request.cookies.get("session"))
            try:
                local.url_adapter = url_adapter = url_map.bind_to_environ(
                    environ)
                try:
                    endpoint, params = url_adapter.match()
                except NotFound:
                    endpoint = "notfound"
                    params = {}
                local.endpoint = endpoint
                endpoints[endpoint](**params)
            except:
                if self.debug:
                    raise
                responders.error()
            response = local.response
            local.session.save()
            local.session.set_cookie(local.response)
        except:
            if self.debug:
                raise
            response = Response("Fejlsidens fejlside.")

        return response(environ, start_response)
 def application(request):
     response = Response('binary data here',
                         mimetype='application/vnd.ms-excel')
     response.headers['Vary'] = 'Cookie'
     response.headers[
         'Content-Disposition'] = 'attachment; filename=foo.xls'
     return response
예제 #3
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
예제 #4
0
파일: utils.py 프로젝트: OriHoch/dbs-back
def humanify(obj, status_code=200):
    """ Gets an obj and possibly a status code and returns a flask Resonse
        with a jsonified obj, not suitable for humans
    >>> humanify({"a": 1})
    <Response 8 bytes [200 OK]>
    >>> humanify({"a": 1}, 404)
    <Response 8 bytes [404 NOT FOUND]>
    >>> humanify({"a": 1}).get_data()
    '{"a": 1}'
    >>> humanify([1,2,3]).get_data()
    '[1, 2, 3]'
    """
    # TODO: refactor the name to `response`
    # jsonify function doesn't work with lists
    if type(obj) == list:
        data = json.dumps(obj, default=json_util.default)
    elif type(obj) == pymongo.cursor.Cursor:
        rv = []
        for doc in obj:
            doc['_id'] = str(doc['_id'])
            rv.append(dumps(doc))
        data = '[' + ',\n'.join(rv) + ']' + '\n'
    else:
        data = dumps(obj,
                          default=json_util.default,
                          cls=MongoJsonEncoder)
    resp = Response(data, mimetype='application/json')
    resp.status_code = status_code
    return resp
예제 #5
0
def humanify(obj, status_code=200):
    """ Gets an obj and possibly a status code and returns a flask Resonse
        with a jsonified obj, with newlines.
    >>> humanify({"a": 1})
    <Response 13 bytes [200 OK]>
    >>> humanify({"a": 1}, 404)
    <Response 13 bytes [404 NOT FOUND]>
    >>> humanify({"a": 1}).get_data()
    '{\\n  "a": 1\\n}\\n'
    >>> humanify([1,2,3]).get_data()
    '[\\n  1, \\n  2, \\n  3\\n]\\n'
    """
    # jsonify function doesn't work with lists
    if type(obj) == list:
        data = json.dumps(obj, default=json_util.default, indent=2) + '\n'
    elif type(obj) == pymongo.cursor.Cursor:
        rv = []
        for doc in obj:
            doc['_id'] = str(doc['_id'])
            rv.append(dumps(doc, indent=2))
        data = '[' + ',\n'.join(rv) + ']' + '\n'
    else:
        data = dumps(obj,
                     default=json_util.default,
                     indent=2,
                     cls=MongoJsonEncoder)
        data += '\n'
    resp = Response(data, mimetype='application/json')
    resp.status_code = status_code
    return resp
예제 #6
0
def drip(request):
    """Drips data over a duration after an optional initial delay."""
    args = CaseInsensitiveDict(request.args.items())
    duration = float(args.get('duration', 2))
    numbytes = min(int(args.get('numbytes', 10)),
                   (10 * 1024 * 1024))  # set 10MB limit
    code = int(args.get('code', 200))

    if numbytes <= 0:
        response = Response('number of bytes must be positive', status=400)
        return response

    delay = float(args.get('delay', 0))
    if delay > 0:
        time.sleep(delay)

    pause = duration / numbytes

    def generate_bytes():
        for i in xrange(numbytes):
            yield u"*".encode('utf-8')
            time.sleep(pause)

    response = Response(generate_bytes(),
                        headers={
                            "Content-Type": "application/octet-stream",
                            "Content-Length": str(numbytes)
                        })

    response.status_code = code

    return response
예제 #7
0
def form_data_consumer(request):
    result_object = request.args['object']
    if result_object == 'text':
        return Response(repr(request.form['text']))
    f = request.files[result_object]
    return Response('\n'.join((repr(f.filename), repr(f.name),
                               repr(f.content_type), f.stream.read())))
예제 #8
0
        def decorated_auth(*args, **kwargs):
            if 'api-token' not in request.headers:
                return Response(
                    mimetype="application/json",
                    response=json.dumps({
                        'error':
                        'Authentication token is not available, please login to get one'
                    }),
                    status=400)
            token = request.headers.get('api-token')
            data = Auth.decode_token(token)
            if data['error']:
                return Response(mimetype="application/json",
                                response=json.dumps(data['error']),
                                status=400)

            user_id = data['data']['user_id']
            check_user = UserModel.get_one_user(user_id)
            if not check_user:
                return Response(mimetype="application/json",
                                response=json.dumps({
                                    'error':
                                    'user does not exist, invalid token'
                                }),
                                status=400)
            g.user = {'id': user_id}
            return func(*args, **kwargs)
예제 #9
0
def view_status_code(request, codes):
    """Return status code or random status code if more than one are given"""

    if ',' not in codes:
        try:
            code = int(codes)
        except ValueError:
            return Response('Invalid status code', status=400)
        return status_code(code)

    choices = []
    for choice in codes.split(','):
        if ':' not in choice:
            code = choice
            weight = 1
        else:
            code, weight = choice.split(':')

        try:
            choices.append((int(code), float(weight)))
        except ValueError:
            return Response('Invalid status code', status=400)

    code = weighted_choice(choices)

    return status_code(code)
예제 #10
0
def direct_to_pdf(template_name,
                  params=None,
                  pdf_name=None,
                  download=False,
                  font_resolver=font_resolver,
                  image_resolver=image_resolver):
    """Simple generic view to tender rml template.
    """
    params = params or {}
    params['pdf_resource'] = pdf_resource
    pdf_name = pdf_name or params.pop('pdf_name', None)
    if pdf_name == None:
        tname_body = template_name.rpartition('/')[-1].rpartition('.')[0]
        if tname_body:
            pdf_name = tname_body + '.pdf'
        else:
            pdf_name = 'download.pdf'
    params['pdf_name'] = pdf_name
    pdf = render_to_pdf(template_name,
                        params,
                        font_resolver=font_resolver,
                        image_resolver=image_resolver)
    response = Response(pdf, mimetype='application/pdf')
    if download:
        disposition = 'attachment; filename=%s' % (pdf_name)
        response.headers['Content-Disposition'] = disposition
    return response
예제 #11
0
def digest_challenge_response(request, qop, algorithm, stale=False):
    response = Response()
    response.status_code = 401

    # RFC2616 Section4.2: HTTP headers are ASCII.  That means
    # request.remote_addr was originally ASCII, so I should be able to
    # encode it back to ascii.  Also, RFC2617 says about nonces: "The
    # contents of the nonce are implementation dependent"
    nonce = H(
        b''.join([
            getattr(request, 'remote_addr', u'').encode('ascii'), b':',
            str(time.time()).encode('ascii'), b':',
            os.urandom(10)
        ]), algorithm)
    opaque = H(os.urandom(10), algorithm)

    auth = WWWAuthenticate("digest")
    auth.set_digest('*****@*****.**',
                    nonce,
                    opaque=opaque,
                    qop=('auth', 'auth-int') if qop is None else (qop, ),
                    algorithm=algorithm)
    auth.stale = stale
    response.headers['WWW-Authenticate'] = auth.to_header()
    return response
예제 #12
0
def humanify(obj, status_code=200):
    """ Gets an obj and possibly a status code and returns a flask Resonse
        with a jsonified obj, not suitable for humans
    >>> humanify({"a": 1})
    <Response 8 bytes [200 OK]>
    >>> humanify({"a": 1}, 404)
    <Response 8 bytes [404 NOT FOUND]>
    >>> humanify({"a": 1}).get_data()
    '{"a": 1}'
    >>> humanify([1,2,3]).get_data()
    '[1, 2, 3]'
    """
    # TODO: refactor the name to `response`
    # jsonify function doesn't work with lists
    if type(obj) == list:
        data = json.dumps(obj, default=json_util.default)
    elif type(obj) == pymongo.cursor.Cursor:
        rv = []
        for doc in obj:
            doc['_id'] = str(doc['_id'])
            rv.append(dumps(doc))
        data = '[' + ',\n'.join(rv) + ']' + '\n'
    else:
        data = dumps(obj,
                          default=json_util.default,
                          cls=MongoJsonEncoder)
    resp = Response(data, mimetype='application/json')
    resp.status_code = status_code
    return resp
예제 #13
0
    def dec(*args, **kwargs):
        """This decorater function will send an authenticate header, if none
        is present and denies access, if HTTP Digest Auth failed."""

        request = flask.request
        usehtml = request.accept_mimetypes.accept_html

        if not request.authorization:
            response = Response('Unauthorized',
                                401,
                                content_type='text/html; charset=utf-8'
                                if usehtml else 'application/json')
            response.www_authenticate.set_digest(
                'Application',
                algorithm='MD5',
                nonce=standard_b64encode(urandom(32)),
                qop=('auth', ),
                opaque='%x' % getrandbits(128))
            return response
        else:
            account = app.db.accounts.find_one(
                {'email': request.authorization.username})
            if account and account['activated_at'] == None:
                return Response('[ "Your account hasn\'t been activated. Please ' \
                                + 'check your email and activate your account." ]', 409)
            elif prove_auth(app, request) != request.authorization.response:
                return Response('Forbidden', 403)
        return f(*args, **kwargs)
예제 #14
0
파일: rest.py 프로젝트: DerRechner/Hanabi
    def response(self, request, data, etag=None, cache_policy=None):
        """Renders `data` to a JSON response.

        An ETag may be specified. When it is not specified one will be generated
        based on the data.

        The caching policy can be optionally configured. By default it takes the
        policy from the controller object: `cache_policy`.
        """
        if etag is None and data is not None:
            etag = self.etag(data)
        # FIXME: Check content-type headers
        if data is None:
            if etag is None:
                raise TypeError('response requires an etag when '
                                'the response body is None')
            resp = Response(status=304, content_type='application/json')
        else:
            # Avoid sending the resource when an ETag matches
            request_etags = parse_etags(
                request.environ.get('HTTP_IF_NONE_MATCH'))
            if request_etags.contains(etag):
                 resp = Response(status=304, content_type='application/json')
            # Render the given data to a response object
            else:
                resp = Response(self.data_encoder.encode(data), content_type='application/json')
        resp.headers['ETag'] = quote_etag(etag)
        if cache_policy is None:
            cache_policy = self.cache_policy
        return cache_policy(resp)
예제 #15
0
 def add_response(self, data, status=None, headers=None):
     response = Response(data)
     response.status_code = status or httplib.OK
     response.headers = headers or {
         'Content-Type': 'text/html; charset=UTF-8'
     }
     self.responses.append(response)
def application(request):
    if request.method == 'POST':
        return Response(repr(request.files) + "\n" + repr(request.form),
                        status=500)
    return Response(
        '<form action="" method="post" enctype="multipart/form-data"><input type="file" name="f"><input type="submit" value="Upload"></form>',
        mimetype='text/html')
예제 #17
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
예제 #18
0
파일: server.py 프로젝트: mgax/notespace
 def static(self, request, filename):
     response = Response(open(path.join(web_media_path, filename)).read())
     if filename.endswith('.js'):
         response.mimetype = 'application/javascript'
     elif filename.endswith('.css'):
         response.mimetype = 'text/css'
     return response
예제 #19
0
    def _application(self, environ, start_response):
        request = Request(environ)
        self.logger.info(request.full_path)

        status_code = 200
        headers = {'Content-Type': 'application/json'}
        content = ''

        if request.path == '/':  # 接管主页,因为所有请求需要token,主页转发不能正常工作
            headers = {'Content-Type': 'text/html'}
            content = '<h1><a href="https://github.com/xiyaoWong/iotbot-http-transfer">iotbot http tranfer</a><h1>'
        elif request.path.strip('/') == 'favicon.ico':
            status_code = 301
            del headers['Content-Type']
            headers['location'] = 'https://cdn.jsdelivr.net/gh/xiyaowong/FileHost/transfer.png'
        elif request.path.strip('/') == 'genToken':  # 处理token生成请求
            key = request.args.get('key')
            if key == self.key:
                token = self._genarate_token('ok, it\' funny.')
                content = json.dumps({'token': token})
            else:
                content = '{"Ret":1111, "Msg":"key错误"}'
        else:  # 处理其他请求
            # 鉴权
            token = request.args.get('token') or request.headers.get('Authorization')
            if not self._check_token(token):  # 大胆,狗贼
                content = '{"Ret":2222, "Msg":"无效的token"}'
            else:
                try:
                    resp = requests.request(
                        request.method,
                        '{}{}?{}'.format(
                            'http://{}:{}'.format(self.iotbot_host, self.iotbot_port),
                            request.path,
                            request.query_string.decode()),
                        headers=request.headers,
                        data=request.data,
                        timeout=self.timeout
                    )
                except requests.Timeout as e:
                    self.logger.warning(e)
                    content = '{"Ret":3333, "Msg":"请求响应超时"}'
                except requests.ConnectionError as e:
                    self.logger.exception(e)
                    content = '{"Ret":4444, "Msg":"连接错误"}'
                except Exception as e:
                    self.logger.exception(e)
                    content = '{"Ret":5555, "Msg":"请求响应失败"}'
                else:
                    content = resp.content
                    status_code = resp.status_code
                    headers = resp.headers

        response = Response(content)
        response.status = HTTP_STATUS_CODES[status_code]
        response.status_code = status_code
        for header_name, header_value in headers.items():
            response.headers[header_name] = header_value
        return response(environ, start_response)
예제 #20
0
 def close(self):
     Response.close(self)
     if self._socket is not None:
         self._socket.close()
         self._socket = None
     if self._httplib_resp is not None:
         self._httplib_resp.close()
         self._httplib_resp = None
예제 #21
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
 def application(request):
     response = Response('binary data here',
                         mimetype='application/vnd.ms-excel')
     response.headers['Pragma'] = ', '.join(pragma)
     response.headers['Cache-Control'] = cc.to_header()
     response.headers[
         'Content-Disposition'] = 'attachment; filename=foo.xls'
     return response
예제 #23
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
예제 #24
0
 def store_pasta(self, pasta):
     pasta.uuid = self.getset_uuid()
     pasta.put()
     self.logger.info("created pasta %s", pasta)
     redir_url = self.request.base_url + "p/" + pasta.pasta_id + "/"
     resp = Response(redir_url + "\n", 302, mimetype="text/plain")
     resp.headers["Location"] = redir_url
     resp.set_cookie(self.uuid_cookie, pasta.uuid)
     return resp
예제 #25
0
 def send_update(self, update):
     response = Response(
         response=update['body'],
         content_type=update['content_type'],
     )
     response.last_modified = update['published_on']
     response.headers['If-Modified-Since'] = update['published_on']
     
     return response
예제 #26
0
def session_debug():
    if local.application.debug == False:
        return notfound()
    from pprint import pformat
    local.session.init()
    response = Response(pformat(local.session.data))
    response.mimetype="text/plain"
    response.charset = "utf-8"
    return response
예제 #27
0
 def process_view_result(self, rv):
     """Processes a view's return value and ensures it's a response
     object.  This is automatically called by the dispatch function
     but is also handy for view decorators.
     """
     if isinstance(rv, basestring):
         rv = Response(rv, mimetype='text/html')
     elif not isinstance(rv, Response):
         rv = Response.force_type(rv, self.environ)
     return rv
예제 #28
0
    def __call__(self, request):
        try:
            response = self.responses[len(self.requests)]
        except IndexError:
            response = Response("No prepared response")
            response.status_code = httplib.NOT_IMPLEMENTED
            return response

        self.requests.append(request)
        return response
예제 #29
0
def create_blobinfo_response(blobinfo, filename=None, mimetype='application/octet-stream'):
    if not mimetype:
        mimetype = blobinfo.content_type
    if not filename:
        filename = blobinfo.filename
    rsp = Response(None, 200)
    rsp.headers[blobstore.BLOB_KEY_HEADER] = blobinfo.key()
    rsp.headers['Content-Type'] = mimetype
    rsp.headers['Content-Disposition'] = 'attachment;filename=%s' % filename
    return rsp
예제 #30
0
def application(req):
    if req.method == 'POST':
        file_in = req.files['myfile']
        buf = convert_doc(file_in)

        filename = file_in.filename.replace('.odt', '-converted.odt')
        resp = Response(buf.getvalue())
        resp.content_type = 'application/x-download'
        resp.headers.add('Content-Disposition', 'attachment', filename=filename)
        return resp
    return Response(HTML, content_type='text/html')
예제 #31
0
def serve_file(file, content_type=None):
    # Reset the stream
    file.seek(0)
    resp = Response(FileWrapper(file), direct_passthrough=True)

    if content_type is None:
        resp.content_type = file.content_type
    else:
        resp.content_type = content_type

    return resp
예제 #32
0
 def app(request):
     if request.args.get('ping', 'N').upper() == 'Y':
         return Response("ok")
     if request.args.get('shutdown', 'N').upper() == 'Y':
         # func = request.environ.get('werkzeug.server.shutdown')
         # if func is None:
         #     raise RuntimeError('Not running with the Werkzeug Server')
         # func()
         srv._BaseServer__shutdown_request = True
         return Response('Shutdown!')
     else:
         raise ex
예제 #33
0
    def __call__(self, env, req, *args, **kwargs):
        res = super(JsonView, self).__call__(env, req, *args, **kwargs)

        if isinstance(res, Response):
            # rendering already done
            return res

        if res is None:
            # no content
            return Response(status=204)

        return Response(json.dumps(res), content_type='application/json')
예제 #34
0
def sensesJson(request):
    db_senses = get_database().senses
    if 'create' in request.args:
        wanted_lemma = request.args['create']
        user = request.user
        if not user or user not in ADMINS:
            raise Forbidden('not an admin')
        info = list(db_senses.find({'lemma': request.args['create']}))
        if len(info) == 0:
            if gwn_dbname is not None:
                from gwn_db import germanet
                gwn = germanet.get_database(gwn_dbname)
                lemma_for_gwn = wanted_lemma.replace('#', '')
                synsets = gwn.synsets_for_word(lemma_for_gwn)
            else:
                synsets = []
            objs = defaultdict(list)
            for synset in synsets:
                pos_cat = str(synset.word_category)[0].upper()
                lu_ids = [
                    lu.id for lu in synset.lexunit
                    if lu.orth_form == lemma_for_gwn
                    or lu.orth_var == lemma_for_gwn
                ]
                if lu_ids:
                    lu_id = lu_ids[0]
                else:
                    lu_id = '?'
                other_lus = [
                    lu.orth_form for lu in synset.lexunit
                    if lu.orth_form != lemma_for_gwn
                    and lu.orth_var != lemma_for_gwn
                ]
                if other_lus:
                    lu_descr = '_'.join(other_lus)
                else:
                    lu_descr = str(synset.word_class)
                objs[pos_cat].append([lu_id, lu_descr])
            info = []
            for k, v in objs.iteritems():
                info.append(make_sense(wanted_lemma, k, v))
            if len(info) == 0:
                if wanted_lemma[0].isupper():
                    info.append(make_sense(wanted_lemma, 'N'))
                else:
                    info.append(make_sense(wanted_lemma, 'V'))
                    info.append(make_sense(wanted_lemma, 'A'))
                    info.append(make_sense(wanted_lemma, 'R'))
        return Response(json.dumps(info), mimetype="text/javascript")
    else:
        info = list(db_senses.find({}))
        return Response(json.dumps(info), mimetype="text/javascript")
예제 #35
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()
예제 #36
0
def get_users():

    try:
        data = list(db.user.find())
        for u in data:
            u["_id"] = str(u["_id"])
        return Response(response=json.dumps(data),
                        status=200,
                        mimetype="application/json")
    except Exception as ex:
        return Response(response=json.dumps({"message": "User not found"}),
                        status=500,
                        mimetype="application/json")
예제 #37
0
def openlayers(req, path='ol_merc.html'):
    global html
    if not html:
        try:
            f = open(path, 'rb')
            html = f.read()
            f.close()
        except IOError:
            return Response('Openlayers HTML/JS file not found: %s' % path,
                            status=404,
                            mimetype='text/html')

    return Response(html, status=200, mimetype='text/html')
예제 #38
0
파일: themes.py 프로젝트: tzoght/solace
def get_resource(request, theme, file):
    """Returns a file from the theme."""
    theme = get_theme(theme)
    if theme is None:
        raise NotFound()
    f = theme.open_resource(file)
    if f is None:
        raise NotFound()
    resp = Response(wrap_file(request.environ, f),
                    mimetype=mimetypes.guess_type(file)[0] or 'text/plain',
                    direct_passthrough=True)
    resp.add_etag()
    return resp.make_conditional(request)
예제 #39
0
def index():
    """Upload a file, when the client has a valid session key.

    -- http://developer.getcloudapp.com/upload-file"""

    db, fs = current_app.db, current_app.fs
    config, sessions = current_app.config, current_app.sessions

    if request.method == 'POST' and not request.accept_mimetypes.accept_html:

        try:
            account = sessions.pop(request.form.get('key'))['account']
        except KeyError:
            abort(401)

        acc = db.accounts.find_one({'email': account})
        source = request.headers.get('User-Agent',
                                     'Regenschirm++/1.0').split(' ', 1)[0]
        privacy = request.form.get('acl', acc['private_items'])

        _id = fs.upload_file(config, account, request.files.get('file'),
                             source, privacy)

        items = acc['items']
        items.append(_id)
        db.accounts.update({'_id': acc['_id']}, {'$set': {
            'items': items
        }},
                           upsert=False)

        obj = fs.get(_id)

        if obj is None:
            abort(400)
        else:
            return jsonify(Item(obj, config, urlscheme(request)))
    else:
        users = db.accounts.find().count()
        files = fs.gfs._GridFS__files.count()
        size = sum([f['length'] for f in fs.gfs._GridFS__files.find()])
        hits = sum([f['view_counter'] for f in fs.mdb.find()])

        if request.args.get('format') == 'csv':
            fields = [('users', users), ('files', files), ('size', size),
                      ('hits', hits)]
            return Response('\n'.join('%s,%s' % field for field in fields),
                            200)

        return Response(render_template("index.html", **locals()),
                        200,
                        content_type="text/html")
예제 #40
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
예제 #41
0
def application(req):
    if req.method == 'POST':
        file_in = req.files['myfile']
        buf = convert_doc(file_in)

        filename = file_in.filename.replace('.odt', '-converted.odt')
        filename = urllib.parse.quote(filename)
        resp = Response(buf.getvalue())
        resp.content_type = 'application/x-download'
        resp.headers.add('Content-Disposition',
                         'attachment',
                         filename=filename)
        return resp
    return Response(HTML, content_type='text/html')
예제 #42
0
파일: blob.py 프로젝트: dpq/spooce
 def __call__(self, env, start_response):
     Config = ConfigParser()
     Config.read(configfile)
     params = {"host": "", "user": "", "database": "", "port": ""}
     for param in params:
         if not Config.has_option("BlobStore", param):
             print "Malformed configuration file: mission option %s in section %s" % (param, "BlobStore")
             sys.exit(1)
         params[param] = Config.get("BlobStore", param)
     req = Request(env)
     resp = Response(status=200, content_type="text/plain")
     #engine = create_engine("mysql+mysqldb://%s:%s@%s:%s/%s?charset=utf8&use_unicode=0" %
     #    (params["user"], secret.BlobSecret, params["host"], params["port"], params["database"]), pool_recycle=3600)
     Base = declarative_base(bind=engine)
     local.Session = []
     local.FileEntry = []
     Session.append(sessionmaker(bind=engine))
     FileEntry.append(makeFileEntry(Base))
     if req.path.startswith('/fx'):
         if req.method == "GET":
             resp.status_code, filename, resp.content_type, resp.response = self.__download(req)
             if resp.content_type == "application/octet-stream":
                 resp.headers["Content-Disposition"] = "attachment; filename=%s" % filename
             return resp(env, start_response)
         elif req.method == "POST":
             resp.content_type="text/plain"
             resp.response = self.__upload(req)
             return resp(env, start_response)
     else:
         resp.status_code = 404
         resp.content_type="text/plain"
         resp.response = ""
         return resp(env, start_response)
예제 #43
0
def upload_handler():
	# Add a task for handling the longer-running creation process
	# (Look through the zip archive, populate the datastore with some
	# metadata, etc.)
	bi = get_request_blobinfos(request)	
	for blob in bi:
		taskqueue.add(url=url_for('create_beta_release'), params={
			'blob-key': blob.key()
		})

	# Redirect to front page for now...
	rsp = Response(None, 301)
	rsp.headers['Location'] = url_for('index')
	return rsp
 def rtf(self, case_id, task_id):
     task = self._validate_task(case_id, task_id)
     if task is not None:
         self.check_permissions(self.current_user, task, 'view')
         stringio = render_rtf(task.notes)
         if stringio is None:
             return Response(self.error_msg,
                             mimetype='text/html',
                             status=200)
         return Response(stringio.getvalue(),
                         direct_passthrough=True,
                         mimetype='application/rtf',
                         status=200)
     else:
         return self.return_404()
def passthrough_xml_object():
    """ Passes through a non-CORS locked down XML object from the origin
    request. """
    if request.method == 'GET':
        reqUrl = request.args.get('url', '')
        req = requests.get(reqUrl)

        if req.status_code == 200:
            resp = Response(req.content,
                            content_type='text/xml; charset=utf-8')
            resp.headers['Access-Control-Allow-Origin'] = '*'
            #return Response(req.content, content_type='text/xml; charset=utf-8,', headers="Access-Control-Allow-Origin: *")
            return resp
        else:
            return false
예제 #46
0
def test_path_info_from_request_uri_fix():
    """Test the PathInfoFromRequestUriFix fixer"""
    app = fixers.PathInfoFromRequestUriFix(path_check_app)
    for key in 'REQUEST_URI', 'REQUEST_URL', 'UNENCODED_URL':
        env = dict(create_environ(), SCRIPT_NAME='/test', PATH_INFO='/?????')
        env[key] = '/test/foo%25bar?drop=this'
        response = Response.from_app(app, env)
        assert response.data == 'PATH_INFO: /foo%bar\nSCRIPT_NAME: /test'
예제 #47
0
def test_lighttpd_cgi_root_fix():
    """Test the LighttpdCGIRootFix fixer"""
    app = fixers.LighttpdCGIRootFix(path_check_app)
    response = Response.from_app(app, dict(create_environ(),
        SCRIPT_NAME='/foo',
        PATH_INFO='/bar'
    ))
    assert response.data == 'PATH_INFO: /foo/bar\nSCRIPT_NAME: '
예제 #48
0
파일: application.py 프로젝트: amadev/rater
def finalize_response(request, response):
    """Finalizes the response.  Applies common response processors."""
    if not isinstance(response, Response):
        response = Response.force_type(response, request.environ)
    if response.status == 200:
        response.add_etag()
        response = response.make_conditional(request)
    before_response_sent.emit(request=request, response=response)
    return response
예제 #49
0
파일: application.py 프로젝트: amadev/rater
 def process_view_result(self, rv):
     """Processes a view's return value and ensures it's a response
     object.  This is automatically called by the dispatch function
     but is also handy for view decorators.
     """
     if isinstance(rv, basestring):
         rv = Response(rv, mimetype='text/html')
     elif not isinstance(rv, Response):
         rv = Response.force_type(rv, self.environ)
     return rv
예제 #50
0
def test_fix_headers_in_response():
    """Make sure fix_headers still works for backwards compatibility"""
    from werkzeug import Response
    class MyResponse(Response):
        def fix_headers(self, environ):
            Response.fix_headers(self, environ)
            self.headers['x-foo'] = "meh"
    myresp = MyResponse('Foo')
    resp = Response.from_app(myresp, create_environ(method='GET'))
    assert resp.headers['x-foo'] == 'meh'
    assert resp.data == 'Foo'
예제 #51
0
    def __call__(self,req):
        """
        """
        print
        print 'Using %s' % self.mapfile
        print
        bbox = req.get('BBOX')
        env = map(float,bbox.split(','))
        bbox = mapnik.Envelope(*env)
        
        if self.singletile:
          self.mapnik_map.width,self.mapnik_map.height = int(req.get('WIDTH')),int(req.get('HEIGHT'))

        self.mapnik_map.zoom_to_box(bbox)
        draw = mapnik.Image(self.mapnik_map.width,self.mapnik_map.height)
        mapnik.render(self.mapnik_map,draw)
        image = draw.tostring('png256')
        
        response = Response(image, status=200, mimetype=self.mime)
        response.content_length = len(image)
        return response
예제 #52
0
def read_pagefile(url):
    wiki = get_wiki()
    user = current_user.get_id()
    page_url = os.path.dirname(url_from_viewarg(url)).\
        replace('\\', '/').\
        rstrip('/')
    page = get_page_or_raise(wiki, page_url, fields=['path'],
                             check_perms=(user, 'read'))
    # If no exception was thrown, we're good for reading the file.

    path_no_ext, _ = os.path.splitext(page.path)
    file_path = os.path.join(path_no_ext, os.path.basename(url))
    try:
        f = open(file_path, 'rb')
    except OSError:
        abort(404)

    r = Response(wrap_file(request.environ, f), direct_passthrough=True)
    _, ext = os.path.splitext(url)
    r.mimetype = mimetype_map.get(ext, '')
    return r
예제 #53
0
파일: views.py 프로젝트: gluwer/przepisymm
def count_view(request, key):
  try:
    db_key = db.Key(key)
    
    if db_key.kind() == 'Recipe':
      shard_key = SHARD_RECIPE_KEY % key
    else:
      shard_key = None
    
    if shard_key:
      Counter.incr(shard_key)

  except: # Don't care that much if something got wrong
    logging.exception('Error in count view')
    pass
  
  response = Response('GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;', mimetype='image/gif')
  response.expires = datetime.datetime(2009, 1, 1)
  response.cache_control.must_revalidate = True
  
  return response
예제 #54
0
def test_header_rewriter_fix():
    """Test the HeaderRewriterFix fixer"""
    @Request.application
    def application(request):
        return Response("", headers=[
            ('X-Foo', 'bar')
        ])
    application = fixers.HeaderRewriterFix(application, ('X-Foo',), (('X-Bar', '42'),))
    response = Response.from_app(application, create_environ())
    assert response.headers['Content-Type'] == 'text/plain; charset=utf-8'
    assert 'X-Foo' not in response.headers
    assert response.headers['X-Bar'] == '42'
예제 #55
0
파일: views.py 프로젝트: nakamuray/blikit
def blob(ctx, rev, path):
    if rev == "HEAD":
        commit_obj = ctx.odb.head
    elif rev == "index":
        commit_obj = ctx.odb.index
        if commit_obj is None:
            raise NotFound("No such file or directory")
    else:
        commit_obj = ctx.odb.get_commit(rev)

    try:
        blob_obj = commit_obj.tree[path]

    except KeyError:
        raise NotFound("No such file or directory")

    if isinstance(blob_obj, TreeObject):
        # redirect to same URL with trailing "/"
        return redirect(ctx.url_for("view_obj", rev=rev, path=path + "/"))
    elif isinstance(blob_obj, LinkObject):
        raise NotFound("No such file or directory")

    if "raw" in ctx.request.args:
        content_type, encoding = mimetypes.guess_type(blob_obj.name)

        if content_type is None:
            if "\x00" in blob_obj.data:
                content_type = "application/octat-stream"
            else:
                content_type = "text/plain"

        # TODO: use encoding
        response = Response(blob_obj.data, content_type=content_type)
        response.headers["X-Robots-Tag"] = "noindex"
    else:
        doc = render_blob(ctx, blob_obj)

        response = ctx.render_to_response("blob.html", doc=doc, blob=blob_obj, commit=commit_obj)

    return response
예제 #56
0
 def application(request):
     try:
         # Parse the JSON in the request
         try:
             data = loads(request.stream.read())
         except ValueError:
             raise BadRequest()
         # Grab the function to execute
         try:
             method = getattr(backend, data['method'])
         except (KeyError, IndexError):
             raise BadRequest()
         if method is None:
             raise NotFound()
         # Get the args and kwargs
         args = data.get('args', [])
         kwargs = data.get('kwargs', {})
         kwargs = dict(((k.encode('utf-8'), v) for k, v in kwargs.iteritems()))
         # Attempt to call the method with the params, or catch the
         # exception and pass that back to the client
         try:
             response = Response(dumps({
                 'id': data.get('id'),
                 'result': method(*args, **kwargs),
                 'error': None,
             }))
         except (KeyboardInterrupt, SystemExit):
             raise
         except Exception, e:
             print e
             response = Response(dumps({
                 'id': data.get('id'),
                 'result': None,
                 'error': ''.join(traceback.format_exception(*sys.exc_info())),
             }))
         # Finish up and return the response
         response.headers['Content-Type'] = 'application/json'
         response.headers['Content-Length'] = len(response.data)
         response.status_code = 200
         return response
예제 #57
0
 def on_subscribe(self, request):
     if request.method == "OPTIONS":
         # Handle cross-domian ajax
         response = Response()
         response.headers['Access-Control-Allow-Origin'] = '*'
         response.headers['Access-Control-Allow-Methods'] = 'GET'
         response.headers['Access-Control-Allow-Headers'] = 'last_modified,if-modified-since,x-requested-with'
         response.headers['Access-Control-Max-Age'] = 86400
         return response
         
     else:
         # Handle a normal request
         last_modified = local.last_modified = request.headers.get('last_modified', None)
         if last_modified is None:
             last_modified = local.last_modified = request.headers.get('If-Modified-Since', None)
             
         channel = request.args.get('channel', None)
     
         if channel is not None:
             if last_modified is not None:
                 last_modified = parse_timestr(last_modified)
                 last_modified += timedelta(seconds=1)
     
             local.next_update = next_update = self.get_next_update(channel, last_modified)
             while (next_update is None):
                 time.sleep(1)
                 next_update = self.get_next_update(channel, last_modified)
     
             response = self.send_update(next_update)
         else:
             response = Response(response="A channel get param must be passed.", status=400)
     
        
         response.headers['Access-Control-Allow-Origin'] = '*'
         response.headers['Access-Control-Allow-Methods'] = 'GET'
         response.headers['Access-Control-Allow-Headers'] = 'last_modified,if-modified-since,x-requested-with'
         response.headers['Access-Control-Max-Age'] = 86400
         return response
예제 #58
0
def direct_to_pdf(request, template_name, params=None,
                  pdf_name=None, download=False,
                  font_resolver=font_resolver,
                  image_resolver=image_resolver):
    """Simple generic view to tender rml template.
    """
    params = params or {}
    params['pdf_resource'] = pdf_resource
    pdf_name = pdf_name or params.pop('pdf_name', None)
    if pdf_name==None:
        tname_body = template_name.rpartition('/')[-1].rpartition('.')[0]
        if tname_body:
            pdf_name = tname_body+'.pdf'
        else:
            pdf_name = 'download.pdf'
    params['pdf_name'] = pdf_name
    pdf = render_to_pdf(template_name, params,
                        font_resolver=font_resolver,
                        image_resolver=image_resolver)
    response = Response(pdf, mimetype='application/pdf')
    if download:
        disposition = 'attachment; filename=%s' %(pdf_name)
        response.headers['Content-Disposition'] = disposition
    return response
예제 #59
0
def test_proxy_fix():
    """Test the ProxyFix fixer"""
    @fixers.ProxyFix
    @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']
        ))
    response = Response.from_app(app, dict(create_environ(),
        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'
    ))
    assert response.data == '1.2.3.4|example.com'