Python में Base64 Encode: b64encode की पूरी गाइड
मुफ़्त Base64 Encode Online को सीधे अपने ब्राउज़र में उपयोग करें — इंस्टॉलेशन की ज़रूरत नहीं।
Base64 Encode Online ऑनलाइन आज़माएं →जब आप Python सर्विसेज बनाते हैं जो HTTP Basic Auth हेडर में credentials पास करती हैं, API रिस्पॉन्स में बाइनरी एसेट एम्बेड करती हैं, या environment variables में TLS सर्टिफिकेट स्टोर करती हैं, तो आपको नियमित रूप से base64 encode Python कोड लिखना पड़ता है। Python base64 मॉड्यूल को standard library के साथ शिप करता है — pip install की जरूरत नहीं — लेकिन bytes-vs-string का अंतर और b64encode, urlsafe_b64encode, और encodebytes के बीच का फर्क developers को अक्सर उम्मीद से ज्यादा उलझाता है। बिना कोड लिखे तुरंत encode करने के लिए, ToolDeck का Base64 एनकोडर इसे ब्राउज़र में तुरंत हैंडल करता है। यह गाइड पूरी stdlib API, JWT के लिए URL-safe encoding, फाइल और API रिस्पॉन्स परिदृश्य, CLI शॉर्टकट, एक हाई-परफॉर्मेंस विकल्प, और कोड रिव्यू में अक्सर दिखने वाली चार गलतियाँ कवर करती है।
- ✓base64.b64encode() bytes की अपेक्षा करता है, str की नहीं — इनपुट स्ट्रिंग पास करने से पहले हमेशा .encode("utf-8") कॉल करें
- ✓रिटर्न वैल्यू भी bytes है — JSON या HTTP हेडर में एम्बेड करने के लिए plain str पाने हेतु .decode("utf-8") या .decode("ascii") कॉल करें
- ✓base64.urlsafe_b64encode() + → - और / → _ बदलता है लेकिन = पैडिंग रखता है — JWT सेगमेंट के लिए .rstrip("=") से मैन्युअली हटाएं
- ✓base64.encodebytes() हर 76 कैरेक्टर पर \n डालता है (MIME फॉर्मेट) — data URI, JSON फील्ड या environment variables के लिए कभी उपयोग न करें
- ✓pybase64 (C एक्सटेंशन, ड्रॉप-इन API) stdlib से 2–10× तेज एन्कोड करता है; बड़े पेलोड प्रोसेस करने वाली हाई-थ्रूपुट सर्विसेज के लिए उपयुक्त
Base64 Encoding क्या है?
Base64 मनमाने बाइनरी डेटा को 64 printable ASCII कैरेक्टर से बनी स्ट्रिंग में कन्वर्ट करता है: A–Z, a–z, 0–9, +, और /। प्रत्येक 3 इनपुट बाइट्स ठीक 4 Base64 कैरेक्टर से मैप होती हैं। अगर इनपुट की लंबाई 3 का गुणक नहीं है, तो एक या दो = पैडिंग कैरेक्टर जोड़े जाते हैं। एन्कोडेड आउटपुट हमेशा ओरिजिनल से लगभग 33% बड़ा होता है।
Base64 एन्क्रिप्शन नहीं है — यह कोई गोपनीयता प्रदान नहीं करता। इसका उद्देश्य ट्रांसपोर्ट सेफ्टी है: कई प्रोटोकॉल और स्टोरेज सिस्टम 7-bit ASCII टेक्स्ट के लिए डिज़ाइन किए गए थे और मनमाने बाइनरी बाइट्स को सुरक्षित रूप से ले जाने में असमर्थ हैं। Base64 इस अंतर को पाटता है। Python के सामान्य उपयोग मामलों में शामिल हैं: HTTP Basic Auth हेडर, HTML या CSS में इमेज इनलाइन करने के लिए data URI, JWT टोकन सेगमेंट, ईमेल MIME अटैचमेंट, और environment variables या JSON API के माध्यम से बाइनरी ब्लॉब पास करना।
deploy-svc:sk-prod-9f2a1c3e8b4d
ZGVwbG95LXN2Yzpzay1wcm9kLTlmMmExYzNlOGI0ZA==
base64.b64encode() — उदाहरणों के साथ स्टैंडर्ड एन्कोडिंग गाइड
base64.b64encode(s, altchars=None) Python की stdlib में प्राथमिक एन्कोडिंग फंक्शन है। यह base64 मॉड्यूल में रहती है, जो प्रत्येक Python इंस्टॉलेशन के साथ आती है। फंक्शन एक bytes ऑब्जेक्ट स्वीकार करता है और ASCII Base64 रिप्रेजेंटेशन वाला एक bytes ऑब्जेक्ट रिटर्न करता है। इस गाइड में Python 3.x (3.6+) मान लिया गया है।
न्यूनतम कार्यशील उदाहरण
import base64
# HTTP Basic Auth हेडर के लिए API credential pair एन्कोड करना
service_id = "deploy-svc"
api_key = "sk-prod-9f2a1c3e8b4d"
credential_bytes = f"{service_id}:{api_key}".encode("utf-8")
encoded_bytes = base64.b64encode(credential_bytes)
encoded_str = encoded_bytes.decode("ascii") # bytes → str
print(encoded_str)
# ZGVwbG95LXN2Yzpzay1wcm9kLTlmMmExYzNlOGI0ZA==
import urllib.request
req = urllib.request.Request("https://api.internal/v1/deployments")
req.add_header("Authorization", f"Basic {encoded_str}")
# हेडर वैल्यू: Basic ZGVwbG95LXN2Yzpzay1wcm9kLTlmMmExYzNlOGI0ZA==विस्तृत उदाहरण — sort_keys, नेस्टेड ऑब्जेक्ट, राउंड-ट्रिप डिकोड
import base64
import json
# एक environment variable के लिए structured server configuration एन्कोड करना
server_config = {
"host": "db-primary.eu-west-1.internal",
"port": 5432,
"database": "analytics_prod",
"max_connections": 150,
"ssl": {
"mode": "verify-full",
"cert_path": "/etc/ssl/certs/db-client.crt",
"reject_self_signed": True,
},
}
config_json = json.dumps(server_config, sort_keys=True)
encoded_bytes = base64.b64encode(config_json.encode("utf-8"))
encoded_str = encoded_bytes.decode("ascii")
print(encoded_str[:60] + "...")
# eyJkYXRhYmFzZSI6ICJhbmFseXRpY3NfcHJvZCIsICJob3N0IjogImRi...
# डिकोड करें और राउंड-ट्रिप वेरिफाई करें
decoded_json = base64.b64decode(encoded_str).decode("utf-8")
restored = json.loads(decoded_json)
print(restored["host"]) # db-primary.eu-west-1.internal
print(restored["ssl"]["mode"]) # verify-fullb64decode() डिफॉल्ट रूप से उदार है — यह व्हाइटस्पेस और न्यूलाइन सहित अमान्य कैरेक्टर को चुपचाप अनदेखा करता है। validate=True पास करें ताकि किसी भी non-Base64 कैरेक्टर पर binascii.Error raise हो। बाहरी सिस्टम से अविश्वसनीय इनपुट डिकोड करते समय इसका उपयोग करें।Python में Non-ASCII और Unicode स्ट्रिंग एन्कोड करना
Python 3 स्ट्रिंग डिफॉल्ट रूप से Unicode हैं। base64 मॉड्यूल str पर नहीं, bytes पर ऑपरेट करता है — इसलिए पास करने से पहले स्ट्रिंग को bytes में एन्कोड करना जरूरी है। एन्कोडिंग का चुनाव महत्वपूर्ण है: UTF-8 हर Unicode कोड पॉइंट हैंडल करता है और लगभग सभी उपयोग मामलों के लिए सही डिफॉल्ट है।
import base64
# बहुभाषी कंटेंट एन्कोड करना — एक इंटरनेशनल प्लेटफॉर्म से यूजर डिस्प्ले नाम
user_names = [
"राहुल शर्मा", # देवनागरी — Unicode
"田中太郎", # CJK आइडियोग्राफ — UTF-8 में प्रत्येक 3 बाइट
"Мария Соколова", # सिरिलिक — U+041C और उससे ऊपर
"प्रिया पटेल", # देवनागरी — Unicode
]
for name in user_names:
encoded = base64.b64encode(name.encode("utf-8")).decode("ascii")
decoded = base64.b64decode(encoded).decode("utf-8")
print(f"ओरिजिनल : {name}")
print(f"एन्कोडेड : {encoded}")
print(f"राउंड-ट्रिप: {decoded}")
print(f"मिलान : {name == decoded}")
print()
# ओरिजिनल : Мария Соколова
# एन्कोडेड : 0JzQsNGA0LjRjyDQodC+0LrQvtC70L7QstCw
# राउंड-ट्रिप: Мария Соколова
# मिलान : Truebase64 मॉड्यूल — फंक्शन संदर्भ
base64 मॉड्यूल कई एन्कोडिंग फंक्शन एक्सपोज़ करता है। यहाँ उन फंक्शनों का पूरा संदर्भ है जो आप व्यवहार में देखेंगे:
| फंक्शन | इनपुट | रिटर्न | विवरण |
|---|---|---|---|
| b64encode(s, altchars=None) | bytes | bytes | स्टैंडर्ड Base64 (RFC 4648 §4)। altchars + और / कैरेक्टर को दो कस्टम बाइट्स से बदलता है। |
| b64decode(s, altchars=None, validate=False) | bytes | str | bytes | स्टैंडर्ड Base64 डिकोड करता है। validate=True अमान्य इनपुट कैरेक्टर पर binascii.Error raise करता है। |
| urlsafe_b64encode(s) | bytes | bytes | URL-safe Base64 (RFC 4648 §5)। + और / के बजाय - और _ उपयोग करता है। = पैडिंग रखता है। |
| urlsafe_b64decode(s) | bytes | str | bytes | URL-safe Base64 डिकोड करता है। पैडेड और अनपैडेड दोनों इनपुट स्वीकार करता है। |
| encodebytes(s) | bytes | bytes | MIME Base64: हर 76 कैरेक्टर पर \n डालता है और अंत में \n जोड़ता है। केवल email/MIME के लिए। |
| decodebytes(s) | bytes | bytes | MIME Base64 डिकोड करता है। व्हाइटस्पेस और एम्बेडेड न्यूलाइन अनदेखा करता है। |
| b16encode(s) | bytes | bytes | हेक्स एन्कोडिंग (Base16)। प्रत्येक बाइट दो अपरकेस हेक्स कैरेक्टर बनती है। पैडिंग नहीं। |
| b32encode(s) | bytes | bytes | Base32 एन्कोडिंग। A–Z और 2–7 उपयोग करता है। Base64 से बड़ा आउटपुट; TOTP secrets में उपयोग। |
b64encode में altchars पैरामीटर एक 2-byte ऑब्जेक्ट स्वीकार करता है जो + और / कैरेक्टर को बदलता है। altchars=b'-_' पास करना urlsafe_b64encode के समान आउटपुट देता है लेकिन पैडिंग को अलग से नियंत्रित करने देता है।
URL-Safe Base64 — JWT और Query Parameters के लिए urlsafe_b64encode()
स्टैंडर्ड Base64 + और / उपयोग करता है, जो दोनों URL में reserved कैरेक्टर हैं। क्वेरी स्ट्रिंग में + स्पेस के रूप में डिकोड होता है, और / पाथ सेपरेटर है। जब एन्कोडेड वैल्यू URL, फ़ाइलनाम, या cookie में दिखे, तो आपको URL-safe वेरिएंट की जरूरत है: urlsafe_b64encode() + के लिए - और / के लिए _ सब्स्टिट्यूट करता है।
JWT तीनों सेगमेंट (हेडर, पेलोड, सिग्नेचर) के लिए पैडिंग के बिना URL-safe Base64 उपयोग करते हैं। पैडिंग मैन्युअली हटानी होगी — Python की stdlib इसे रखती है।
JWT payload segment एन्कोड करना
import base64
import json
def encode_jwt_segment(data: dict) -> str:
"""dict को बिना पैडिंग के URL-safe Base64 स्ट्रिंग के रूप में एन्कोड करें (JWT फॉर्मेट)।"""
json_bytes = json.dumps(data, separators=(",", ":")).encode("utf-8")
return base64.urlsafe_b64encode(json_bytes).rstrip(b"=").decode("ascii")
def decode_jwt_segment(segment: str) -> dict:
"""URL-safe Base64 JWT segment डिकोड करें (गायब पैडिंग हैंडल करता है)।"""
# पैडिंग वापस जोड़ें: Base64 को लंबाई 4 का गुणक चाहिए
padding = 4 - len(segment) % 4
padded = segment + ("=" * (padding % 4))
raw = base64.urlsafe_b64decode(padded)
return json.loads(raw)
# JWT हेडर और पेलोड बनाएं
header = {"alg": "HS256", "typ": "JWT"}
payload = {
"sub": "usr_7c3a9f1b2d",
"workspace": "ws_eu-west-1-prod",
"role": "data-engineer",
"iat": 1741824000,
"exp": 1741910400,
}
header_segment = encode_jwt_segment(header)
payload_segment = encode_jwt_segment(payload)
print(header_segment)
# eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
print(payload_segment)
# eyJzdWIiOiJ1c3JfN2MzYTlmMWIyZCIsIndvcmtzcGFjZSI6IndzX2...
# राउंड-ट्रिप वेरिफाई करें
restored = decode_jwt_segment(payload_segment)
print(restored["role"]) # data-engineerurlsafe_b64decode() Python 3.x से पैडेड और अनपैडेड दोनों इनपुट स्वीकार करता है, लेकिन केवल तब जब कैरेक्टर URL-safe हों ( - और _)। कभी भी स्टैंडर्ड Base64 स्ट्रिंग ( + या / के साथ) urlsafe_b64decode को पास न करें — मिसमैच कैरेक्टर silent data corruption या binascii.Error का कारण बनेंगे।Python में फाइलें और API रिस्पॉन्स एन्कोड करना
प्रोडक्शन कोड में, Base64 एन्कोडिंग सबसे अधिक ट्रांसमिट की जा रही फाइलों के आसपास और बाइनरी कंटेंट डिलीवर करने वाले बाहरी API के रिस्पॉन्स के आसपास दिखती है। दोनों परिदृश्यों में bytes बाउंड्री की सावधानीपूर्वक हैंडलिंग जरूरी है।
डिस्क से फाइल पढ़कर एन्कोड करना
import base64
import json
from pathlib import Path
def encode_file_to_base64(file_path: str) -> str:
"""बाइनरी फाइल पढ़ें और उसका Base64-एन्कोडेड रिप्रेजेंटेशन रिटर्न करें।"""
try:
raw_bytes = Path(file_path).read_bytes()
return base64.b64encode(raw_bytes).decode("ascii")
except FileNotFoundError:
raise FileNotFoundError(f"फाइल नहीं मिली: {file_path}")
except PermissionError:
raise PermissionError(f"पढ़ने की अनुमति नहीं: {file_path}")
# deployment manifest में TLS सर्टिफिकेट अटैच करें
cert_b64 = encode_file_to_base64("./ssl/service-client.crt")
deployment_manifest = {
"service": "payment-processor",
"environment": "production",
"region": "eu-west-1",
"tls": {
"client_cert": cert_b64,
"cert_format": "base64-pem",
},
}
# manifest लिखें — सर्टिफिकेट सुरक्षित रूप से स्ट्रिंग के रूप में एम्बेड है
with open("./dist/deployment-manifest.json", "w") as f:
json.dump(deployment_manifest, f, indent=2)
print(f"सर्टिफिकेट एन्कोडेड: {len(cert_b64)} कैरेक्टर")डीबगिंग के लिए HTTP API रिस्पॉन्स एन्कोड करना
import base64
import requests # pip install requests
def fetch_and_encode_binary(url: str, headers: dict | None = None) -> str:
"""API से बाइनरी रिसोर्स फेच करें और Base64 के रूप में रिटर्न करें।"""
response = requests.get(url, headers=headers or {}, timeout=10)
response.raise_for_status() # 4xx/5xx के लिए HTTPError raise करता है
content_type = response.headers.get("Content-Type", "unknown")
encoded = base64.b64encode(response.content).decode("ascii")
print(f"Content-Type : {content_type}")
print(f"Raw size : {len(response.content):,} bytes")
print(f"Encoded size : {len(encoded):,} characters")
return encoded
# उदाहरण: internal billing API से signed PDF invoice डाउनलोड करें
invoice_b64 = fetch_and_encode_binary(
"https://billing.internal/api/v2/invoices/INV-2026-0042/pdf",
headers={"Authorization": "Bearer eyJhbGc..."},
)
# notification payload में अटैच करें
notification = {
"recipient_id": "team-finance",
"invoice_id": "INV-2026-0042",
"attachment": {
"filename": "invoice-2026-0042.pdf",
"content": invoice_b64,
"content_type": "application/pdf",
"encoding": "base64",
},
}
print(f"Payload ready: {len(str(notification)):,} characters")Python में Image File को Base64 Encode कैसे करें
इमेज को Base64 में एन्कोड करके data URI के रूप में एम्बेड करना HTML ईमेल टेम्पलेट, PDF जनरेशन, और सेल्फ-कंटेन्ड HTML स्नैपशॉट के लिए स्टैंडर्ड तरीका है। ब्राउज़र एन्कोडेड स्ट्रिंग को सीधे इंटरप्रेट करता है — अलग इमेज रिक्वेस्ट की जरूरत नहीं। यही पैटर्न किसी भी बाइनरी फाइल टाइप के लिए काम करता है: PNG, JPEG, SVG, WebP, या PDF।
import base64
import mimetypes
from pathlib import Path
def image_to_data_uri(image_path: str) -> str:
"""इनलाइन HTML एम्बेडिंग के लिए इमेज फाइल को Base64 data URI में कन्वर्ट करें।"""
path = Path(image_path)
mime_type = mimetypes.guess_type(image_path)[0] or "image/octet-stream"
raw_bytes = path.read_bytes()
encoded = base64.b64encode(raw_bytes).decode("ascii")
return f"data:{mime_type};base64,{encoded}"
# HTML ईमेल टेम्पलेट में प्रोडक्ट इमेज इनलाइन एम्बेड करें
hero_uri = image_to_data_uri("./assets/product-hero-768px.png")
thumbnail_uri = image_to_data_uri("./assets/product-thumb-128px.webp")
html_fragment = f"""
<img src="{hero_uri}"
alt="प्रोडक्ट हीरो"
width="768" height="432"
style="display:block;max-width:100%" />
"""
print(f"PNG data URI शुरू होती है: {hero_uri[:60]}...")
# data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAwAAAAA...data:image/svg+xml,{encoded}) अक्सर Base64 से छोटी होती है क्योंकि SVG टेक्स्ट-बेस्ड है और Base64 साइज़ ~33% बढ़ाता है। रास्टर फॉर्मेट (PNG, JPEG, WebP) के लिए Base64 और SVG के लिए URL-encoding उपयोग करें।बड़ी फाइलों के साथ काम करना — Chunked Base64 Encoding
Path.read_bytes() से पूरी फाइल मेमोरी में लोड करना ~50 MB तक की फाइलों के लिए ठीक है। उस थ्रेशोल्ड से ऊपर, peak मेमोरी उपयोग महत्वपूर्ण हो जाता है — एक 200 MB फाइल raw bytes के लिए ~200 MB और Base64 आउटपुट के लिए ~267 MB चाहती है, एक प्रोसेस में कुल ~467 MB। बड़ी फाइलों के लिए, chunks में पढ़ें और एन्कोड करें।
महत्वपूर्ण बाधा: chunk साइज़ 3 bytes का गुणक होनी चाहिए। Base64 3 इनपुट bytes को ठीक 4 आउटपुट कैरेक्टर में एन्कोड करता है। अगर chunk बाउंड्री 3 के गैर-गुणक पर पड़े, तो एनकोडर स्ट्रीम के बीच में = पैडिंग जोड़ देता है, जिससे concatenated आउटपुट अमान्य हो जाता है।
फाइल में streaming encode (पूरी फाइल मेमोरी लोड के बिना)
import base64
from pathlib import Path
CHUNK_SIZE = 3 * 1024 * 256 # 786,432 bytes — 3 का गुणक, ~768 KB प्रति chunk
def encode_large_file(input_path: str, output_path: str) -> int:
"""
बड़ी बाइनरी फाइल को पूरी तरह मेमोरी में लोड किए बिना Base64 में एन्कोड करें।
लिखे गए Base64 कैरेक्टर की संख्या रिटर्न करता है।
"""
total_chars = 0
with open(input_path, "rb") as src, open(output_path, "w") as dst:
while True:
chunk = src.read(CHUNK_SIZE)
if not chunk:
break
encoded_chunk = base64.b64encode(chunk).decode("ascii")
dst.write(encoded_chunk)
total_chars += len(encoded_chunk)
return total_chars
# asset delivery manifest के लिए 300 MB प्रोडक्ट वीडियो एन्कोड करें
chars_written = encode_large_file(
"./uploads/product-demo-4k.mp4",
"./dist/product-demo-4k.b64",
)
print(f"एन्कोडेड: {chars_written:,} Base64 characters")
# एन्कोडेड: 407,374,184 Base64 charactersबाइनरी एसेट डायरेक्टरी एन्कोड करना (NDJSON आउटपुट)
import base64
import json
from pathlib import Path
def encode_assets_to_ndjson(asset_dir: str, output_path: str) -> int:
"""
डायरेक्टरी की सभी बाइनरी फाइलें NDJSON manifest में एन्कोड करें।
प्रत्येक लाइन एक JSON ऑब्जेक्ट है: {"path": "...", "mime": "...", "data": "<base64>"}
प्रोसेस की गई फाइलों की संख्या रिटर्न करता है।
"""
import mimetypes
asset_path = Path(asset_dir)
count = 0
with open(output_path, "w") as out:
for file_path in sorted(asset_path.rglob("*")):
if not file_path.is_file():
continue
mime = mimetypes.guess_type(str(file_path))[0] or "application/octet-stream"
encoded = base64.b64encode(file_path.read_bytes()).decode("ascii")
record = {"path": str(file_path.relative_to(asset_path)), "mime": mime, "data": encoded}
out.write(json.dumps(record) + "\n")
count += 1
return count
processed = encode_assets_to_ndjson("./dist/static/", "./dist/asset-bundle.ndjson")
print(f"{processed} फाइलें NDJSON asset bundle में एन्कोड की गईं")read_bytes() से chunked reading में तब स्विच करें जब इनपुट फाइल ~50–100 MB से अधिक हो, या जब आपकी सर्विस एक साथ कई फाइलें प्रोसेस करती हो और मेमोरी प्रेशर चिंता का विषय बन जाए। 50 MB से कम फाइलों के लिए, सरल one-liner b64encode(path.read_bytes()).decode() तेज़ और समझने में आसान है।Python के साथ Command-Line Base64 Encoding
Python base64 मॉड्यूल के लिए एक CLI इंटरफेस शिप करता है — कोई अतिरिक्त टूल्स की जरूरत नहीं। यह क्रॉस-प्लेटफॉर्म काम करता है, जो इसे CI pipelines और Windows environments में उपयोगी बनाता है जहाँ सिस्टमbase64 कमांड उपलब्ध न हो।
# ── python -m base64 ─────────────────────────────────────────────────── # स्ट्रिंग एन्कोड करें (stdin से पाइप) echo -n "deploy-svc:sk-prod-9f2a1c3e8b4d" | python3 -m base64 # ZGVwbG95LXN2Yzpzay1wcm9kLTlmMmExYzNlOGI0ZA== # फाइल एन्कोड करें python3 -m base64 ./ssl/service-client.crt # Base64 स्ट्रिंग डिकोड करें echo "ZGVwbG95LXN2Yzpzay1wcm9kLTlmMmExYzNlOGI0ZA==" | python3 -m base64 -d # Base64 फाइल वापस बाइनरी में डिकोड करें python3 -m base64 -d ./dist/service-client.b64 > ./restored.crt # ── Python one-liner — क्रॉस-प्लेटफॉर्म, Windows पर काम करता है ──────── # स्ट्रिंग एन्कोड करें python3 -c "import base64,sys; print(base64.b64encode(sys.argv[1].encode()).decode())" "my-secret" # bXktc2VjcmV0 # URL-safe encode (बिना पैडिंग) python3 -c "import base64,sys; print(base64.urlsafe_b64encode(sys.argv[1].encode()).rstrip(b'=').decode())" "my-secret" # bXktc2VjcmV0 # फाइल inline एन्कोड करें (stdout पर रिजल्ट) python3 -c "import base64,sys; print(base64.b64encode(open(sys.argv[1],'rb').read()).decode())" ./config.json
base64 कमांड के विपरीत, python -m base64 डिफॉल्ट रूप से 76 कैरेक्टर पर आउटपुट wrap नहीं करता। आउटपुट एकल unbroken लाइन है, जो environment variables, JSON fields, और HTTP headers के लिए वांछित है। किसी भी OS पर सिस्टम base64 के ड्रॉप-इन के रूप में उपयोग करें।हाई-परफॉर्मेंस विकल्प: pybase64
Python का stdlib base64 मॉड्यूल pure Python में इम्प्लीमेंट है (CPython में thin C layer के साथ)। बड़े payloads को हाई थ्रूपुट पर एन्कोड करने वाली सर्विसेज के लिए — image processing pipelines, bulk export jobs, real-time telemetry ingestion — pybase64 एक ड्रॉप-इन रिप्लेसमेंट है जो SIMD-accelerated C library libbase64 द्वारा समर्थित है। Benchmarks payload size और CPU architecture के आधार पर 2–10× थ्रूपुट सुधार दिखाते हैं।
pip install pybase64
import pybase64
import time
# pybase64 ड्रॉप-इन रिप्लेसमेंट है — stdlib के समान फंक्शन signatures
sample_payload = b"x" * (1024 * 1024) # 1 MB बाइनरी डेटा
# स्टैंडर्ड एन्कोडिंग — base64.b64encode() के समान आउटपुट
encoded = pybase64.b64encode(sample_payload)
decoded = pybase64.b64decode(encoded)
assert decoded == sample_payload
# URL-safe एन्कोडिंग — base64.urlsafe_b64encode() के समान आउटपुट
url_safe = pybase64.urlsafe_b64encode(sample_payload)
# b64encode_as_string() सीधे str रिटर्न करता है — .decode() कॉल की जरूरत नहीं
telemetry_event = b'{"event":"page_view","session_id":"sess_3a7f91c2","ts":1741824000}'
encoded_str: str = pybase64.b64encode_as_string(telemetry_event)
print(encoded_str[:48] + "...")
# eyJldmVudCI6InBhZ2VfdmlldyIsInNlc3Npb25faWQi...
# थ्रूपुट तुलना (अनुमानित, hardware के अनुसार भिन्न)
# stdlib base64.b64encode(1 MB): ~80 MB/s
# pybase64.b64encode(1 MB): ~800 MB/s (AVX2 CPU पर SIMD path)pybase64 पर तब switch करें जब profiling Base64 encoding को bottleneck दिखाए, या जब आप ~100 KB से अधिक payloads बार-बार एन्कोड करें। छोटी strings (credentials, tokens) के one-off encoding के लिए, stdlib काफी तेज है और कोई install dependency नहीं है।
Syntax Highlighting के साथ Terminal Output
टर्मिनल में Base64-encoded payloads डीबग करते समय — विशेष रूप से JSON configs या JWT contents — rich library syntax-highlighted, indented आउटपुट देती है जो raw dump से पढ़ने में कहीं आसान है। CLI tools, debugging scripts, और REPL sessions में विशेष रूप से उपयोगी है।
pip install rich
import base64
import json
from rich import print as rprint
from rich.syntax import Syntax
from rich.console import Console
console = Console()
def decode_and_pretty_print(encoded: str, label: str = "Decoded payload") -> None:
"""Base64 स्ट्रिंग डिकोड करें, JSON के रूप में parse करें, और syntax highlighting के साथ प्रिंट करें।"""
raw_bytes = base64.b64decode(encoded + "==") # tolerant padding
try:
parsed = json.loads(raw_bytes)
pretty = json.dumps(parsed, indent=2, ensure_ascii=False)
syntax = Syntax(pretty, "json", theme="monokai", line_numbers=False)
console.rule(f"[bold blue]{label}")
console.print(syntax)
except json.JSONDecodeError:
# JSON नहीं — raw text प्रिंट करें
console.rule(f"[bold yellow]{label} (raw text)")
rprint(raw_bytes.decode("utf-8", errors="replace"))
# असफल authentication request से JWT payload segment inspect करें
jwt_payload_segment = "eyJzdWIiOiJ1c3JfN2MzYTlmMWIyZCIsInJvbGUiOiJkYXRhLWVuZ2luZWVyIiwiZXhwIjoxNzQxOTEwNDAwfQ"
decode_and_pretty_print(jwt_payload_segment, "JWT Payload")rich आउटपुट केवल terminal display के लिए उपयोग करें — debugging, stdout पर logging, या interactive CLI tools के लिए। इसे कभी भी फाइलों में Base64 आउटपुट लिखने, API endpoints से रिटर्न करने, या environment variables में स्टोर करने के लिए उपयोग न करें, क्योंकि rich ANSI escape codes जोड़ता है जो data corrupt करते हैं।सामान्य गलतियाँ
मैंने Base64 encoding वाले बहुत से Python codebase review किए हैं, और ये चार गलतियाँ लगातार दिखती हैं — अक्सर तब तक अनदेखी रहती हैं जब तक non-ASCII इनपुट या बाइनरी फाइल प्रोडक्शन में encoding path से न गुज़रे।
गलती 1 — b64encode() को bytes के बजाय str पास करना
समस्या: b64encode() एक bytes ऑब्जेक्ट की उम्मीद करता है। str पास करने पर तुरंत TypeError: a bytes-like object is required raise होता है। समाधान: एन्कोड करने से पहले स्ट्रिंग पर हमेशा .encode("utf-8") कॉल करें।
import base64 # ❌ TypeError: a bytes-like object is required, not 'str' webhook_secret = "wh-secret-a3f91c2b4d" encoded = base64.b64encode(webhook_secret) # crash होता है
import base64
# ✅ पहले str को bytes में encode करें
webhook_secret = "wh-secret-a3f91c2b4d"
encoded = base64.b64encode(webhook_secret.encode("utf-8"))
# b'd2gtc2VjcmV0LWEzZjkxYzJiNGQ='गलती 2 — bytes रिजल्ट पर .decode() कॉल करना भूलना
समस्या: b64encode() str नहीं, bytes रिटर्न करता है। इसे सीधे f-string में एम्बेड करने पर आउटपुट में b'...' बनता है, जो अमान्य HTTP header value है और JSON serialisation तोड़ता है। समाधान: encoded result पर हमेशा .decode("ascii") कॉल करें।
import base64
credential = base64.b64encode(b"svc-monitor:sk-7f3a1b")
# ❌ Authorization header में "b'c3ZjLW1vbml0b3I6c2stN2YzYTFi'" है
headers = {"Authorization": f"Basic {credential}"}import base64
credential = base64.b64encode(b"svc-monitor:sk-7f3a1b").decode("ascii")
# ✅ Authorization: Basic c3ZjLW1vbml0b3I6c2stN2YzYTFi
headers = {"Authorization": f"Basic {credential}"}गलती 3 — जहाँ b64encode() चाहिए वहाँ encodebytes() उपयोग करना
समस्या: encodebytes() हर 76 कैरेक्टर पर \n डालता है (MIME line-wrapping) और अंत में trailing newline जोड़ता है। इसे JSON field, environment variable, या data URI में स्टोर करने पर literal newline characters embed होते हैं जो downstream value corrupt करते हैं। समाधान: MIME email composition छोड़कर हर जगह b64encode() उपयोग करें।
import base64, json
cert_bytes = open("./ssl/root-ca.crt", "rb").read()
# ❌ encodebytes() हर 76 chars पर \n जोड़ता है — JSON और env vars तोड़ता है
cert_b64 = base64.encodebytes(cert_bytes).decode()
config = json.dumps({"ca_cert": cert_b64}) # string value के अंदर newlinesimport base64, json
from pathlib import Path
cert_bytes = Path("./ssl/root-ca.crt").read_bytes()
# ✅ b64encode() एकल unbroken string produce करता है
cert_b64 = base64.b64encode(cert_bytes).decode("ascii")
config = json.dumps({"ca_cert": cert_b64}) # clean single-line valueगलती 4 — URL-safe Base64 को स्टैंडर्ड decoder से डिकोड करना
समस्या: URL-safe Base64 + और / के बजाय - और _ उपयोग करता है। URL-safe स्ट्रिंग को b64decode() को पास करने पर उन कैरेक्टर वाले किसी भी segment के लिए चुपचाप गलत bytes मिलती हैं — डिफॉल्ट रूप से कोई exception raise नहीं होता। समाधान: URL-safe इनपुट के लिए urlsafe_b64decode() उपयोग करें, या mismatch जल्दी detect करने के लिए validate=True पास करें।
import base64 # ❌ JWT payload segment URL-safe Base64 उपयोग करता है (- और _) # b64decode() उन characters के लिए चुपचाप गलत bytes produce करता है jwt_segment = "eyJzdWIiOiJ1c3JfN2MzYTlmMWIyZCIsInJvbGUiOiJhZG1pbiJ9" wrong = base64.b64decode(jwt_segment) # - या _ मौजूद हो तो silently wrong
import base64
# ✅ JWT और URL-safe input के लिए urlsafe_b64decode() उपयोग करें
jwt_segment = "eyJzdWIiOiJ1c3JfN2MzYTlmMWIyZCIsInJvbGUiOiJhZG1pbiJ9"
padding = 4 - len(jwt_segment) % 4
raw = base64.urlsafe_b64decode(jwt_segment + "=" * (padding % 4))
# b'{"sub":"usr_7c3a9f1b2d","role":"admin"}'Python Base64 Methods — त्वरित तुलना
| मेथड | इनपुट प्रकार | URL-safe वर्ण | पैडिंग | लाइन ब्रेक | रिटर्न प्रकार | इंस्टॉल आवश्यक |
|---|---|---|---|---|---|---|
| b64encode() | bytes, bytearray, memoryview | ❌ + और / | ✅ = padding | ❌ कोई नहीं | bytes | नहीं |
| urlsafe_b64encode() | bytes, bytearray, memoryview | ✅ - और _ | ✅ = padding | ❌ कोई नहीं | bytes | नहीं |
| b64encode(altchars=b"-_") | bytes, bytearray, memoryview | ✅ custom 2 chars | ✅ = padding | ❌ कोई नहीं | bytes | नहीं |
| encodebytes() | bytes, bytearray, memoryview | ❌ + और / | ✅ = padding | ✅ \n हर 76 chars पर | bytes | नहीं |
| pybase64.b64encode() | bytes, bytearray, memoryview | ❌ + और / | ✅ = padding | ❌ कोई नहीं | bytes | pip install |
| pybase64.b64encode_as_string() | bytes, bytearray, memoryview | ❌ + और / | ✅ = padding | ❌ कोई नहीं | str | pip install |
अधिकांश उपयोग मामलों के लिए b64encode() चुनें: HTTP headers, JSON fields, environment variables, और data URIs। जब भी output URL, filename, cookie, या JWT segment में दिखे तो urlsafe_b64encode() पर switch करें। encodebytes() केवल MIME email attachments compose करते समय उपयोग करें — line-wrapping MIME specification द्वारा required है लेकिन बाकी सब चुपचाप तोड़ देगा। ~100 KB से अधिक payloads को hot path में encode करते समय pybase64 की ओर रुखें।
अक्सर पूछे जाने वाले प्रश्न
संबंधित टूल
बिना कोई Python लिखे one-click encode या decode के लिए, अपनी string या file सीधे Base64 एनकोडर में paste करें — यह आपके browser में बिना किसी setup के standard और URL-safe दोनों modes तुरंत handle करता है।
Maria is a backend developer specialising in Python and API integration. She has broad experience with data pipelines, serialisation formats, and building reliable server-side services. She is an active member of the Python community and enjoys writing practical, example-driven guides that help developers solve real problems without unnecessary theory.
Priya is a data scientist and machine learning engineer who has worked across the full Python data stack — from raw data ingestion and cleaning to model deployment and monitoring. She is passionate about reproducible research, Jupyter-based workflows, and the practical engineering side of ML. She writes about NumPy, Pandas, data serialisation, and the Python patterns that make data pipelines reliable at scale.