convenience function rethinstuff.utcnow()

This commit is contained in:
Noah Levitt 2015-11-17 20:06:51 +00:00
parent 79b3895da3
commit 447f23615f
3 changed files with 25 additions and 3 deletions

View File

@ -6,6 +6,14 @@ import time
import types
import socket
import os
import datetime
def utcnow():
"""Convenience function to get timezone-aware UTC datetime. RethinkDB
requires timezone-aware datetime for its native time type, and
unfortunately datetime.datetime.utcnow() is not timezone-aware. Also python
2 doesn't come with a timezone implementation."""
return datetime.datetime.now(r.make_timezone("00:00"))
class RethinkerWrapper(object):
logger = logging.getLogger('rethinkstuff.RethinkerWrapper')
@ -144,13 +152,13 @@ class ServiceRegistry(object):
if not 'pid' in status_info:
status_info['pid'] = os.getpid()
result = self.r.table('services').insert(status_info, conflict='replace', return_changes=True).run()
# XXX check
# XXX check
return result['changes'][0]['new_val']
def unregister(self, id):
result = self.r.table('services').get(id).delete().run()
if result != {'deleted':1,'errors':0,'inserted':0,'replaced':0,'skipped':0,'unchanged':0}:
self.logger.warn('unexpected result attempting to delete id=%s from rethinkdb services table: %s', id, result)
self.logger.warn('unexpected result attempting to delete id=%s from rethinkdb services table: %s', id, result)
def available_service(self, role):
try:
@ -169,3 +177,4 @@ class ServiceRegistry(object):
return result
except r.ReqlNonExistenceError:
return []

View File

@ -2,7 +2,7 @@ import setuptools
setuptools.setup(
name='rethinkstuff',
version='0.1.2',
version='0.1.3',
packages=['rethinkstuff'],
classifiers=[
'Programming Language :: Python :: 2.7',

View File

@ -8,6 +8,7 @@ import rethinkdb
import time
import socket
import os
import datetime
logging.basicConfig(stream=sys.stderr, level=logging.INFO,
format="%(asctime)s %(process)d %(levelname)s %(threadName)s %(name)s.%(funcName)s(%(filename)s:%(lineno)d) %(message)s")
@ -164,3 +165,15 @@ def test_service_registry(r):
svc0 = svcreg.heartbeat(svc0)
svc1 = svcreg.heartbeat(svc1)
assert len(svcreg.available_services("yes-such-role")) == 2
def test_utcnow(r):
now_notz = datetime.datetime.utcnow() # has no timezone :(
assert not now_notz.tzinfo
now_tz = r.utcnow() # solution to that problem
assert now_tz.tzinfo
assert now_tz.tzinfo.delta == datetime.timedelta(0)
# XXX should really run this test in non-utc timezone environment
assert now_tz.timestamp() - now_notz.timestamp() < 0.1