Python 瓶子 + postgresql

Python bottle + postgresql

我有问题。我安装了 pgadmin3。创建了一个编码为 UTF-8 的库。创建文件 index.py:

# -*- coding utf-8 -*-

from bottle import route, run, template, request, install
from bottle_pgsql import PgSQLPlugin

install(PgSQLPlugin('dbname=test, user=postgres password=111'))

@route('/hello')
def hello(db):
    c = db.execute('''SELECT gorod FROM gorod''')
    result = c.fetchone()
    return template('hello', rows=result)

run (host='localhost', port=8080, debug=True)

接下来我创建了 tpl 文件 hello.tpl:

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8">
        <title>Статистика</title>
    </head>
    <body>
        <h1>{{rows}}</h1>
    </body>
</html>

当我转到页面 http://localhost:8080/hello error:

Critical error while processing request: /hello

Error:

UnicodeDecodeError('utf8', 'Traceback (most recent call last):\n  File "C:\Users\User\Desktop\test\bottle.py", line 862, in _handle\n    return route.call(**args)\n  File "C:\Users\User\Desktop\test\bottle.py", line 1732, in wrapper\n    rv = callback(*a, **ka)\n  File "C:\Users\User\Desktop\test\bottle_pgsql.py", line 83, in wrapper\n    con = psycopg2.connect(dsn)\n  File "C:\Python27\lib\site-packages\psycopg2\__init__.py", line 164, in connect\n    conn = _connect(dsn, connection_factory=connection_factory, async=async)\nOperationalError: \xc2\xc0\xc6\xcd\xce:  \xe1\xe0\xe7\xe0 \xe4\xe0\xed\xed\xfb\xf5 "test," \xed\xe5 \xf1\xf3\xf9\xe5\xf1\xf2\xe2\xf3\xe5\xf2\n\n', 512, 513, 'invalid continuation byte')
Traceback:

Traceback (most recent call last):
  File "C:\Users\User\Desktop\test\bottle.py", line 954, in wsgi
    out = self._cast(self._handle(environ))
  File "C:\Users\User\Desktop\test\bottle.py", line 907, in _cast
    out = self.error_handler.get(out.status_code, self.default_error_handler)(out)
  File "C:\Users\User\Desktop\test\bottle.py", line 842, in default_error_handler
    return tob(template(ERROR_PAGE_TEMPLATE, e=res))
  File "C:\Users\User\Desktop\test\bottle.py", line 3595, in template
    return TEMPLATES[tplid].render(kwargs)
  File "C:\Users\User\Desktop\test\bottle.py", line 3399, in render
    self.execute(stdout, env)
  File "C:\Users\User\Desktop\test\bottle.py", line 3386, in execute
    eval(self.co, env)
  File "<string>", line 26, in <module>
  File "C:\Users\User\Desktop\test\bottle.py", line 3337, in <lambda>
    self._escape = lambda x: escape_func(touni(x, enc))
  File "C:\Users\User\Desktop\test\bottle.py", line 123, in touni
    return s.decode(enc, err) if isinstance(s, bytes) else unicode(s)
  File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc2 in position 512: invalid continuation byte

你能帮帮我吗! 对不起,我的英语不好 ;) 谢谢

您是否尝试过使用 UTF-8 对您的模板文件进行编码?

以 iconv 为例:

iconv -f ascii -t utf-8 "hello.tpl" -o "hello.tpl"

编辑:您可以使用iconv for windows here