Skip to content

Instantly share code, notes, and snippets.

@rane-hs
Last active May 8, 2018 04:05
Show Gist options
  • Save rane-hs/40b36be270797fe23480885341121d85 to your computer and use it in GitHub Desktop.
Save rane-hs/40b36be270797fe23480885341121d85 to your computer and use it in GitHub Desktop.
python3 choose_boundary
import os
# Utility functions
# -----------------
try:
import _thread
except ImportError:
import _dummy_thread as _thread
_counter_lock = _thread.allocate_lock()
_counter = 0
def _get_next_counter():
global _counter
_counter_lock.acquire()
_counter += 1
result = _counter
_counter_lock.release()
return result
def choose_boundary(_prefix=None):
"""Return a string usable as a multipart boundary.
The string chosen is unique within a single program run, and
incorporates the user id (if available), process id (if available),
and current time. So it's very unlikely the returned string appears
in message text, but there's no guarantee.
The boundary contains dots so you have to quote it in the header."""
import time
if _prefix is None:
import socket
try:
hostid = socket.gethostbyname(socket.gethostname())
except socket.gaierror:
hostid = '127.0.0.1'
try:
uid = repr(os.getuid())
except AttributeError:
uid = '1'
try:
pid = repr(os.getpid())
except AttributeError:
pid = '1'
_prefix = hostid + '.' + uid + '.' + pid
return "%s.%.3f.%d" % (_prefix, time.time(), _get_next_counter())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment