App Engine上的Pyramid获取“InvalidResponseError:标题值必须是str,得到'unicode' [英] Pyramid on App Engine gets "InvalidResponseError: header values must be str, got 'unicode'

查看:89
本文介绍了App Engine上的Pyramid获取“InvalidResponseError:标题值必须是str,得到'unicode'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在OS X 10.7.3上使用Pyramid 1.3和AppEngine 1.6.4 SDK。

  @view_config(route_name ='manager_swms',permission ='经理',renderer ='经理/ swms.jinja2')
def manager_swms(请求):
生成blobstore url并将swms表传递给用户swms

#为可能出现的任何表单上载生成url
upload_url = blobstore.create_upload_url('/ upload_swm')
$ b $ user = get_current_user(请求)
swms = DBSession.query( SWMS).filter_by(owner_id = int(user.id))。all()

返回{
analytics_id:analytics_id,
user:get_current_user(request) ,
upload_url:upload_url,
swms:[(x.filename,x.blob_key)for x in swms]
}

class BlobstoreUploadHandler )

def __init __(self,* args,** kwargs):
self .__ uploads =无

de f get_uploads(self,field_name = None):
获取发送到这个处理程序的上传。

参数:
field_name:只选择作为特定字段发送的上传。

返回:
与每次上传相对应的BlobInfo记录列表。
如果field_name没有blob-info记录,则为空列表。

如果self .__ uploads是None:
self .__ uploads = {}
for key,self.request.params.items()中的值:
如果isinstance(value,cgi.FieldStorage):
如果'blob-key'在value.type_options中:
self .__ uploads.setdefault(key,[])。append(
blobstore。 parse_blob_info(value))

如果field_name:
尝试:
返回列表(self .__ uploads [field_name])
除KeyError:
return []
else:
results = []
用于上传自己.__ uploads.itervalues():
结果+ =上传
返回结果

@view_config(route_name ='upload_swm',permission ='manager')
UploadHandler(BlobstoreUploadHandler):
'''处理来自Blobstore上传的重定向。'''

def __init __(self,request):
self.request =请求
super(UploadHandler,self).__ init __()
$ b $ def __call __(self):

user = get_current_user(self.request)
用于self.get_uploads('file')中的blob_info:

new_swm = SWMS(
owner_id = int(user.id ),
blob_key = str(blob_info.key()),
filename = blob_info.filename,
size = blob_info.size,

DBSession.add( new_swm)
DBSession.flush()

#重定向到swms页面
return HTTPFound(location ='/ manager / swms')

在上面的代码中,manager_swms()生成一个页面,其中包含一个用于将文件上传到Blobstore的表单。表单工作正常,当使用表单时,我可以看到blob出现在Blobstore中。然后,blobstore POST的重定向到/ upload_swm,我成功地将BlobInfo详细信息放入SQL表中。所有这一切都很好,我想要做的最后一件事就是重定向到第一页,以便在需要时可以上传另一个文件,并且可以显示上传的文件列表。



根据金字塔文档,我使用HTTPFound(location ='/ manager / swms')[原始页面URL]尝试重定向,但是我得到:

 错误2012-03-29 22:56:38,170 wsgi.py:208] 
追溯(最近一次调用最后一次):
文件/ Users / tim /工作/ OHSPro / var / parts / google_appengine / google / appengine / runtime / wsgi.py,第196行,处理
result = handler(self._environ,self._StartResponse)
文件lib /在__call__
foo = response(request.environ,start_response)
文件lib / dist / pyramid / httpexceptions.py中,第291行中的dist / pyramid / router.py
foo =响应.__调用__(self,environ,start_response)
在__call__
start_response(self.status,headerlist)中的文件lib / dist / webob / response.py,第922行,
Fi le/Users/tim/work/OHSPro/var/parts/google_appengine/google/appengine/runtime/wsgi.py,第150行,位于_StartResponse
_GetTypeName(header [1]))
InvalidResponseError :头值必须是str,得到'unicode'
INFO 2012-03-29 22:56:38,174 dev_appserver_blobstore.py:408]上传处理程序返回500
INFO 2012-03-29 22:56: 38,193 dev_appserver.py:2884]POST / _ah / upload / ahJkZXZ-cHJvdG8tc2NvaHNwcm9yGwsSFV9fQmxvYlVwbG9hZFNlc3Npb25fXxgTDA HTTP / 1.1500 -



< AppEngine显然是反对HTTP头中的unicode,但我没有做任何异常的AFAIK。如果我放入pdb中并查看HTTPFound对象,则标头为:

  ResponseHeaders([('Content-Type ','text / html; charset = UTF-8'),('Content-Length','0'),('Location','/ manager / swms')])
解决方案

div>

所以你看起来像是覆盖了appengine支持的webob,它是1.1.1的 2.7 runtime。金字塔1.3取决于webob> = 1.2。这很可能是问题,因为它是Blobstore处理程序的东西,它将sdk保持在webob == 0.9,直到SDK 1.6.4发布。

FWIW,这个问题有望通过SDK 1.6.5(4月下旬)解决。我知道这一点的唯一原因是因为我试图在2.7运行时被认为可以用于一般用途时解决所有这些问题,但SDK不支持它。请参阅问题了解更多详情。

如果可能的话,我会建议用金字塔1.2来运行它,我知道在appengine上运行得很好。并且坚持几个星期的1.3。 :)

I am using Pyramid 1.3 with the AppEngine 1.6.4 SDK on OS X 10.7.3. I am using Python 2.7 and have threadsafe true in app.yaml.

@view_config(route_name='manager_swms', permission='manager', renderer='manager/swms.jinja2')
def manager_swms(request):
    """Generates blobstore url and passes users swms in swms table"""

    # generate url for any form upload that may occur
    upload_url = blobstore.create_upload_url('/upload_swm')

    user = get_current_user(request)
    swms = DBSession.query(SWMS).filter_by(owner_id=int(user.id)).all()

    return {
        "analytics_id": analytics_id,
        "user": get_current_user(request),
        "upload_url": upload_url,
        "swms": [(x.filename, x.blob_key) for x in swms]
    }

class BlobstoreUploadHandler(object):
    """Base class for creation blob upload handlers."""

    def __init__(self, *args, **kwargs):
        self.__uploads = None

    def get_uploads(self, field_name=None):
        """Get uploads sent to this handler.

        Args:
          field_name: Only select uploads that were sent as a specific field.

        Returns:
          A list of BlobInfo records corresponding to each upload.
          Empty list if there are no blob-info records for field_name.
        """
        if self.__uploads is None:
            self.__uploads = {}
            for key, value in self.request.params.items():
                if isinstance(value, cgi.FieldStorage):
                    if 'blob-key' in value.type_options:
                        self.__uploads.setdefault(key, []).append(
                            blobstore.parse_blob_info(value))

        if field_name:
            try:
                return list(self.__uploads[field_name])
            except KeyError:
                return []
        else:
            results = []
            for uploads in self.__uploads.itervalues():
                results += uploads
            return results

@view_config(route_name='upload_swm', permission='manager')
class UploadHandler(BlobstoreUploadHandler):
    ''' Handles redirects from Blobstore uploads. '''

    def __init__(self, request):
        self.request = request
        super(UploadHandler, self).__init__()

    def __call__(self):

        user = get_current_user(self.request)
        for blob_info in self.get_uploads('file'):

            new_swm = SWMS(
                owner_id = int(user.id),
                blob_key = str(blob_info.key()),
                filename = blob_info.filename,
                size = blob_info.size,
            )
            DBSession.add(new_swm)
        DBSession.flush()

        # redirect to swms page
        return HTTPFound(location='/manager/swms')

In the above code, manager_swms() generates a page which includes a form for uploading a file into the Blobstore. The form works OK and I can see the blob appear in the Blobstore when the form is used. The redirect from the blobstore POST is then to /upload_swm where I successfully take BlobInfo details and place them into a SQL table. All of this is good and the final thing I want to do is redirect to the first page so another file can be uploaded if need be and I can show the list of files uploaded.

As per Pyramid documentation, I am using HTTPFound(location='/manager/swms') [the original page URL] to try and redirect however I get:

ERROR    2012-03-29 22:56:38,170 wsgi.py:208] 
Traceback (most recent call last):
  File "/Users/tim/work/OHSPro/var/parts/google_appengine/google/appengine/runtime/wsgi.py", line 196, in Handle
    result = handler(self._environ, self._StartResponse)
  File "lib/dist/pyramid/router.py", line 195, in __call__
    foo = response(request.environ, start_response)
  File "lib/dist/pyramid/httpexceptions.py", line 291, in __call__
    foo = Response.__call__(self, environ, start_response)
  File "lib/dist/webob/response.py", line 922, in __call__
    start_response(self.status, headerlist)
  File "/Users/tim/work/OHSPro/var/parts/google_appengine/google/appengine/runtime/wsgi.py", line 150, in _StartResponse
    _GetTypeName(header[1]))
InvalidResponseError: header values must be str, got 'unicode'
INFO     2012-03-29 22:56:38,174 dev_appserver_blobstore.py:408] Upload handler returned 500
INFO     2012-03-29 22:56:38,193 dev_appserver.py:2884] "POST /_ah/upload/ahJkZXZ-cHJvdG8tc2NvaHNwcm9yGwsSFV9fQmxvYlVwbG9hZFNlc3Npb25fXxgTDA HTTP/1.1" 500 -

AppEngine is clearly objecting to unicode in the HTTP header but I'm not doing anything unusual AFAIK. If I drop into pdb and take a look at the HTTPFound object, the headers are:

ResponseHeaders([('Content-Type', 'text/html; charset=UTF-8'), ('Content-Length', '0'), ('Location', '/manager/swms')])

Why would I get a unicode problem from these?

解决方案

so it looks like you are overriding appengine's supported webob which is 1.1.1 on the 2.7 runtime. And pyramid 1.3 depends on webob>=1.2. This is most likely the problem because it was the Blobstore handler stuff that was keeping the sdk held back at webob==0.9 until SDK 1.6.4 was released.

FWIW, this problem is expected to be resolved by SDK 1.6.5 (late April). The only reason I know this is because I was trying to get all this crap resolved when the 2.7 runtime was deemed ready for general use, yet the SDK didn't support it. see this issue for more details.

If possible, I would suggest running it with pyramid 1.2, I know that works fine on appengine. And Just hold off on moving to 1.3 for a few weeks. :)

这篇关于App Engine上的Pyramid获取“InvalidResponseError:标题值必须是str,得到'unicode'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆