def check_date_validity(date: DatetimeWithNanoseconds): settings_dict = settings_ref.document("times").get().to_dict() appointment_start_time, appointment_end_time = ( settings_dict["openTime"], settings_dict["endTime"], ) time_slots = (int(appointment_end_time[:2]) - int(appointment_start_time[:2])) * 2 docs = (appointments_ref.where( "startTime", ">", DatetimeWithNanoseconds(date.year, date.month, date.day, tzinfo=datetime.timezone.utc), ).where( "startTime", "<", DatetimeWithNanoseconds(date.year, date.month, date.day + 1, tzinfo=datetime.timezone.utc), ).get()) if docs is not None: if sum(1 for _ in docs) < time_slots: return True else: return False return True
def __init__(self, year, month, day, hour, minute): self.booking = DatetimeWithNanoseconds.from_rfc3339( datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%fZ')) self.reserved = DatetimeWithNanoseconds(year=year, month=month, day=day, hour=hour, minute=minute)
def check_time_validity(start_time: DatetimeWithNanoseconds, end_time: DatetimeWithNanoseconds): settings_dict = settings_ref.document("times").get().to_dict() appointment_start_time, appointment_end_time = ( settings_dict["openTime"], settings_dict["endTime"], ) if start_time.minute == 0: start_minute = "00" else: start_minute = str(start_time.minute) if end_time.minute == 0: end_minute = "00" else: end_minute = str(end_time.minute) str_start_time = str(start_time.hour) + start_minute str_end_time = str(end_time.hour) + end_minute if not (appointment_start_time <= str_start_time < str_end_time <= appointment_end_time): return False, "invalid time" docs = (appointments_ref.where( "startTime", ">", DatetimeWithNanoseconds( start_time.year, start_time.month, start_time.day, tzinfo=datetime.timezone.utc, ), ).where( "startTime", "<", DatetimeWithNanoseconds( start_time.year, start_time.month, start_time.day + 1, tzinfo=datetime.timezone.utc, ), ).get()) if docs is not None: for each_doc in docs: each_patient_info = each_doc.to_dict() each_patient_start_time = each_patient_info["startTime"] each_patient_end_time = each_patient_info["endTime"] if (each_patient_start_time < start_time < each_patient_end_time or each_patient_start_time < end_time < each_patient_end_time): return False, "unavailable time slot" if (each_patient_start_time > start_time and each_patient_end_time < end_time): return False, "unavailable time slot" if (each_patient_start_time == start_time and each_patient_end_time == end_time): return False, "unavailable time slot" return True, ""
def to_datetime_with_nanoseconds(dt): return DatetimeWithNanoseconds(dt.year, dt.month, dt.day, dt.hour, dt.minute, tzinfo=datetime.timezone.utc)
def decode_value( value, client ) -> Union[None, bool, int, float, list, datetime.datetime, str, bytes, dict, GeoPoint]: """Converts a Firestore protobuf ``Value`` to a native Python value. Args: value (google.cloud.firestore_v1.types.Value): A Firestore protobuf to be decoded / parsed / converted. client (:class:`~google.cloud.firestore_v1.client.Client`): A client that has a document factory. Returns: Union[NoneType, bool, int, float, datetime.datetime, \ str, bytes, dict, ~google.cloud.Firestore.GeoPoint]: A native Python value converted from the ``value``. Raises: NotImplementedError: If the ``value_type`` is ``reference_value``. ValueError: If the ``value_type`` is unknown. """ value_pb = getattr(value, "_pb", value) value_type = value_pb.WhichOneof("value_type") if value_type == "null_value": return None elif value_type == "boolean_value": return value_pb.boolean_value elif value_type == "integer_value": return value_pb.integer_value elif value_type == "double_value": return value_pb.double_value elif value_type == "timestamp_value": return DatetimeWithNanoseconds.from_timestamp_pb( value_pb.timestamp_value) elif value_type == "string_value": return value_pb.string_value elif value_type == "bytes_value": return value_pb.bytes_value elif value_type == "reference_value": return reference_value_to_document(value_pb.reference_value, client) elif value_type == "geo_point_value": return GeoPoint(value_pb.geo_point_value.latitude, value_pb.geo_point_value.longitude) elif value_type == "array_value": return [ decode_value(element, client) for element in value_pb.array_value.values ] elif value_type == "map_value": return decode_dict(value_pb.map_value.fields, client) else: raise ValueError("Unknown ``value_type``", value_type)
async def admin_word_list(request: Request): result = await request.form() print(result) items = [] if "selsected_items" in result._dict: items = re.sub('(\[|\'|\]|\s)', '', result._dict["selsected_items"]).split(',') print(items) next_key = None if "action" in result._dict: if result._dict["action"] == "next": if result._dict["next_key"] != 'None': print(result._dict["next_key"]) date_time = datetime.fromisoformat( str(result._dict["next_key"])) next_key = DatetimeWithNanoseconds( date_time.year, date_time.month, date_time.day, date_time.hour, date_time.minute, date_time.second, date_time.microsecond) elif result._dict["action"] == "fitst": pass elif result._dict["action"] == "delete_word": for item in items: word_service.delete(item) elif result._dict["action"] == "mean_init": for item in items: word_service.update_mean(item, item, "admin") elif result._dict["action"] == "update_mean": for item in items: word_service.update_mean(item, result._dict["mean"], "admin") elif result._dict["action"] == "update_tag": for item in items: tags_cnt_dict = json.loads(result._dict["tags_cnt"].replace( "'", '"')) word_service.update_tags(item, tags_cnt_dict) word_list = word_service.get_word_list_next(20, next_key) # print(word_list["doc"]) return templates.TemplateResponse("word_list.html", { "request": request, "data": word_list })
def test_update_results_written(altitude_grp): with transaction() as txn: analytics.update_result(txn, [datetime.now()], PHASE, SOURCE, YEAR, SPECIES, altitude_grp) data = read_result(altitude_grp=altitude_grp) if altitude_grp is None: assert "altitude_grp" not in data else: assert data["altitude_grp"] == altitude_grp assert data["source"] == SOURCE assert data["year"] == YEAR assert data["species"] == SPECIES assert (k in data["values"]["phase"] for k in ["min", "max", "median", "quantile_25", "quantile_75"])
def decode_value(value, client): """Converts a Firestore protobuf ``Value`` to a native Python value. Args: value (google.cloud.firestore_v1beta1.types.Value): A Firestore protobuf to be decoded / parsed / converted. client (~.firestore_v1beta1.client.Client): A client that has a document factory. Returns: Union[NoneType, bool, int, float, datetime.datetime, \ str, bytes, dict, ~google.cloud.Firestore.GeoPoint]: A native Python value converted from the ``value``. Raises: NotImplementedError: If the ``value_type`` is ``reference_value``. ValueError: If the ``value_type`` is unknown. """ value_type = value.WhichOneof("value_type") if value_type == "null_value": return None elif value_type == "boolean_value": return value.boolean_value elif value_type == "integer_value": return value.integer_value elif value_type == "double_value": return value.double_value elif value_type == "timestamp_value": return DatetimeWithNanoseconds.from_timestamp_pb(value.timestamp_value) elif value_type == "string_value": return value.string_value elif value_type == "bytes_value": return value.bytes_value elif value_type == "reference_value": return reference_value_to_document(value.reference_value, client) elif value_type == "geo_point_value": return GeoPoint(value.geo_point_value.latitude, value.geo_point_value.longitude) elif value_type == "array_value": return [decode_value(element, client) for element in value.array_value.values] elif value_type == "map_value": return decode_dict(value.map_value.fields, client) else: raise ValueError("Unknown ``value_type``", value_type)
async def admin_tweet_log(request: Request): result = await request.form() print(result) items = [] if "selsected_items" in result._dict: items = re.sub('(\[|\'|\]|\s)', '', result._dict["selsected_items"]).split(',') print(items) next_key = None if "action" in result._dict: if result._dict["action"] == "next": if result._dict["next_key"] != 'None': print(result._dict["next_key"]) date_time = datetime.fromisoformat( str(result._dict["next_key"])) next_key = DatetimeWithNanoseconds( date_time.year, date_time.month, date_time.day, date_time.hour, date_time.minute, date_time.second, date_time.microsecond) elif result._dict["action"] == "fitst": pass elif result._dict["action"] == "delete_tweet": for item in items: word_service.tweet_delete(item) elif result._dict["action"] == "force_tweet": for item in items: word_service.tweet_force(item) tweet_list = word_service.get_tweet_log_next(20, next_key) # print(word_list["doc"]) return templates.TemplateResponse("tweet_log.html", { "request": request, "data": tweet_list })
def update(self, new_state, new_availability, timezone): if not self.is_valid(self.state, self.availability): if not self.is_idle(new_state, new_availability): return else: utc_time = DatetimeWithNanoseconds.utcnow() self.update_in_use_charging(new_state, new_availability, utc_time) self.update_in_use_stopped(new_state, new_availability, utc_time) self.update_weekly_usage( new_state, new_availability, self.utc_to_local_time(utc_time, timezone)) if new_state != self.state: logging.debug("updating meter state from {} to {}".format( self.state, new_state)) self.state = new_state self.stale = True if new_availability != self.availability: logging.debug("updating meter availability from {} to {}".format( self.availability, new_availability)) self.availability = new_availability self.stale = True
def _parse_conditions( self, conditions: List[Tuple[str, str, Any]]) -> List[Tuple[str, str, Any]]: conditions = list(conditions) conditions_parsed = [] if self.schema_props is not None: for attribute, operator, value in conditions: if not self.has_attribute(attribute): raise KeyError( f"Invalid attribute provided: `{attribute}`") attr_props = self.schema_props.get(attribute, {}) any_of = attr_props.get("anyOf", []) # Check if schema is a datetime if any((x.get("format") == "date-time" for x in any_of)): if type(value) == str: try: value = DatetimeWithNanoseconds.fromisoformat( value) except ValueError: pass conditions_parsed.append((attribute, operator, value)) return conditions_parsed
def test_table_backup( admin_client, unique_suffix, instance_labels, location_id, data_instance_populated, data_cluster_id, instances_to_delete, tables_to_delete, backups_to_delete, skip_on_emulator, ): from google.cloud._helpers import _datetime_to_pb_timestamp from google.cloud.bigtable import enums temp_table_id = "test-backup-table" temp_table = data_instance_populated.table(temp_table_id) temp_table.create() tables_to_delete.append(temp_table) temp_backup_id = "test-backup" # TODO: consider using `datetime.datetime.now().timestamp()` # when support for Python 2 is fully dropped expire = int(time.mktime(datetime.datetime.now().timetuple())) + 604800 # Testing `Table.backup()` factory temp_backup = temp_table.backup( temp_backup_id, cluster_id=data_cluster_id, expire_time=datetime.datetime.utcfromtimestamp(expire), ) # Reinitialize the admin client. This is to test `_table_admin_client` # returns a client object (and not NoneType) temp_backup._instance._client = admin_client # Sanity check for `Backup.exists()` method assert not temp_backup.exists() # Testing `Backup.create()` method backup_op = temp_backup.create() backup_op.result(timeout=30) # Implicit testing of `Backup.delete()` method backups_to_delete.append(temp_backup) # Testing `Backup.exists()` method assert temp_backup.exists() # Testing `Table.list_backups()` method temp_table_backup = temp_table.list_backups()[0] assert temp_backup_id == temp_table_backup.backup_id assert data_cluster_id == temp_table_backup.cluster assert expire == temp_table_backup.expire_time.seconds assert (temp_table_backup.encryption_info.encryption_type == enums.EncryptionInfo.EncryptionType.GOOGLE_DEFAULT_ENCRYPTION) # Testing `Backup.update_expire_time()` method expire += 3600 # A one-hour change in the `expire_time` parameter updated_time = datetime.datetime.utcfromtimestamp(expire) temp_backup.update_expire_time(updated_time) test = _datetime_to_pb_timestamp(updated_time) # Testing `Backup.get()` method temp_table_backup = temp_backup.get() assert test.seconds == DatetimeWithNanoseconds.timestamp( temp_table_backup.expire_time) # Testing `Table.restore()` and `Backup.retore()` methods restored_table_id = "test-backup-table-restored" restored_table = data_instance_populated.table(restored_table_id) local_restore_op = temp_table.restore(restored_table_id, cluster_id=data_cluster_id, backup_id=temp_backup_id) local_restore_op.result(timeout=30) tables = data_instance_populated.list_tables() assert restored_table in tables restored_table.delete() # Testing `Backup.restore()` into a different instance: # Setting up another instance... alt_instance_id = f"gcp-alt-{unique_suffix}" alt_cluster_id = f"{alt_instance_id}-cluster" alt_instance = admin_client.instance(alt_instance_id, labels=instance_labels) alt_cluster = alt_instance.cluster( cluster_id=alt_cluster_id, location_id=location_id, serve_nodes=1, ) create_op = alt_instance.create(clusters=[alt_cluster]) instances_to_delete.append(alt_instance) create_op.result(timeout=30) # Testing `restore()`... restore_op = temp_backup.restore(restored_table_id, alt_instance_id) restore_op.result(timeout=30) restored_table = alt_instance.table(restored_table_id) assert restored_table in alt_instance.list_tables() restored_table.delete()
def datetime_helper(day, hour): return DatetimeWithNanoseconds(2021, 8, day, hour, 00, 00, tzinfo=datetime.timezone.utc)
def test_main(self): self.prepare_responses() master_collection = self.firebase_db.collection(u'{}'.format( config.PRIMARY_TABLE_NAME)).stream() # Collection should be empty for _ in master_collection: assert False with mock.patch("main.datetime") as datetime_mock: custom_date = datetime(2020, 6, 1) datetime_mock.now.return_value = custom_date main("data", "context") master_collection = self.firebase_db.collection(u'{}'.format( config.PRIMARY_TABLE_NAME)).stream() master_actual = [] # Collection should contain expected for document in master_collection: master_actual.append(document.to_dict()) class_a = { 'id': 80007, 'seats': { 'remaining': 0, 'actual': 57, 'capacity': 58 }, 'waitlist': { 'remaining': 3, 'actual': 27, 'capacity': 30 }, 'name': 'Class A', 'prerequisites': 'a prerequisite', 'credits': 3.0, 'code': 'ABC 123', 'last_updated': DatetimeWithNanoseconds(2020, 6, 1, 0, 0, 0, 0, tzinfo=UTC), 'restrictions': 'a restriction' } class_b = { 'id': 80008, 'seats': { 'remaining': 0, 'actual': 55, 'capacity': 55 }, 'waitlist': { 'remaining': 28, 'actual': 2, 'capacity': 30 }, 'name': 'Class B', 'prerequisites': 'b prerequisites', 'credits': 3.0, 'code': 'CBA 321', 'last_updated': DatetimeWithNanoseconds(2020, 6, 1, 0, 0, 0, 0, tzinfo=UTC), 'restrictions': 'b restrictions' } master_expected = [class_a, class_b] self.maxDiff = None self.assertCountEqual(master_expected, master_actual) all_actual = [] all_collection = self.firebase_db.collection(u'{}'.format( config.SECONDARY_TABLE_NAME)).stream() # Collection should contain expected for document in all_collection: all_actual.append(document.to_dict()) all_expected = [{"80007": class_a, "80008": class_b}] self.assertCountEqual(all_expected, all_actual)
def convert_to_date_from_dict(date): return DatetimeWithNanoseconds(**date)
def get_current_date(): return DatetimeWithNanoseconds.from_rfc3339( datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
def datetimewithnanoseconds_eq(self, other): if old_datetimewithnanoseconds_eq: equal = old_datetimewithnanoseconds_eq(self, other) if equal: return True elif type(self) is type(other): return False # Otherwise try to convert them to an equvialent form. # See https://github.com/googleapis/python-spanner-django/issues/272 if isinstance(other, datetime.datetime): return self.ctime() == other.ctime() return False DatetimeWithNanoseconds.__eq__ = datetimewithnanoseconds_eq # Sanity check here since tests can't easily be run for this file: if __name__ == "__main__": from django.utils import timezone UTC = timezone.utc dt = datetime.datetime(2020, 1, 10, 2, 44, 57, 999, UTC) dtns = DatetimeWithNanoseconds(2020, 1, 10, 2, 44, 57, 999, UTC) equal = dtns == dt if not equal: raise Exception("%s\n!=\n%s" % (dtns, dt))
def test_backup(self): if Config.IN_EMULATOR: self.skipTest("backups are not supported in the emulator") from google.cloud._helpers import _datetime_to_pb_timestamp temp_table_id = "test-backup-table" temp_table = Config.INSTANCE_DATA.table(temp_table_id) temp_table.create() self.tables_to_delete.append(temp_table) temp_backup_id = "test-backup" # TODO: consider using `datetime.datetime.now().timestamp()` # when support for Python 2 is fully dropped expire = int(time.mktime(datetime.datetime.now().timetuple())) + 604800 # Testing `Table.backup()` factory temp_backup = temp_table.backup( temp_backup_id, cluster_id=CLUSTER_ID_DATA, expire_time=datetime.datetime.utcfromtimestamp(expire), ) # Sanity check for `Backup.exists()` method self.assertFalse(temp_backup.exists()) # Testing `Backup.create()` method temp_backup.create().result() # Implicit testing of `Backup.delete()` method self.backups_to_delete.append(temp_backup) # Testing `Backup.exists()` method self.assertTrue(temp_backup.exists()) # Testing `Table.list_backups()` method temp_table_backup = temp_table.list_backups()[0] self.assertEqual(temp_backup_id, temp_table_backup.backup_id) self.assertEqual(CLUSTER_ID_DATA, temp_table_backup.cluster) self.assertEqual(expire, temp_table_backup.expire_time.seconds) # Testing `Backup.update_expire_time()` method expire += 3600 # A one-hour change in the `expire_time` parameter updated_time = datetime.datetime.utcfromtimestamp(expire) temp_backup.update_expire_time(updated_time) test = _datetime_to_pb_timestamp(updated_time) # Testing `Backup.get()` method temp_table_backup = temp_backup.get() self.assertEqual( test.seconds, DatetimeWithNanoseconds.timestamp(temp_table_backup.expire_time), ) # Testing `Table.restore()` and `Backup.retore()` methods restored_table_id = "test-backup-table-restored" restored_table = Config.INSTANCE_DATA.table(restored_table_id) temp_table.restore(restored_table_id, cluster_id=CLUSTER_ID_DATA, backup_id=temp_backup_id).result() tables = Config.INSTANCE_DATA.list_tables() self.assertIn(restored_table, tables) restored_table.delete()
def web_hooks(request): dialogflow_request = DialogflowRequest(request.data) session_id = dialogflow_request.get_session().split("/")[-1] if dialogflow_request.get_intent_displayName( ) == "Create Appointment - User": _raw_user_name = dialogflow_request.get_paramter("person") str_raw_user_name = str(_raw_user_name) str_user_name = (str_raw_user_name.strip("{").strip("}").strip( "[").strip("]").strip(":").strip("'")) temp_ref.document(session_id).set({"Patient": str_user_name}) dialogflow_response = DialogflowResponse( "Hi {}! Did I get your name right?".format(str_user_name)) elif dialogflow_request.get_intent_displayName( ) == "Create Appointment - Phone": phone_number = dialogflow_request.get_paramter("phone-number") temp_ref.document(session_id).update({"phone_number": phone_number}) dialogflow_response = DialogflowResponse( "Your phone number is {}. Is that correct?".format(phone_number)) elif dialogflow_request.get_intent_displayName( ) == "Create Appointment - Purpose": purpose = dialogflow_request.get_paramter("purpose") temp_ref.document(session_id).update({"Symptoms": purpose}) dialogflow_response = DialogflowResponse( "Thank you. What date would you like to make this appointment on?") elif dialogflow_request.get_intent_displayName( ) == "Create Appointment - Date": intend_date = dialogflow_request.get_paramter("date") if isinstance(intend_date, str): intend_date = datetime.datetime.fromisoformat(intend_date) intend_date = DatetimeWithNanoseconds( intend_date.year, intend_date.month, intend_date.day, intend_date.hour, intend_date.minute, ) temp_ref.document(session_id).update({"intend_date": intend_date}) dialogflow_response = DialogflowResponse( "Ok, so the date is {}. Is that right?".format(intend_date)) elif (dialogflow_request.get_intent_displayName() == "Create Appointment - Date - yes"): docu_dict = temp_ref.document(session_id).get().to_dict() intend_date = docu_dict["intend_date"] if isinstance(intend_date, str): intend_date = datetime.datetime.fromisoformat(intend_date) intend_date = DatetimeWithNanoseconds( intend_date.year, intend_date.month, intend_date.day, intend_date.hour, intend_date.minute, ) if check_date_validity(intend_date): dialogflow_response = DialogflowResponse( "The date you specified is available. Please indicate a time interval (30 minutes) to book." ) dialogflow_response.expect_user_response = False dialogflow_response.add( OutputContexts("pintox-app", session_id, "Create Appointment - Time", 200, {})) dialogflow_response.add(SystemIntent("Create Appointment - Time")) else: dialogflow_response = DialogflowResponse( "Sorry, the date you selected is full. Please select another date." ) dialogflow_response.expect_user_response = False dialogflow_response.add( OutputContexts("pintox-app", session_id, "Create Appointment - Date", 200, {})) dialogflow_response.add(SystemIntent("Create Appointment - Date")) elif dialogflow_request.get_intent_displayName( ) == "Create Appointment - Time": time_period = dialogflow_request.get_paramter("time-period") start_time, end_time = time_period["startTime"], time_period["endTime"] if isinstance(start_time, str): start_time = datetime.datetime.fromisoformat(start_time) start_time = DatetimeWithNanoseconds( start_time.year, start_time.month, start_time.day, start_time.hour, start_time.minute, ) if isinstance(end_time, str): end_time = datetime.datetime.fromisoformat(end_time) end_time = DatetimeWithNanoseconds( end_time.year, end_time.month, end_time.day, end_time.hour, end_time.minute, ) temp_ref.document(session_id).update({ "startTime": start_time, "endTime": end_time }) dialogflow_response = DialogflowResponse( "Your time is from {} to {}. Is that correct?".format( start_time, end_time)) elif (dialogflow_request.get_intent_displayName() == "Create Appointment - Time - yes"): docu_dict = temp_ref.document(session_id).get().to_dict() start_time, end_time = docu_dict["startTime"], docu_dict["endTime"] if isinstance(start_time, str): start_time = datetime.datetime.fromisoformat(start_time) start_time = DatetimeWithNanoseconds( start_time.year, start_time.month, start_time.day, start_time.hour, start_time.minute, ) if isinstance(end_time, str): end_time = datetime.datetime.fromisoformat(end_time) end_time = DatetimeWithNanoseconds( end_time.year, end_time.month, end_time.day, end_time.hour, end_time.minute, ) res, msg = check_time_validity(start_time, end_time) if res: dialogflow_response = DialogflowResponse( "The appointment has been booked. Would you like to book another?" ) appointments_ref.document().set(docu_dict) patients_ref.document(docu_dict["phone_number"]).set( {"name": docu_dict["Patient"]}) else: if msg == "invalid time": dialogflow_response = DialogflowResponse( "The time you specified is out of the working hour. Please select another time." ) dialogflow_response.expect_user_response = False dialogflow_response.add( SystemIntent("Create Appointment - Time - hours")) else: dialogflow_response = DialogflowResponse( "Sorry, the time you selected is unavailable. Please select another time." ) dialogflow_response.expect_user_response = False dialogflow_response.add( SystemIntent("Create Appointment - Time - failure")) else: dialogflow_response = DialogflowResponse( "This is a text response from webhook.") response = app.response_class( response=dialogflow_response.get_final_response(), mimetype="application/json") return response
def __init__(self, timestamp: str): self.value = DatetimeWithNanoseconds.from_rfc3339(timestamp)
def build_timestamp( dt: Optional[Union[DatetimeWithNanoseconds, datetime.datetime]] = None ) -> Timestamp: """Returns the supplied datetime (or "now") as a Timestamp""" return _datetime_to_pb_timestamp(dt or DatetimeWithNanoseconds.utcnow())