Miscellaneous utilities

coaster.utils.misc.base_domain_matches(d1, d2)[source]

Check if two domains have the same base domain, using the Public Suffix List.

>>> base_domain_matches('https://hasjob.co', 'hasjob.co')
True
>>> base_domain_matches('hasgeek.hasjob.co', 'hasjob.co')
True
>>> base_domain_matches('hasgeek.com', 'hasjob.co')
False
>>> base_domain_matches('static.hasgeek.co.in', 'hasgeek.com')
False
>>> base_domain_matches('static.hasgeek.co.in', 'hasgeek.co.in')
True
>>> base_domain_matches('example@example.com', 'example.com')
True
coaster.utils.misc.buid()[source]

Return a new random id that is exactly 22 characters long, by encoding a UUID4 in URL-safe Base64. See http://en.wikipedia.org/wiki/Base64#Variants_summary_table

>>> len(buid())
22
>>> buid() == buid()
False
>>> isinstance(buid(), six.text_type)
True
coaster.utils.misc.buid2uuid(value)[source]

Convert a 22-char BUID string to a UUID object

>>> b = u'MyA90vLvQi-usAWNb19wiQ'
>>> buid2uuid(b)
UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089')
coaster.utils.misc.check_password(reference, attempt)[source]

Compare a reference password with the user attempt.

>>> check_password('{PLAIN}foo', 'foo')
True
>>> check_password(u'{PLAIN}bar', 'bar')
True
>>> check_password(u'{UNKNOWN}baz', 'baz')
False
>>> check_password(u'no-encoding', u'no-encoding')
False
>>> check_password(u'{SSHA}q/uVU8r15k/9QhRi92CWUwMJu2DM6TUSpp25', u're-foo')
True
>>> check_password(u'{BCRYPT}$2b$12$NfKivgz7njR3/rWZ56EsDe7..PPum.fcmFLbdkbP.chtMTcS1s01C', 'foo')
True
coaster.utils.misc.domain_namespace_match(domain, namespace)[source]

Checks if namespace is related to the domain because the base domain matches.

>>> domain_namespace_match('hasgeek.com', 'com.hasgeek')
True
>>> domain_namespace_match('funnel.hasgeek.com', 'com.hasgeek.funnel')
True
>>> domain_namespace_match('app.hasgeek.com', 'com.hasgeek.peopleflow')
True
>>> domain_namespace_match('app.hasgeek.in', 'com.hasgeek.peopleflow')
False
>>> domain_namespace_match('peopleflow.local', 'local.peopleflow')
True
coaster.utils.misc.format_currency(value, decimals=2)[source]

Return a number suitably formatted for display as currency, with thousands separated by commas and up to two decimal points.

>>> format_currency(1000)
'1,000'
>>> format_currency(100)
'100'
>>> format_currency(999.95)
'999.95'
>>> format_currency(99.95)
'99.95'
>>> format_currency(100000)
'100,000'
>>> format_currency(1000.00)
'1,000'
>>> format_currency(1000.41)
'1,000.41'
>>> format_currency(23.21, decimals=3)
'23.210'
>>> format_currency(1000, decimals=3)
'1,000'
>>> format_currency(123456789.123456789)
'123,456,789.12'
coaster.utils.misc.get_email_domain(emailaddr)[source]

Return the domain component of an email address. Returns None if the provided string cannot be parsed as an email address.

>>> get_email_domain('test@example.com')
'example.com'
>>> get_email_domain('test+trailing@example.com')
'example.com'
>>> get_email_domain('Example Address <test@example.com>')
'example.com'
>>> get_email_domain('foobar')
>>> get_email_domain('foo@bar@baz')
'bar'
>>> get_email_domain('foobar@')
>>> get_email_domain('@foobar')
coaster.utils.misc.getbool(value)[source]

Returns a boolean from any of a range of values. Returns None for unrecognized values. Numbers other than 0 and 1 are considered unrecognized.

>>> getbool(True)
True
>>> getbool(1)
True
>>> getbool('1')
True
>>> getbool('t')
True
>>> getbool(2)
>>> getbool(0)
False
>>> getbool(False)
False
>>> getbool('n')
False
coaster.utils.misc.is_collection(item)[source]

Returns True if the item is a collection class: list, tuple, set, frozenset or any other class that resembles one of these (using abstract base classes).

>>> is_collection(0)
False
>>> is_collection(0.1)
False
>>> is_collection('')
False
>>> is_collection({})
False
>>> is_collection({}.keys())
True
>>> is_collection([])
True
>>> is_collection(())
True
>>> is_collection(set())
True
>>> is_collection(frozenset())
True
>>> from coaster.utils import InspectableSet
>>> is_collection(InspectableSet({1, 2}))
True
coaster.utils.misc.isoweek_datetime(year, week, timezone='UTC', naive=False)[source]

Returns a datetime matching the starting point of a specified ISO week in the specified timezone (default UTC). Returns a naive datetime in UTC if requested (default False).

>>> isoweek_datetime(2017, 1)
datetime.datetime(2017, 1, 2, 0, 0, tzinfo=<UTC>)
>>> isoweek_datetime(2017, 1, 'Asia/Kolkata')
datetime.datetime(2017, 1, 1, 18, 30, tzinfo=<UTC>)
>>> isoweek_datetime(2017, 1, 'Asia/Kolkata', naive=True)
datetime.datetime(2017, 1, 1, 18, 30)
>>> isoweek_datetime(2008, 1, 'Asia/Kolkata')
datetime.datetime(2007, 12, 30, 18, 30, tzinfo=<UTC>)
coaster.utils.misc.make_name(text, delim=u'-', maxlength=50, checkused=None, counter=2)[source]

Generate an ASCII name slug. If a checkused filter is provided, it will be called with the candidate. If it returns True, make_name will add counter numbers starting from 2 until a suitable candidate is found.

Parameters:
  • delim (string) – Delimiter between words, default ‘-‘
  • maxlength (int) – Maximum length of name, default 50
  • checkused – Function to check if a generated name is available for use
  • counter (int) – Starting position for name counter
>>> make_name('This is a title')
'this-is-a-title'
>>> make_name('Invalid URL/slug here')
'invalid-url-slug-here'
>>> make_name('this.that')
'this-that'
>>> make_name('this:that')
'this-that'
>>> make_name("How 'bout this?")
'how-bout-this'
>>> make_name(u"How’s that?")
'hows-that'
>>> make_name(u'K & D')
'k-d'
>>> make_name('billion+ pageviews')
'billion-pageviews'
>>> make_name(u'हिन्दी slug!')
'hindii-slug'
>>> make_name(u'__name__', delim=u'_')
'name'
>>> make_name(u'how_about_this', delim=u'_')
'how_about_this'
>>> make_name(u'and-that', delim=u'_')
'and_that'
>>> make_name(u'Umlauts in Mötörhead')
'umlauts-in-motorhead'
>>> make_name('Candidate', checkused=lambda c: c in ['candidate'])
'candidate2'
>>> make_name('Candidate', checkused=lambda c: c in ['candidate'], counter=1)
'candidate1'
>>> make_name('Candidate', checkused=lambda c: c in ['candidate', 'candidate1', 'candidate2'], counter=1)
'candidate3'
>>> make_name('Long title, but snipped', maxlength=20)
'long-title-but-snipp'
>>> len(make_name('Long title, but snipped', maxlength=20))
20
>>> make_name('Long candidate', maxlength=10, checkused=lambda c: c in ['long-candi', 'long-cand1'])
'long-cand2'
>>> make_name(u'Lǝnkǝran')
'lankaran'
>>> make_name(u'example@example.com')
'example-example-com'
>>> make_name('trailing-delimiter', maxlength=10)
'trailing-d'
>>> make_name('trailing-delimiter', maxlength=9)
'trailing'
>>> make_name('''test this
... newline''')
'test-this-newline'
>>> make_name(u"testing an emoji😁")
u'testing-an-emoji'
>>> make_name('''testing\t\nmore\r\nslashes''')
'testing-more-slashes'
>>> make_name('What if a HTML <tag/>')
'what-if-a-html-tag'
>>> make_name('These are equivalent to  through ')
'these-are-equivalent-to-through'
coaster.utils.misc.make_password(password, encoding='BCRYPT')[source]

Make a password with PLAIN, SSHA or BCRYPT (default) encoding.

>>> make_password('foo', encoding='PLAIN')
'{PLAIN}foo'
>>> make_password(u're-foo', encoding='SSHA')[:6]
'{SSHA}'
>>> make_password(u're-foo')[:8]
'{BCRYPT}'
>>> make_password('foo') == make_password('foo')
False
coaster.utils.misc.md5sum(data)[source]

Return md5sum of data as a 32-character string.

>>> md5sum('random text')
'd9b9bec3f4cc5482e7c5ef43143e563a'
>>> md5sum(u'random text')
'd9b9bec3f4cc5482e7c5ef43143e563a'
>>> len(md5sum('random text'))
32
coaster.utils.misc.midnight_to_utc(dt, timezone=None, naive=False)[source]

Returns a UTC datetime matching the midnight for the given date or datetime.

>>> from datetime import date
>>> midnight_to_utc(datetime(2017, 1, 1))
datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>)
>>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1)))
datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>)
>>> midnight_to_utc(datetime(2017, 1, 1), naive=True)
datetime.datetime(2017, 1, 1, 0, 0)
>>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1)), naive=True)
datetime.datetime(2016, 12, 31, 18, 30)
>>> midnight_to_utc(date(2017, 1, 1))
datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>)
>>> midnight_to_utc(date(2017, 1, 1), naive=True)
datetime.datetime(2017, 1, 1, 0, 0)
>>> midnight_to_utc(date(2017, 1, 1), timezone='Asia/Kolkata')
datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>)
>>> midnight_to_utc(datetime(2017, 1, 1), timezone='Asia/Kolkata')
datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>)
>>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1)), timezone='UTC')
datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>)
coaster.utils.misc.namespace_from_url(url)[source]

Construct a dotted namespace string from a URL.

coaster.utils.misc.newpin(digits=4)[source]

Return a random numeric string with the specified number of digits, default 4.

>>> len(newpin())
4
>>> len(newpin(5))
5
>>> newpin().isdigit()
True
coaster.utils.misc.newsecret()[source]

Make a secret key for email confirmation and all that stuff. 44 characters long.

>>> len(newsecret())
44
>>> newsecret() == newsecret()
False
coaster.utils.misc.nullint(value)[source]

Return int(value) if bool(value) is not False. Return None otherwise. Useful for coercing optional values to an integer.

>>> nullint('10')
10
>>> nullint('') is None
True
coaster.utils.misc.nullstr(value)[source]

Return unicode(value) if bool(value) is not False. Return None otherwise. Useful for coercing optional values to a string.

>>> nullstr(10) == '10'
True
>>> nullstr('') is None
True
coaster.utils.misc.nullunicode(value)

Return unicode(value) if bool(value) is not False. Return None otherwise. Useful for coercing optional values to a string.

>>> nullstr(10) == '10'
True
>>> nullstr('') is None
True
coaster.utils.misc.require_one_of(_return=False, **kwargs)[source]

Validator that raises TypeError unless one and only one parameter is not None. Use this inside functions that take multiple parameters, but allow only one of them to be specified:

def my_func(this=None, that=None, other=None):
    # Require one and only one of `this` or `that`
    require_one_of(this=this, that=that)

    # If we need to know which parameter was passed in:
    param, value = require_one_of(True, this=this, that=that)

    # Carry on with function logic
    pass
Parameters:
  • _return – Return the matching parameter
  • kwargs – Parameters, of which one and only one is mandatory
Returns:

If _return, matching parameter name and value

Return type:

tuple

Raises:

TypeError – If the count of parameters that aren’t None is not 1

coaster.utils.misc.sorted_timezones()[source]

Return a list of timezones sorted by offset from UTC.

coaster.utils.misc.unicode_http_header(value)[source]

Convert an ASCII HTTP header string into a unicode string with the appropriate encoding applied. Expects headers to be RFC 2047 compliant.

>>> unicode_http_header('=?iso-8859-1?q?p=F6stal?=') == u'pöstal'
True
>>> unicode_http_header(b'=?iso-8859-1?q?p=F6stal?=') == u'pöstal'
True
>>> unicode_http_header('pöstal') == u'pöstal'
True
coaster.utils.misc.uuid1mc()[source]

Return a UUID1 with a random multicast MAC id

coaster.utils.misc.uuid1mc_from_datetime(dt)[source]

Return a UUID1 with a random multicast MAC id and with a timestamp matching the given datetime object or timestamp value.

Warning

This function does not consider the timezone, and is not guaranteed to return a unique UUID. Use under controlled conditions only.

>>> dt = datetime.now()
>>> u1 = uuid1mc()
>>> u2 = uuid1mc_from_datetime(dt)
>>> # Both timestamps should be very close to each other but not an exact match
>>> u1.time > u2.time
True
>>> u1.time - u2.time < 5000
True
>>> d2 = datetime.fromtimestamp((u2.time - 0x01b21dd213814000) * 100 / 1e9)
>>> d2 == dt
True
coaster.utils.misc.uuid2buid(value)[source]

Convert a UUID object to a 22-char BUID string

>>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089')
>>> uuid2buid(u)
'MyA90vLvQi-usAWNb19wiQ'
coaster.utils.misc.valid_username(candidate)[source]

Check if a username is valid.

>>> valid_username('example person')
False
>>> valid_username('example_person')
False
>>> valid_username('exampleperson')
True
>>> valid_username('example-person')
True
>>> valid_username('a')
True
>>> valid_username('a-') or valid_username('ab-') or valid_username('-a') or valid_username('-ab')
False