|
| 1 | +import os |
| 2 | + |
| 3 | +from copy import deepcopy |
| 4 | +from pubnub.pubnub import PubNub |
| 5 | +from pubnub.pnconfiguration import PNConfiguration |
| 6 | +from pubnub.exceptions import PubNubException |
| 7 | + |
| 8 | +config = PNConfiguration() |
| 9 | +config.publish_key = os.getenv('PUBLISH_KEY', default='demo') |
| 10 | +config.subscribe_key = os.getenv('SUBSCRIBE_KEY', default='demo') |
| 11 | +config.user_id = "example" |
| 12 | + |
| 13 | +config_2 = deepcopy(config) |
| 14 | +config_2.user_id = "example_2" |
| 15 | + |
| 16 | +pubnub = PubNub(config) |
| 17 | +pubnub_2 = PubNub(config_2) |
| 18 | + |
| 19 | +sample_user = { |
| 20 | + "uuid": "SampleUser", |
| 21 | + "name": "John Doe", |
| 22 | + |
| 23 | + "custom": {"age": 42, "address": "123 Main St."}, |
| 24 | +} |
| 25 | + |
| 26 | +# One client creates a metada for the user "SampleUser" and successfully writes it to the server. |
| 27 | +set_result = pubnub.set_uuid_metadata( |
| 28 | + **sample_user, |
| 29 | + include_custom=True, |
| 30 | + include_status=True, |
| 31 | + include_type=True |
| 32 | +).sync() |
| 33 | + |
| 34 | +# We store the eTag for the user for further updates. |
| 35 | +original_e_tag = set_result.result.data.get('eTag') |
| 36 | + |
| 37 | +# Another client sets the user meta with the same UUID but different data. |
| 38 | +overwrite_result = pubnub_2.set_uuid_metadata(uuid="SampleUser", name="Jane Doe").sync() |
| 39 | +new_e_tag = overwrite_result.result.data.get('eTag') |
| 40 | + |
| 41 | +# We can verify that there is a new eTag for the user. |
| 42 | +print(f"{original_e_tag == new_e_tag=}") |
| 43 | + |
| 44 | +# We modify the user and try to update it. |
| 45 | +updated_user = {**sample_user, "custom": {"age": 43, "address": "321 Other St."}} |
| 46 | + |
| 47 | +try: |
| 48 | + update_result = pubnub.set_uuid_metadata( |
| 49 | + **updated_user, |
| 50 | + include_custom=True, |
| 51 | + include_status=True, |
| 52 | + include_type=True |
| 53 | + ).if_matches_etag(original_e_tag).sync() |
| 54 | +except PubNubException as e: |
| 55 | + # We get an exception and after reading the error message we can see that the reason is that the eTag is outdated. |
| 56 | + print(f"Update failed: {e.get_error_message().get('message')}\nHTTP Status Code: {e.get_status_code()}") |
| 57 | + |
| 58 | + |
| 59 | +except Exception as e: |
| 60 | + print(f"Unexpected error: {e}") |
0 commit comments