user1459985
user1459985

Reputation: 23

Can pyramid change the default request.charset from utf-8 to gbk?

I am new to pyramid. I use python2.7, MSSQL, slqalchemy.mssql and use the gbk charset, and I have much old data. So I change the front html to encode to gbk, using the following code:

@view_config(route_name='g', renderer='json')
def my_view1(request):
  print 2
  print request.charset
  print 1
  print isinstance(request.params['one'], str)
  if request.params['one']:
    print request.params['one']
    filters = (Bzjl.one == request.params['one'])
  try:
    two1 = DBSession.query(Bzjl).filter(filters)
  except DBAPIError:
    return Response(conn_err_msg, content_type='text/plain', status_int=500)
  return Response(getjson(two1))

example url: http://127.0.0.1:6543/g?one='中国福建' returns no rows: {"records": 0, "total": 20, "rows": [], "page": 1}

Upvotes: 2

Views: 848

Answers (1)

Michael Merickel
Michael Merickel

Reputation: 23331

Pyramid supports a request factory. You can use this to decode the request.

def request_factory(environ):
    req = pyramid.request.Request(environ)
    return req.decode(charset='gbk')

config.set_request_factory(request_factory)

This means that the request passed around within pyramid will be using the gbk charset. Failure to decode the request with this charset will cause UnicodeDecodeError exceptions so you may want to add extra logic to your request factory to handle these things.

Upvotes: 4

Related Questions