โมดูล stringprep ใช้เตรียม Unicode Strings ตาม RFC 3454 ก่อนส่งผ่าน Network ใช้สำหรับ Internationalized Domain Names (IDNA), SASL, XMPP ฯลฯ
import stringprep
หลักการ
- Mapping: Map Characters ตามตาราง (เช่น Case Folding)
- Normalization: Unicode Normalization (NFKC)
- Prohibition: ตรวจสอบห้ามมี Characters ที่ห้าม
- Bidirectional: ตรวจสอบ Bidi Properties
- Unassigned: ตรวจสอบ Unassigned Code Points
Profiles (ชุด Rules รวม)
- Nameprep - Internationalized Domain Names (RFC 3491)
- SASLprep - SASL Authentication (RFC 4013)
- Resourceprep - XMPP Resource Parts
- Nodeprep - XMPP Node Parts
Tables ใน stringprep (RFC 3454)
| Table | Function | คำอธิบาย |
|---|---|---|
| A.1 | in_table_a1 | Unassigned Code Points in Unicode 3.2 |
| B.1 | in_table_b1 | Commonly Mapped to Nothing |
| B.2 | in_table_b2 | Mapping for NFKC Case-folding |
| B.3 | in_table_b3 | Case-folding No Normalization |
| C.1.1 | in_table_c11 | ASCII Space Characters |
| C.1.2 | in_table_c12 | Non-ASCII Space Characters |
| C.1.1+C.1.2 | in_table_c11_c12 | Combined Spaces |
| C.2.1 | in_table_c21 | ASCII Control Characters |
| C.2.2 | in_table_c22 | Non-ASCII Control Characters |
| C.3 | in_table_c3 | Private Use Characters |
| C.4 | in_table_c4 | Non-character Code Points |
| C.5 | in_table_c5 | Surrogate Codes |
| C.6 | in_table_c6 | Inappropriate for Plain Text |
| C.7 | in_table_c7 | Inappropriate for Canonical Representation |
| C.8 | in_table_c8 | Display Property Change |
| C.9 | in_table_c9 | Tagging Characters |
| D.1 | in_table_d1 | Bidi 'R' or 'AL' (Right-to-Left) |
| D.2 | in_table_d2 | Bidi 'L' (Left-to-Right) |
โค้ดตัวอย่าง
import stringprep as sp
# Space Character (U+0020)
print(sp.in_table_c11('\u0020')) # True (ASCII Space)
print(sp.in_table_c12('\u0020')) # False
# Bidirectional
print(sp.in_table_d2('L')) # True (Left-to-Right)
print(sp.in_table_d1('L')) # False
# Control Character
print(sp.in_table_c21('\x00')) # True (NULL)
print(sp.in_table_c21('A')) # False
# Private Use
print(sp.in_table_c3('\uE000')) # True (Private Use Area)
ผลลัพธ์
True False True False True False True
การใช้งานจริง: Nameprep (IDNA)
Python มี idna Encoding Built-in (ใช้ stringprep ภายใน)
# IDNA Encoding (RFC 5891)
domain = 'münchen.de'
encoded = domain.encode('idna')
print(encoded) # b'xn--mnchen-3ya.de'
decoded = encoded.decode('idna')
print(decoded) # münchen.de
กรณีใช้งาน
- Internationalized Domain Names (IDN)
- XMPP/Jabber Identifiers
- SASL Authentication
- Email Address Internationalization (EAI)
- Username Normalization
หมายเหตุ
- โมดูลนี้ Low-level มาก ใช้ผ่าน High-level Libraries (idna, pysasl, xmpp) ดีกว่า
- RFC 3454 ถูก Supersede โดย RFC 7564 (PRECIS Framework)
- Python 3.10+ มี
stringprepแต่ไม่ควรใช้โดยตรงสำหรับ Application ใหม่