Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Internet String Preparation ใน Python (โมดูล stringprep)

โมดูล stringprep ใช้เตรียม Unicode Strings ตาม RFC 3454 ก่อนส่งผ่าน Network ใช้สำหรับ Internationalized Domain Names (IDNA), SASL, XMPP ฯลฯ

import stringprep


หลักการ

  1. Mapping: Map Characters ตามตาราง (เช่น Case Folding)
  2. Normalization: Unicode Normalization (NFKC)
  3. Prohibition: ตรวจสอบห้ามมี Characters ที่ห้าม
  4. Bidirectional: ตรวจสอบ Bidi Properties
  5. 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)

TableFunctionคำอธิบาย
A.1in_table_a1Unassigned Code Points in Unicode 3.2
B.1in_table_b1Commonly Mapped to Nothing
B.2in_table_b2Mapping for NFKC Case-folding
B.3in_table_b3Case-folding No Normalization
C.1.1in_table_c11ASCII Space Characters
C.1.2in_table_c12Non-ASCII Space Characters
C.1.1+C.1.2in_table_c11_c12Combined Spaces
C.2.1in_table_c21ASCII Control Characters
C.2.2in_table_c22Non-ASCII Control Characters
C.3in_table_c3Private Use Characters
C.4in_table_c4Non-character Code Points
C.5in_table_c5Surrogate Codes
C.6in_table_c6Inappropriate for Plain Text
C.7in_table_c7Inappropriate for Canonical Representation
C.8in_table_c8Display Property Change
C.9in_table_c9Tagging Characters
D.1in_table_d1Bidi 'R' or 'AL' (Right-to-Left)
D.2in_table_d2Bidi '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 ใหม่