Amir
Amir

Reputation: 1061

How to enable decoding for specific Python class?

I have following code:

return render_template(
        'sample.html',
        title=('Härre').decode('utf-8'),
        year=datetime.now().year,
        message = ("Härre guut").decode('utf-8')
    )

Above code is working fine. But I want to know is it possible to enable automatic decoding for special characters for specific class? So that my code becomes like this:

return render_template(
        'sample.html',
        title=('Härre'),
        year=datetime.now().year,
        message = ("Härre guut")
    )

If yes then how it is done?

In my case special character is letter ä, and it can be decoded with utf-8.

I have tried to to add following line at first line of my code:

# -*- coding: utf-8 -*-

However that won't help. I get following error if I try to enable above line and take out all decode('utf-8') parts:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 12: ordinal not in range(128)

Which is very clear error. It tries to use 'ascii' codec to decode special characters of the code.

If you wonder why I want to enable such functionality, the answer is that in future I'm going to have more render_template() method. This method is used with Flask framework.

Upvotes: 1

Views: 115

Answers (3)

Alastair McCormack
Alastair McCormack

Reputation: 27704

Simply define your strings as Unicode strings using the u prefix:

return render_template(
        'sample.html',
        title=(u'Härre'),
        year=datetime.now().year,
        message = (u"Härre guut")
)

As you've baked non-ASCII into your source code, set the 'coding' bit at the top of your source code. Ensure your editor's character encoding matches the coding header.

# -*- coding: utf-8 -*- 

Upvotes: 1

Michelle Welcks
Michelle Welcks

Reputation: 3894

At the risk of being too trivial, you could make this decoding automatic by using Python 3, which uses Unicode instead of ascii.

Otherwise, as Brandon indicated, you do have to take pains with Python 2 to appropriately decode you inputs, use Unicode within your program, prefacing strings awing 'u', and the encoding when you output data, usually to utf-8, but whatever is appropriate for you.

Decoding and encoding at the "the edges" and using Unicode in between, is a lot of work, but necessary. It's a good reason to make the switch to Python 3. :-)

Upvotes: 1

NotAnAmbiTurner
NotAnAmbiTurner

Reputation: 2743

If you're only talking about string which you are typing, I'd try putting a u in front of them (eg. u'string'). The u tells python the string is unicode. I've used that successfully in similar circumstances in the past.

Also, according to the flask docs (way at the bottom), to use that # -*- coding: ... bit properly, you have to set your text editor to UTF-8, otherwise it's saving in ascii, which might be why you're still getting that error.

Upvotes: 2

Related Questions