Gilbert
Gilbert

Reputation: 921

Having encoded a unicode string in javascript, how can I decode it in Python?

Platform: App Engine Framework: webapp / CGI / WSGI

On my client side (JS), I construct a URL by concatenating a URL with an unicode string:

http://www.foo.com/地震

then I call encodeURI to get

http://www.foo.com/%E5%9C%B0%E9%9C%87

and I put this in a HTML form value.

The form gets submitted to PayPal, where I've set the encoding to 'utf-8'.

PayPal then (through IPN) makes a post request on the said URL.

On my server side, WSGIApplication tries to extract the unicode string using a regular expression I've defined:

(r'/paypal-listener/(.+?)', c.PayPalIPNListener)

I'd try to decode it by calling

query = unquote_plus(query).decode('utf-8')

(or a variation) but I'd get the error

/paypal-listener/%E5%9C%B0%E9%9C%87

... (ommited) ...

'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

(the first line is the request URL)

When I check the length of query, python says it has length 18, which suggests to me that '%E5%9C%B0%E9%9C%87' has not been encoded in anyway.

Upvotes: 2

Views: 3936

Answers (6)

Lasitha Lakmal
Lasitha Lakmal

Reputation: 880

check out this way

  var uri = "https://rasamarasa.com/service/catering/ගාල්ල-Galle";
  var uri_enc = encodeURIComponent(uri);
  var uri_dec = decodeURIComponent(uri_enc);
  var res = "Encoded URI: " + uri_enc + "<br>" + "Decoded URI: " + uri_dec;
  document.getElementById("demo").innerHTML = res;

for more check this link https://www.w3schools.com/jsref/jsref_decodeuricomponent.asp

Upvotes: 0

jfs
jfs

Reputation: 414835

urllib.unquote() doesn't like unicode-string in this case. Pass it byte-string and decode afterwards to get unicode.

This works:

>>> u = u'http://www.foo.com/%E5%9C%B0%E9%9C%87'
>>> print urllib.unquote(u.encode('ascii'))
http://www.foo.com/地震
>>> print urllib.unquote(u.encode('ascii')).decode('utf-8')
http://www.foo.com/地震

This doesn't (see also urllib.unquote decodes percent-escapes with Latin-1):

>>> print urllib.unquote(u)
http://www.foo.com/å °é  

Decoding string that already unicode doesn't work:

>>> print urllib.unquote(u).decode('utf-8')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File ".../lib/python2.6/encodings/utf_8.py", line
16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 19-24: o
rdinal not in range(128)

Upvotes: 0

bobince
bobince

Reputation: 536715

In principle this should work:

>>> urllib.unquote_plus('http://www.foo.com/%E5%9C%B0%E9%9C%87').decode('utf-8')
u'http://www.foo.com/\u5730\u9707'

However, note that:

  1. unquote_plus is for application/x-form-www-urlencoded data such as POSTed forms and query string parameters. In the path part of a URL, + means a literal plus sign, not space, so you should use plain unquote here.

  2. You shouldn't generally unquote a whole URL. Characters that have special meaning in a component of the URL will be lost. You should split the URL into parts, get the single pathname component (%E5%9C%B0%E9%9C%87) that you are interested in, and then unquote it.

(If you want to fully convert a URI to an IRI like http://www.foo.com/地震 things are a bit more complicated. Only the path/query/fragment part of an IRI is UTF-8-%-encoded; the domain name is mapped between Unicode and bytes using the oddball ‘Punycode’ IDN scheme.)

This gets received in my python server side.

What exactly is your server-side? Server, gateway, framework? And how are you getting the url variable?

You appear to be getting a UnicodeEncodeError, which is about unexpected non-ASCII characters in the input to the unquote function, not an decoding problem at all. So I suggest that something has already decoded the path part of your URL to a Unicode string of some sort. Let's see the repr of that variable!

There are unfortunately a number of serious problems with several web servers that makes using Unicode in the pathname part of a URL very unreliable, not just in Python but generally.

The main problem is that the PATH_INFO variable is defined (by the CGI specification, and subsequently by WSGI) to be pre-decoded. This is a dreadful mistake partly because of issue (1) above, which means you can't get %2F in a path part, but more seriously because decoding a %-sequence introduces a Unicode decode step that is out of the hands of the application. Server environments differ greatly in how non-ASCII %-escapes in the URL are handled, and it is often impossible to recreate the exact sequence of bytes that the web browser passed in.

IIS is a particular problem in that it will try to parse the URL path as UTF-8 by default, falling back to the wildly-unreliable system default codepage (eg. cp1252 on a Western Windows install) if the path isn't a valid UTF-8 sequence, but without telling you. You are then likely to have fairly severe problems trying to read any non-ASCII characters in PATH_INFO out of the environment variables map, because Windows envvars are Unicode but are accessed by Python 2 and many others as bytes in the system codepage.

Apache mitigates the problem by providing an extra non-standard environ REQUEST_URI that holds the original, completely undecoded URL submitted by the browser, which is easy to handle manually. However if you are using URL rewriting or error documents, that unmapped URL may not match what you thought it was going to be.

Some frameworks attempt to fix up these problems, with varying degrees of success. WSGI 1.1 is expected to make a stab at standardising this, but in the meantime the practical position we're left in is that Unicode paths won't work everywhere, and hacks to try to fix it on one server will typically break it on another.

You can always use URL rewriting to convert a Unicode path into a Unicode query parameter. Since the QUERY_STRING environ variable is not decoded outside of the application, it is much easier to handle predictably.

Upvotes: 3

cryo
cryo

Reputation: 14515

Assuming the HTML page is encoded in utf-8, it should just be a simple path.decode('utf-8') if the framework decodes the URLs percentage escapes.

If it doesn't, you could use:

  • urllib.unquote(path).decode('utf-8') if the URL is http://www.foo.com/地震
  • urllib.unquote_plus(path).decode('utf-8') if you're talking about a parameter sent via AJAX or in an HTML <form>

(see http://docs.python.org/library/urllib.html#urllib.unquote)

EDIT: Please supply us with the following information if you're still having problems to help us track this problem down:

  • Which web framework you're using inside of google app engine, e.g. Django, WebOb, CGI etc

  • How you're getting the URL in your app (please add a short code sample if you can)

  • repr(url) of when you add http://www.foo.com/地震 as the URL

  • Try adding this as the URL and post repr(url) so we can make sure the server isn't decoding the characters as either latin-1 or Windows-1252:

    http://foo.com/¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ
    

EDIT 2: Seeing as it's an actual URL (and not in the query section i.e. not http://www.foo.com/?param=%E5%9C%B0%E9%9C%87), doing

query = unquote(query.encode('ascii')).decode('utf-8')

is probably safe. It should be unquote and not unquote_plus if you're decoding the actual URL though. I don't know why google passes the URL as a unicode object but I doubt the actual URL passed to the app would be decoded using windows-1252 etc. I was a bit concerned as I thought it was decoding the query incorrectly (i.e. the parameters passed to GET or POST) but it doesn't seem to be doing that by the looks of it.

Upvotes: 1

si28719e
si28719e

Reputation: 2165

aaaah, the dreaded

'ascii' codec can't encode characters in position... ordinal not in range

error. unavoidable when dealing with languages like Japanese in python...

this is not a url encode/decode issue in this case. your data is most likely already decoded and ready to go.

i would try getting rid of the call to 'decode' and see what happens. if you get garbage but no error it probably means people are sending you data in one of the other lovely japanese specific encodings: eucjp, iso-2022-jp, shift-jis, or perhaps even the elusive iso-2022-jp-ext which is nowadays only rarely spotted in the wild. this latter case seems pretty unlikely though.

edit: id also take a look at this for reference: What is the difference between encode/decode?

Upvotes: -1

Sarfraz
Sarfraz

Reputation: 382881

Usually there is a function in server-side languages to decode urls, there might be one in Python as well. You can also use the decodeURIComponent() function of javascript in your case.

Upvotes: 0

Related Questions