當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。