• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python werkzeug.Response类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: upload_handler

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


示例17: test_path_info_from_request_uri_fix

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'
开发者ID:AndryulE,项目名称:kitsune,代码行数:8,代码来源:test_fixers.py


示例18: test_lighttpd_cgi_root_fix

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: '
开发者ID:AndryulE,项目名称:kitsune,代码行数:8,代码来源:test_fixers.py


示例19: finalize_response

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


示例20: process_view_result

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



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python _compat.iteritems函数代码示例发布时间:2022-05-26
下一篇:
Python werkzeug.Request类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap