\r\n

51Degrees Device Detection Python  4.3Newer Version 4.4

Device Detection services for 51Degrees Pipeline

cloud/gettingstarted_console.py

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:

  • fiftyone_devicedetection
1 # *********************************************************************
2 # This Original Work is copyright of 51 Degrees Mobile Experts Limited.
3 # Copyright 2019 51 Degrees Mobile Experts Limited, 5 Charlotte Close,
4 # Caversham, Reading, Berkshire, United Kingdom RG4 7BY.
5 #
6 # This Original Work is licensed under the European Union Public Licence (EUPL)
7 # 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 
34 
35 import logging
36 import sys
37 from fiftyone_devicedetection.devicedetection_pipelinebuilder import DeviceDetectionPipelineBuilder
38 from fiftyone_devicedetection_examples.example_utils import ExampleUtils
39 
40 class GettingStartedConsole():
41  def run(self, resource_key, logger):
42 
43  # In this example, we use the DeviceDetectionPipelineBuilder
44  # and configure it in code. For more information about
45  # pipelines in general see the documentation at
46  # http://51degrees.com/documentation/4.3/_concepts__configuration__builders__index.html
47  pipeline = DeviceDetectionPipelineBuilder(
48  # Tell it that we want to use cloud and pass our resource key.
49  resource_key = resource_key,
50  # The origin header should be set in order to help the
51  # cloud service know where the request is coming from.
52  cloud_request_origin = "51Degrees.example.com").build()
53 
54  # carry out some sample detections
55  for values in self.EvidenceValues:
56  self.analyseEvidence(values, pipeline, logger)
57 
58  def analyseEvidence(self, evidence, pipeline, logger):
59 
60  # FlowData is a data structure that is used to convey
61  # information required for detection and the results of the
62  # detection through the pipeline.
63  # Information required for detection is called "evidence"
64  # and usually consists of a number of HTTP Header field
65  # values, in this case represented by a dictionary of header
66  # name/value entries.
67  data = pipeline.create_flowdata()
68 
69  message = []
70 
71  # List the evidence
72  message.append("Input values:\n")
73  for key in evidence:
74  message.append(f"\t{key}: {evidence[key]}\n")
75 
76  logger.info("".join(message))
77 
78  # Add the evidence values to the flow data
79  data.evidence.add_from_dict(evidence)
80 
81  # Process the flow data.
82  data.process()
83 
84  message = []
85  message.append("Results:\n")
86 
87  # Now that it's been processed, the flow data will have
88  # been populated with the result. In this case, we want
89  # information about the device, which we can get by
90  # asking for a result matching named "device"
91  device = data.device
92 
93  # Display the results of the detection, which are called
94  # device properties. See the property dictionary at
95  # https://51degrees.com/developers/property-dictionary
96  # for details of all available properties.
97  self.outputValue("Mobile Device", device.ismobile, message);
98  self.outputValue("Platform Name", device.platformname, message);
99  self.outputValue("Platform Version", device.platformversion, message);
100  self.outputValue("Browser Name", device.browsername, message);
101  self.outputValue("Browser Version", device.browserversion, message);
102  logger.info("".join(message));
103 
104  def outputValue(self, name, value, message):
105  # Individual result values have a wrapper called
106  # `AspectPropertyValue`. This functions similarly to
107  # a null-able type.
108  # If the value has not been set then trying to access the
109  # `value` method will throw an exception.
110  # `AspectPropertyValue` also includes the `no_value_message`
111  # method, which describes why the value has not been set.
112  message.append(
113  f"\t{name}: {value.value()}\n" if value.has_value()
114  else f"\t{name}: {value.no_value_message()}\n")
115 
116 
117  # This collection contains the various input values that will
118  # be passed to the device detection algorithm.
119  EvidenceValues = [
120  # A User-Agent from a mobile device.
121  { "header.user-agent":
122  "Mozilla/5.0 (Linux; Android 9; SAMSUNG SM-G960U) "
123  "AppleWebKit/537.36 (KHTML, like Gecko) "
124  "SamsungBrowser/10.1 Chrome/71.0.3578.99 Mobile Safari/537.36" },
125  # A User-Agent from a desktop device.
126  { "header.user-agent":
127  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
128  "AppleWebKit/537.36 (KHTML, like Gecko) "
129  "Chrome/78.0.3904.108 Safari/537.36" },
130  # Evidence values from a windows 11 device using a browser
131  # that supports User-Agent Client Hints.
132  { "header.user-agent":
133  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
134  "AppleWebKit/537.36 (KHTML, like Gecko) "
135  "Chrome/98.0.4758.102 Safari/537.36",
136  "header.sec-ch-ua-mobile": "?0",
137  "header.sec-ch-ua":
138  "\" Not A; Brand\";v=\"99\", \"Chromium\";v=\"98\", "
139  "\"Google Chrome\";v=\"98\"",
140  "header.sec-ch-ua-platform": "\"Windows\"",
141  "header.sec-ch-ua-platform-version": "\"14.0.0\"" }
142  ]
143 
144 def main(argv):
145  # Use the command line args to get the resource key if present.
146  # Otherwise, get it from the environment variable.
147  resource_key = argv[0] if len(argv) > 0 else ExampleUtils.get_resource_key()
148 
149  # Configure a logger to output to the console.
150  logger = logging.getLogger("Getting Started")
151  logger.setLevel(logging.INFO)
152 
153  if (resource_key):
154  GettingStartedConsole().run(resource_key, logger)
155  else:
156  logger.error(
157  "No resource key specified in environment variable " +
158  f"'{ExampleUtils.RESOURCE_KEY_ENV_VAR}'. The 51Degrees " +
159  "cloud service is accessed using a 'ResourceKey'. " +
160  "For more detail see " +
161  "http://51degrees.com/documentation/4.3/_info__resource_keys.html. " +
162  "A resource key with the properties required by this " +
163  "example can be created for free at " +
164  "https://configure.51degrees.com/g3gMZdPY. " +
165  "Once complete, populated the environment variable " +
166  "mentioned at the start of this message with the key.")
167 
168 if __name__ == "__main__":
169  main(sys.argv[1:])