Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -206,11 +206,12 @@
# example.
CONTACT_US = "https://51degrees.com/contact-us?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-onpremise-datafileupdate_console.py&utm_term=licence-key"
DEFAULT_DATA_FILENAME = os.path.expanduser("~") + os.path.sep + ENTERPRISE_DATAFILE_NAME
# The product asked of the 51Degrees distributor when no other is given,
# which is the Enterprise data file. A license key for another product needs
# that product given as the third command line argument, such as V4TAC for
# the TAC data file.
DATA_UPDATE_PRODUCT_TYPE = "V4Enterprise"
# The product asked of the 51Degrees distributor when none is given as the
# third command line argument. It is None, so no product is named and the
# distributor serves the product the license key holds. A license key that
# holds several products needs the one wanted to be given, such as
# V4Enterprise for the Enterprise data file or V4TAC for the TAC data file.
DATA_UPDATE_PRODUCT_TYPE = None

# Where to go next, printed when the example ends.
FIND_OUT_MORE = [
Expand Down Expand Up @@ -419,8 +420,10 @@ def run(self, data_file, license_key, interactive, logger, output, product = Non
# Watch the data file on disk and refresh the engine
# as soon as that file is updated.
file_system_watcher=True,
# The product the license key holds, which the 51Degrees
# distributor is asked for.
# The product the 51Degrees distributor is asked for, which
# is named only when this example is given one. With none
# given no product is named, and the distributor serves the
# product the license key holds.
data_update_product_type = product if product else DATA_UPDATE_PRODUCT_TYPE,
).add_logger(logger).build()

Expand Down Expand Up @@ -474,8 +477,8 @@ def main(argv):
# file that is included in the repository.
license_key = argv[0] if len(argv) > 0 else None
data_file = argv[1] if len(argv) > 1 else None
# The product the license key holds, when it is not the Enterprise
# data file.
# The product to ask for, which a license key that holds several
# products needs. With none given, no product is named.
product = argv[2] if len(argv) > 2 else None

# Configure a logger to output to the console.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# *********************************************************************
# This Original Work is copyright of 51 Degrees Mobile Experts Limited.
# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House,
# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU.
#
# This Original Work is licensed under the European Union Public Licence
# (EUPL) v.1.2 and is subject to its terms as set out below.
#
# If a copy of the EUPL was not distributed with this file, You can obtain
# one at https://opensource.org/licenses/EUPL-1.2.
#
# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be
# amended by the European Commission) shall be deemed incompatible for
# the purposes of the Work and the provisions of the compatibility
# clause in Article 5 of the EUPL shall not apply.
#
# If using the Work as, or as part of, a network application, by
# including the attribution notice(s) required under Article 5 of the EUPL
# in the end user terms of the application under an appropriate heading,
# such notice(s) shall fulfill the requirements of that article.
# *********************************************************************

# The data file update example names a product to the 51Degrees distributor
# only when it is given one. With none given it names none, so a license key
# that holds one product is served that product. No pipeline is built and
# nothing is downloaded, so these tests need no license key and no data
# file.

import os
import tempfile
import unittest
from unittest import mock

from fiftyone_devicedetection_examples.example_utils import ExampleUtils
from fiftyone_devicedetection_examples.onpremise import datafileupdate_console
from fiftyone_pipeline_core.logger import Logger

# Stands in for a license key. No request is made with it.
KEY = "ABCDEFGHIJKL"


class Stop(Exception):
"""Ends the example where it would build the pipeline that updates the
data file."""


def settings_given(*product):
"""Runs the example to the point where it builds the pipeline that
updates the data file, and returns the settings it gave the pipeline
builder. The data file is one that does not exist, in a directory that
does, so the example builds no other pipeline first."""
builder = mock.Mock(side_effect=Stop())
with tempfile.TemporaryDirectory() as directory:
location = os.path.join(directory, "not-there.hash")
with mock.patch.object(
datafileupdate_console, "DeviceDetectionPipelineBuilder",
builder), mock.patch.object(
ExampleUtils, "find_file", return_value=location):
try:
datafileupdate_console.DataFileUpdateConsole().run(
location, KEY, False, Logger(min_level="error"),
lambda text: None, *product)
except Stop:
pass
if builder.call_count != 1:
raise AssertionError(
"The example built " + str(builder.call_count) + " pipelines")
return builder.call_args[1]


class DataFileUpdateProductTests(unittest.TestCase):

def test_a_product_given_is_the_product_asked_for(self):
settings = settings_given("V4TAC")
self.assertEqual("V4TAC", settings["data_update_product_type"])
self.assertEqual(KEY, settings["licence_keys"])

def test_no_product_is_asked_for_when_none_is_given(self):
for name, product in (
("no argument", ()), ("none", (None,)), ("empty", ("",))):
with self.subTest(name):
self.assertIsNone(
settings_given(*product).get("data_update_product_type"))

def test_the_third_argument_is_the_product(self):
for name, argv, product in (
("given", [KEY, "a.hash", "V4TAC"], "V4TAC"),
("not given", [KEY, "a.hash"], None)):
with self.subTest(name):
with mock.patch.object(
datafileupdate_console.DataFileUpdateConsole,
"run") as run, mock.patch.object(
ExampleUtils, "print_find_out_more"):
datafileupdate_console.main(argv)
self.assertEqual(product, run.call_args[0][-1])


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,14 @@ def get_url_formatter(self):
if not self._data_update_use_url_formatter:
return self.update_url_params["base_url"]

# A product is named only when one is configured, and then every
# request carries it. With none configured the URL has no Product
# parameter at all, so a license key that holds one product is
# served that product.
query_params = {
"Type": self.update_url_params["type"],
"licenseKeys": self.update_url_params.get("license_keys"),
"Product": self.update_url_params.get("product")
"Product": self.update_url_params.get("product") or None
}

# Remove keys with None values
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,8 @@ def __init__(
@param use_predictive_graph: True if the predictive optimized graph should be used for processing
@param data_update_use_url_formatter: This must be set to false to prevent the API from appending the query string parameters that are required when calling the 51Degrees Distributor service.
@type data_update_use_url_formatter: bool
@param data_update_product_type: The product to ask the 51Degrees Distributor for, such as V4TAC. When one is given, every request for a data file names it. When none is given, no request names a product unless the Distributor asks which of several is wanted, and the product of the data file in use is then named.
@type data_update_product_type: string

"""

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,5 +68,40 @@ def test_no_product_is_named_before_a_data_file_is_loaded(self):
data_file(flow_element).get_data_update_product())


def formatted(product):
"""The update URL the URL formatter writes for a data file that is
configured with the product."""
return DeviceDetectionDataFile(
flow_element=SimpleNamespace(), identifier="HashV41",
path="not-read.hash", data_update_use_url_formatter=True,
update_url_params={
"base_url": "https://example.com/update",
"type": "HashV41",
"license_keys": "ABCDEFGHIJKL",
"product": product}).get_update_url()


# A product is named in the update URL only when one is configured. Every
# request is made to that URL, so with a product configured every request
# names it, the first included, and with none configured the first request
# has no Product parameter at all.
class ConfiguredProductTests(unittest.TestCase):

def test_a_configured_product_is_named_in_the_update_url(self):
self.assertEqual(
"https://example.com/update?Type=HashV41&"
"licenseKeys=ABCDEFGHIJKL&Product=V4TAC",
formatted("V4TAC"))

def test_no_product_is_named_when_none_is_configured(self):
for name, product in (("none", None), ("empty", "")):
with self.subTest(name):
url = formatted(product)
self.assertEqual(
"https://example.com/update?Type=HashV41&"
"licenseKeys=ABCDEFGHIJKL", url)
self.assertNotIn("product", url.lower())


if __name__ == "__main__":
unittest.main()
2 changes: 1 addition & 1 deletion ip-intelligence/fiftyone_ipintelligence_examples/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ python -m fiftyone_ipintelligence_examples.onpremise.countries_console [data-fil
python -m fiftyone_ipintelligence_examples.onpremise.offlineprocessing [data-file [evidence-file]]
python -m fiftyone_ipintelligence_examples.onpremise.performance_console [-d data-file] [-e evidence-file]
python -m fiftyone_ipintelligence_examples.onpremise.compare_console [-d data-file] [-t truth-file]
python -m fiftyone_ipintelligence_examples.onpremise.datafileupdate_console [license-key [data-file]]
python -m fiftyone_ipintelligence_examples.onpremise.datafileupdate_console [license-key [data-file [product]]]
python -m fiftyone_ipintelligence_examples.onpremise.mixed_console [hash-file [ipi-file]]
python -m fiftyone_ipintelligence_examples.onpremise.gettingstarted_web
```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,12 @@
# example.
CONTACT_US = "https://51degrees.com/contact-us?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_ipintelligence_examples-src-fiftyone_ipintelligence_examples-onpremise-datafileupdate_console.py&utm_term=licence-key"

# The product type passed to the 51Degrees distributor. This identifies the
# IP intelligence Enterprise product and may need to be adjusted to match
# the product your license entitles you to.
DATA_UPDATE_PRODUCT_TYPE = "IPIV4Enterprise"
# The product asked of the 51Degrees distributor when none is given as the
# third command line argument. It is None, so no product is named and the
# distributor serves the product the license key holds. A license key that
# holds several products needs the one wanted to be given, such as
# IPIV4Enterprise for the Enterprise data file.
DATA_UPDATE_PRODUCT_TYPE = None

DEFAULT_DATA_FILENAME = os.path.join(
os.path.expanduser("~"), ENTERPRISE_DATAFILE_NAME)
Expand Down Expand Up @@ -212,7 +214,7 @@ def update_programmatically(self, data_file, output):
finally:
shutil.rmtree(directory, ignore_errors=True)

def run(self, data_file, license_key, interactive, logger, output):
def run(self, data_file, license_key, interactive, logger, output, product = None):
logger.log("info", "Starting example")

# Try to find a license key in the environment if not supplied.
Expand Down Expand Up @@ -282,7 +284,11 @@ def run(self, data_file, license_key, interactive, logger, output):
auto_update = True,
# Reload automatically when the data file on disk changes.
file_system_watcher = True,
data_update_product_type = DATA_UPDATE_PRODUCT_TYPE,
# The product the 51Degrees distributor is asked for, which is
# named only when this example is given one. With none given no
# product is named, and the distributor serves the product the
# license key holds.
data_update_product_type = product if product else DATA_UPDATE_PRODUCT_TYPE,
# Usage sharing is off for this example. In production turn it on,
# because the requests shared improve the data every user gets.
usage_sharing = False).add_logger(logger).build()
Expand Down Expand Up @@ -330,11 +336,14 @@ def run(self, data_file, license_key, interactive, logger, output):
def main(argv):
license_key = argv[0] if len(argv) > 0 else None
data_file = argv[1] if len(argv) > 1 else None
# The product to ask for, which a license key that holds several
# products needs. With none given, no product is named.
product = argv[2] if len(argv) > 2 else None

# Configure a logger to output to the console.
logger = Logger(min_level="info")

DataFileUpdateConsole().run(data_file, license_key, True, logger, print)
DataFileUpdateConsole().run(data_file, license_key, True, logger, print, product)

# Printed however the example ended, whether it updated the data file,
# had no licence key, or was stopped before the download.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# *********************************************************************
# This Original Work is copyright of 51 Degrees Mobile Experts Limited.
# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House,
# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU.
#
# This Original Work is licensed under the European Union Public Licence
# (EUPL) v.1.2 and is subject to its terms as set out below.
#
# If a copy of the EUPL was not distributed with this file, You can obtain
# one at https://opensource.org/licenses/EUPL-1.2.
#
# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be
# amended by the European Commission) shall be deemed incompatible for
# the purposes of the Work and the provisions of the compatibility
# clause in Article 5 of the EUPL shall not apply.
#
# If using the Work as, or as part of, a network application, by
# including the attribution notice(s) required under Article 5 of the EUPL
# in the end user terms of the application under an appropriate heading,
# such notice(s) shall fulfill the requirements of that article.
# *********************************************************************

# The data file update example names a product to the 51Degrees distributor
# only when it is given one. With none given it names none, so a license key
# that holds one product is served that product. No pipeline is built and
# nothing is downloaded, so these tests need no license key and no data
# file.

import os
import tempfile
import unittest
from unittest import mock

from fiftyone_ipintelligence_examples.example_utils import ExampleUtils
from fiftyone_ipintelligence_examples.onpremise import datafileupdate_console
from fiftyone_pipeline_core.logger import Logger

# Stands in for a license key. No request is made with it.
KEY = "ABCDEFGHIJKL"


class Stop(Exception):
"""Ends the example where it would build the pipeline that updates the
data file."""


def settings_given(*product):
"""Runs the example to the point where it builds the pipeline that
updates the data file, and returns the settings it gave the pipeline
builder. The data file is one that does not exist, in a directory that
does, so the example copies no file first."""
builder = mock.Mock(side_effect=Stop())
with tempfile.TemporaryDirectory() as directory:
location = os.path.join(directory, "not-there.ipi")
with mock.patch.object(
datafileupdate_console, "IpIntelligencePipelineBuilder",
builder):
try:
datafileupdate_console.DataFileUpdateConsole().run(
location, KEY, False, Logger(min_level="error"),
lambda text: None, *product)
except Stop:
pass
if builder.call_count != 1:
raise AssertionError(
"The example built " + str(builder.call_count) + " pipelines")
return builder.call_args[1]


class DataFileUpdateProductTests(unittest.TestCase):

def test_a_product_given_is_the_product_asked_for(self):
settings = settings_given("IPIV4Enterprise")
self.assertEqual(
"IPIV4Enterprise", settings["data_update_product_type"])
self.assertEqual(KEY, settings["licence_keys"])

def test_no_product_is_asked_for_when_none_is_given(self):
for name, product in (
("no argument", ()), ("none", (None,)), ("empty", ("",))):
with self.subTest(name):
self.assertIsNone(
settings_given(*product).get("data_update_product_type"))

def test_the_third_argument_is_the_product(self):
for name, argv, product in (
("given", [KEY, "a.ipi", "IPIV4Enterprise"],
"IPIV4Enterprise"),
("not given", [KEY, "a.ipi"], None)):
with self.subTest(name):
with mock.patch.object(
datafileupdate_console.DataFileUpdateConsole,
"run") as run, mock.patch.object(
ExampleUtils, "print_find_out_more"):
datafileupdate_console.main(argv)
self.assertEqual(product, run.call_args[0][-1])


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,14 @@ def get_url_formatter(self):
if not self._data_update_use_url_formatter:
return self.update_url_params["base_url"]

# A product is named only when one is configured, and then every
# request carries it. With none configured the URL has no Product
# parameter at all, so a license key that holds one product is
# served that product.
query_params = {
"Type": self.update_url_params["type"],
"licenseKeys": self.update_url_params.get("license_keys"),
"Product": self.update_url_params.get("product")
"Product": self.update_url_params.get("product") or None
}

# Remove keys with None values
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@ def __init__(
@param data_update_url: base url for the datafile update service
@param data_update_use_url_formatter: This must be set to false to prevent the API from appending the query string parameters that are required when calling the 51Degrees Distributor service.
@type data_update_use_url_formatter: bool
@param data_update_product_type: The product to ask the 51Degrees Distributor for, such as IPIV4Enterprise. When one is given, every request for a data file names it. When none is given, no request names a product unless the Distributor asks which of several is wanted, and the product of the data file in use is then named.
@type data_update_product_type: string

"""

Expand Down
Loading
Loading