\r\n

51Degrees Device Detection Python  4.5

Device Detection services for 51Degrees Pipeline

cloud/gettingstarted_console.py

Getting Started Console Example - Cloud This example shows how to use the 51Degrees Cloud service to determine details about a device based on its User-Agent and User-Agent Client Hint HTTP header values.

You will learn:

  1. How to create a Pipeline that uses the 51Degrees cloud service
  2. How to pass input data (evidence) to the Pipeline
  3. How to retrieve the results

This example is available in full on GitHub.

To run this example, you will need to create a resource key. The resource key is used as shorthand to store the particular set of properties you are interested in as well as any associated license keys that entitle you to increased request limits and/or paid-for properties.

You can create a resource key using the 51Degrees Configurator.

Required PyPi Dependencies:

1 # *********************************************************************
2 # This Original Work is copyright of 51 Degrees Mobile Experts Limited.
3 # Copyright 2025 51 Degrees Mobile Experts Limited, Davidson House,
4 # Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU.
5 #
6 # This Original Work is licensed under the European Union Public Licence
7 # (EUPL) v.1.2 and is subject to its terms as set out below.
8 #
9 # If a copy of the EUPL was not distributed with this file, You can obtain
10 # one at https://opensource.org/licenses/EUPL-1.2.
11 #
12 # The 'Compatible Licences' set out in the Appendix to the EUPL (as may be
13 # amended by the European Commission) shall be deemed incompatible for
14 # the purposes of the Work and the provisions of the compatibility
15 # clause in Article 5 of the EUPL shall not apply.
16 #
17 # If using the Work as, or as part of, a network application, by
18 # including the attribution notice(s) required under Article 5 of the EUPL
19 # in the end user terms of the application under an appropriate heading,
20 # such notice(s) shall fulfill the requirements of that article.
21 # *********************************************************************
22 
23 
40 
41 import json5
42 from pathlib import Path
43 import sys
44 from fiftyone_devicedetection.devicedetection_pipelinebuilder import DeviceDetectionPipelineBuilder
45 from fiftyone_pipeline_core.logger import Logger
46 from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder
47 # pylint: disable=E0402
48 from ..example_utils import ExampleUtils
49 
50 class GettingStartedConsole():
51  def run(self, config, logger, output):
52 
53  # In this example, we use the PipelineBuilder and configure it from a file.
54  # For more information about builders in general see the documentation at
55  # https://51degrees.com/documentation/_concepts__configuration__builders__index.html
56 
57  # Create the pipeline using the service provider and the configured options.
58  pipeline = PipelineBuilder().add_logger(logger).build_from_configuration(config)
59 
60  # carry out some sample detections
61  for values in self.EvidenceValues:
62  self.analyseEvidence(values, pipeline, output)
63 
64  def analyseEvidence(self, evidence, pipeline, output):
65 
66  # FlowData is a data structure that is used to convey
67  # information required for detection and the results of the
68  # detection through the pipeline.
69  # Information required for detection is called "evidence"
70  # and usually consists of a number of HTTP Header field
71  # values, in this case represented by a dictionary of header
72  # name/value entries.
73  data = pipeline.create_flowdata()
74 
75  message = []
76 
77  # List the evidence
78  message.append("Input values:\n")
79  for key in evidence:
80  message.append(f"\t{key}: {evidence[key]}\n")
81 
82  output("".join(message))
83 
84  # Add the evidence values to the flow data
85  data.evidence.add_from_dict(evidence)
86 
87  # Process the flow data.
88  data.process()
89 
90  message = []
91  message.append("Results:\n")
92 
93  # Now that it's been processed, the flow data will have
94  # been populated with the result. In this case, we want
95  # information about the device, which we can get by
96  # asking for a result matching named "device"
97  device = data.device
98 
99  # Display the results of the detection, which are called
100  # device properties. See the property dictionary at
101  # https://51degrees.com/developers/property-dictionary
102  # for details of all available properties.
103  self.outputValue("Mobile Device", device.ismobile, message)
104  self.outputValue("Platform Name", device.platformname, message)
105  self.outputValue("Platform Version", device.platformversion, message)
106  self.outputValue("Browser Name", device.browsername, message)
107  self.outputValue("Browser Version", device.browserversion, message)
108  output("".join(message))
109 
110  def outputValue(self, name, value, message):
111  # Individual result values have a wrapper called
112  # `AspectPropertyValue`. This functions similarly to
113  # a null-able type.
114  # If the value has not been set then trying to access the
115  # `value` method will throw an exception.
116  # `AspectPropertyValue` also includes the `no_value_message`
117  # method, which describes why the value has not been set.
118  message.append(
119  f"\t{name}: {value.value()}\n" if value.has_value()
120  else f"\t{name}: {value.no_value_message()}\n")
121 
122 
123  # This collection contains the various input values that will
124  # be passed to the device detection algorithm.
125  EvidenceValues = [
126  # A User-Agent from a mobile device.
127  { "header.user-agent":
128  "Mozilla/5.0 (Linux; Android 9; SAMSUNG SM-G960U) "
129  "AppleWebKit/537.36 (KHTML, like Gecko) "
130  "SamsungBrowser/10.1 Chrome/71.0.3578.99 Mobile Safari/537.36" },
131  # A User-Agent from a desktop device.
132  { "header.user-agent":
133  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
134  "AppleWebKit/537.36 (KHTML, like Gecko) "
135  "Chrome/78.0.3904.108 Safari/537.36" },
136  # Evidence values from a windows 11 device using a browser
137  # that supports User-Agent Client Hints.
138  { "header.user-agent":
139  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
140  "AppleWebKit/537.36 (KHTML, like Gecko) "
141  "Chrome/98.0.4758.102 Safari/537.36",
142  "header.sec-ch-ua-mobile": "?0",
143  "header.sec-ch-ua":
144  "\" Not A; Brand\";v=\"99\", \"Chromium\";v=\"98\", "
145  "\"Google Chrome\";v=\"98\"",
146  "header.sec-ch-ua-platform": "\"Windows\"",
147  "header.sec-ch-ua-platform-version": "\"14.0.0\"" }
148  ]
149 
150 def main(argv):
151  # Use the command line args to get the resource key if present.
152  # Otherwise, get it from the environment variable.
153  resource_key = argv[0] if len(argv) > 0 else ExampleUtils.get_resource_key()
154 
155  # Configure a logger to output to the console.
156  logger = Logger(min_level="info")
157 
158  # Load the configuration file
159  configFile = Path(__file__).resolve().parent.joinpath("gettingstarted_console.json").read_text()
160  config = json5.loads(configFile)
161 
162  # Get the resource key setting from the config file.
163  resourceKeyFromConfig = ExampleUtils.get_resource_key_from_config(config)
164  configHasKey = resourceKeyFromConfig and resourceKeyFromConfig.startswith("!!") == False
165 
166  # If no resource key is specified in the config file then override it with the key
167  # from the environment variable / command line.
168  if configHasKey == False:
169  ExampleUtils.set_resource_key_in_config(config, resource_key)
170 
171  # If we don't have a resource key then log an error.
172  if not ExampleUtils.get_resource_key_from_config(config):
173  logger.log("error",
174  "No resource key specified in the configuration file " +
175  "'gettingstarted_console.json' or the environment variable " +
176  f"'{ExampleUtils.RESOURCE_KEY_ENV_VAR}'. The 51Degrees cloud " +
177  "service is accessed using a 'ResourceKey'. For more information " +
178  "see " +
179  "https://51degrees.com/documentation/_info__resource_keys.html. " +
180  "A resource key with the properties required by this example can be " +
181  "created for free at https://configure.51degrees.com/1QWJwHxl. " +
182  "Once complete, populate the config file or environment variable " +
183  "mentioned at the start of this message with the key.")
184  else:
185  GettingStartedConsole().run(config, logger, print)
186 
187 if __name__ == "__main__":
188  main(sys.argv[1:])