当前位置: 首页>>代码示例>>Python>>正文


Python werkzeug.Response类代码示例

本文整理汇总了Python中werkzeug.Response的典型用法代码示例。如果您正苦于以下问题:Python Response类的具体用法?Python Response怎么用?Python Response使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Response类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: dispatch_request

    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
开发者ID:christianhans,项目名称:buteo,代码行数:33,代码来源:application.py

示例2: humanify

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
开发者ID:OriHoch,项目名称:dbs-back,代码行数:29,代码来源:utils.py

示例3: static

 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
开发者ID:mgax,项目名称:notespace,代码行数:7,代码来源:server.py

示例4: __call__

    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
开发者ID:smokey42,项目名称:PhotoBlog,代码行数:30,代码来源:app.py

示例5: response

    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)
开发者ID:DerRechner,项目名称:Hanabi,代码行数:30,代码来源:rest.py

示例6: miku

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
开发者ID:mzp,项目名称:home-image,代码行数:8,代码来源:views.py

示例7: store_pasta

 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
开发者ID:pombredanne,项目名称:pastabin,代码行数:9,代码来源:views.py

示例8: session_debug

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
开发者ID:bjornua,项目名称:fprojekt2010,代码行数:9,代码来源:responders.py

示例9: send_update

 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
开发者ID:SeanOC,项目名称:dev_push_server,代码行数:9,代码来源:application.py

示例10: create_blobinfo_response

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
开发者ID:mkrautz,项目名称:mumble-iphoneos-betaweb,代码行数:10,代码来源:util.py

示例11: serve_file

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
开发者ID:smokey42,项目名称:PhotoBlog,代码行数:11,代码来源:images.py

示例12: application

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')
开发者ID:gdamjan,项目名称:convertor,代码行数:11,代码来源:web_app.py

示例13: message

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()
开发者ID:lucian1900,项目名称:webcollab,代码行数:13,代码来源:views.py

示例14: get_resource

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)
开发者ID:DasIch,项目名称:solace,代码行数:13,代码来源:themes.py

示例15: __call__

 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:%[email protected]%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)
开发者ID:dpq,项目名称:spooce,代码行数:33,代码来源:blob.py


注:本文中的werkzeug.Response类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。