def test_nodb_cache(self): nodb = NoDB('dummy') nodb.index = "Name" nodb.cache = True jeff = {"Name": "Jeff", "age": 19} serialized = nodb._serialize(jeff) real_index = nodb._format_index_value("Jeff") base_cache_path = os.path.join(tempfile.gettempdir(), '.nodb') if not os.path.isdir(base_cache_path): os.makedirs(base_cache_path) cache_path = os.path.join(base_cache_path, real_index) if not os.path.exists(cache_path): f = open(cache_path, 'a') f.close() with open(cache_path, "wb") as in_file: in_file.write(serialized.encode(NoDB.encoding)) nodb.load("Jeff") loaded = nodb.load("Jeff", default={}) self.assertEqual(loaded, jeff) loaded = nodb.load("Jeff", default="Booty") self.assertEqual(loaded, jeff) bcp = nodb._get_base_cache_path()
class User(object): email = None name = None def __init__(self): self.nodb = NoDB() self.nodb.bucket = 'herolfg-tests-learning-nodb-users' self.nodb.index = 'email' self.nodb.human_readable_indexes = True def __str__(self): return "{ email: '%s', name: '%s' }" % (self.email, self.name) def save(self): self.nodb.save(self) def load(self, email): instance = self.nodb.load(email) self.email = instance.email self.name = instance.name def delete(self, email): self.nodb.delete(email) def all(self): result = [] bucket = self.nodb.s3.Bucket(self.nodb.bucket) for obj in bucket.objects.filter(Prefix=self.nodb.prefix): serialized = obj.get()["Body"].read() deserialized = self.nodb._deserialize(serialized) result.append(deserialized['obj']) return result
def update_taskdb(task, user): user = user + '_tasks' nodb = NoDB() nodb.serializer = "json" nodb.bucket = "alexa-life-tracker" nodb.index = "user" # see if user exists db_tasks = nodb.load(user) print('loaded db_user') print(str(db_tasks)) completion_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") if hasattr(db_tasks, 'get') and db_tasks.get('tasks'): user_tasks = db_tasks.get('tasks', {}) current_task = user_tasks.get(task, []) current_task.insert(0, completion_time) user_tasks[task] = current_task else: db_tasks = { 'user': user, 'tasks': { task: [ completion_time, ] } } nodb.save(db_tasks)
def create_user(ctx, amz_user_id=None, habitica_user=None, habitica_key=None): if amz_user_id is None: amz_user_id = os.environ.get("AMZ_USER_ID") if habitica_user is None: habitica_user = os.environ.get("HABITICA_USER") if habitica_key is None: habitica_key = os.environ.get("HABITICA_TOKEN") from nodb import NoDB nodb = NoDB() nodb.serializer = "json" nodb.bucket = 'alexa-life-tracker' nodb.index = 'user' # check if exists first nodb_key = amz_user_id + '-keys' lt_user = nodb.load(nodb_key) if not lt_user: print("user not found, creating new entry") lt_user = {} else: print('user found data is %s ' % str(lt_user)) print("updating user") lt_user.update({ 'user': nodb_key, 'habitica_user': habitica_user, 'habitica_key': habitica_key }) nodb.save(lt_user)
def handler(event, context): code = event['pathParameters'].get('proxy', None) if code: code = code.replace('/','') nodb = NoDB() nodb.serializer = "json" nodb.bucket = "pythondaymx" nodb.index = "code" obj = nodb.load(code) # Save object data = obj data['requests'].append(event) data['count'] = len(data['requests']) nodb.save(data) return {"statusCode": 200, "body": "created"} else: return {"statusCode": 200, "body": "Bad request."}
def test_nodb_save_load(self): # create dummy bucket and store some objects bucket_name = 'dummy_bucket' self._create_mock_bucket(bucket_name) nodb = NoDB(bucket_name) nodb.index = "Name" jeff = {"Name": "Jeff", "age": 19} nodb.save(jeff) possible_jeff = nodb.load('Jeff') self.assertEqual(possible_jeff, jeff)
def createCode(): code = str(uuid.uuid4().get_hex()[0:8]) # check if code exists nodb = NoDB() nodb.serializer = "json" nodb.bucket = "pythondaymx" nodb.index = "code" obj = nodb.load(code) if obj: code = createCode() else: data = {"code": code, "requests": [], "count": 0} nodb.save(data) return code
def get_user_info_from_token(token): logging.info("verify token with amazon") from urllib.parse import quote_plus resp = requests.get( "https://api.amazon.com/auth/o2/tokeninfo?access_token=" + quote_plus(token)) logging.info(resp) verify = resp.json()['aud'] if verify != os.environ['CLIENT_ID']: logging.info("*********** invalid auth token %s" % verify) raise Exception("Invalid Token") # get user info headers = { 'Authorization': 'bearer ' + token, 'Content-Type': 'application/json' } user_info = requests.get('https://api.amazon.com/user/profile', headers=headers).json() # Save an object! store = NoDB() store.bucket = "chameleon-moto" store.serializer = 'json' store.index = "email" logger.info("about to query") user = store.load(user_info['email']) if not user: return None # update user info if not complete update = False if not user.get('name'): user['name'] = user_info['name'] update = True if not user.get('amzn_userid'): user['amzn_userid'] = user_info['name'] update = True print("********** about to store \n" + str(user)) if update: store.save(user) # True return user
def handler(event, context): code = event['params']['querystring'].get('code', None) if code: nodb = NoDB() nodb.serializer = "json" nodb.bucket = "pythondaymx" nodb.index = "code" obj = nodb.load(code) if obj: return {"statusCode": 200, "body": "ok", "response": obj} else: return {"statusCode": 404, "body": "Not found.", "obj":obj, "code":code} else: return {"statusCode": 400, "body": "Bad request."}
def test_nodb_cache(self): bucket_name = 'dummy' nodb = NoDB(bucket_name) self._create_mock_bucket(bucket_name) nodb.index = "Name" nodb.cache = True jeff = {"Name": "Jeff", "age": 19} serialized = nodb._serialize(jeff) real_index = nodb._format_index_value("Jeff") base_cache_path = os.path.join(tempfile.gettempdir(), '.nodb') if not os.path.isdir(base_cache_path): os.makedirs(base_cache_path) cache_path = os.path.join(base_cache_path, real_index) if not os.path.exists(cache_path): f = open(cache_path, 'a') f.close() with open(cache_path, "wb") as in_file: in_file.write(serialized.encode(NoDB.encoding)) nodb.load("Jeff") loaded = nodb.load("Jeff", default={}) self.assertEqual(loaded, jeff) loaded = nodb.load("Jeff", default="Booty") self.assertEqual(loaded, jeff) # test the cached item is deleted nodb.delete('Jeff') loaded = nodb.load("Jeff") self.assertIsNone(loaded) # test read from bucket when cache enabled # remove cached file nodb.save(jeff) if os.path.isfile(cache_path): os.remove(cache_path) nodb.load('Jeff') bcp = nodb._get_base_cache_path()
print(resp) verify = resp.json()['aud'] if verify != os.environ['CLIENT_ID']: print("*********** invalid auth token %s" % verify) raise Exception("Invalid Token") # get user info headers = { 'Authorization': 'bearer ' + bearer['token'], 'Content-Type': 'application/json' } user_info = requests.get('https://api.amazon.com/user/profile', headers=headers).json() # Save an object! store = NoDB() store.bucket = "chameleon-moto" store.serializer = 'json' store.index = "email" user = { "endpointid": endpoint, "email": user_info['email'], 'name': user_info['name'], 'amzn_userid': user_info['user_id'] } print("********** about to store \n" + str(user)) store.save(user) # True loaded_user = store.load(user_info['email']) assert loaded_user['endpointid'] == 'dev001' print("users saved successfully")