URL for non English in django

March 23, 2011

ว่าด้วยเรื่อง IRI และ URI
From: uri-and-iri-handling

ปัญหามีอยู่ว่า เราต้องการ url ที่เป็นภาษาไทยแต่่่่่่่่่่พอ apache (LAM) มันดันเก็บไฟล์ไว้ในโครงสร้างที่เป็น native code
ตัว browser เองก็จัดการแปลงภาษาไทยให้เป็น unicode เรียบร้อยแต่พอไปถึงตัว django ที่จะทำการ Lookup หา file path กลับไม่เจอ
เรื่องง่ายแบบนี้มีผิดบ่อย

ยกตัวอย่าง เราอยากได้ url http://www/ยูอาร์แอล

Browser ก็ทำการแปลงและ request มาที่ django อัตโนมัติถ้าเป็นเราเก็บ location ของ file ไว้เป็น unicode แต่แรกก็จะเหมาะเจาะไม่เกิดปัญหาอะไร
แต่เรากลับไปเก็บไว้เป็น tis-620 นี่สิ

หน้าตาของ “ยูอาร์แอล” ใน unicode เป็นทำนองนี้

'\xe0\xb8\xa2\xe0\xb8\xb9\xe0\xb8\xad\xe0\xb8\xb2\xe0\xb8\xa3\xe0\xb9\x8c\xe0\xb9\x81\xe0\xb8\xad\xe0\xb8\xa5'
    import django
    from django.utils.encoding import *
    smart_str("ยูอาร์แอล", encoding='tis620')

    '\xc2\xd9\xcd\xd2\xc3\xec\xe1\xcd\xc5'

ทางแก้ไขไม่ยากอย่างที่คิดเพราะ django มี function ให้เรียบร้อยคือจับใส่ function

    iri_to_uri(smart_str("ยูอาร์แอล", encoding='tis-620'))

งานนี้เลยได้ Best practice ไปในตัวคือ ว่าเวลาเก็บไฟล์ไว้ควรจะให้ encoding location เป็น unicode ก่อน
ส่วน คำแนะนำสำหรับการแก้ปัญหาระยะยาวคือ ให้ migrate location เดิมที่เป็น native หรือ tis-620 ไปเป็น unicode utf-8 ให้เรียบร้อย

posted in Uncategorized by Tomz

Follow comments via the RSS Feed | Leave a comment | Trackback URL

2 Comments to "URL for non English in django"

  1. Champ wrote:

    that’s so useful

    Keep sharing good things here Bro!

  2. chch wrote:

    Good blog!

Leave Your Comment

 
 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org