\r\n

51Degrees Device Detection Python  4.3

Device Detection services for 51Degrees Pipeline

cloud/useragentclienthints-web.py

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.

Expected output:

1 User Agent Client Hints Example
2 
3 Hardware Vendor: Unknown
4 Hardware Name: Array
5 Device Type: Desktop
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 
39 
40 from flask.helpers import make_response
41 from fiftyone_devicedetection_cloud.devicedetection_cloud_pipelinebuilder import DeviceDetectionCloudPipelineBuilder
42 from fiftyone_pipeline_core.web import *
43 
44 # You need to create a resource key at https://configure.51degrees.com
45 # and paste it into the code, replacing !!YOUR_RESOURCE_KEY!! below.
46 # Alternatively, add a resource_key environment variable
47 import os
48 if "resource_key" in os.environ:
49  resource_key = os.environ["resource_key"]
50 else:
51  resource_key = "!!YOUR_RESOURCE_KEY!!"
52 
53 if resource_key == "!!YOUR_RESOURCE_KEY!!":
54  print("""
55  You need to create a resource key at
56  https://configure.51degrees.com and paste it into the code,
57  'replacing !!YOUR_RESOURCE_KEY!!
58  To include the properties used in this example, go to https://configure.51degrees.com/
59  """)
60 else:
61 
62  # First create the device detection pipeline with the desired settings and include required UACH SetHeader properties which are in the following format
63  # SetHeader[Component name][Response header name]
64  # e.g. for browser component properties to be set in Accept-CH response header use following property
65  # SetHeaderBrowserAccept-CH
66 
67  pipeline = DeviceDetectionCloudPipelineBuilder({
68  "resource_key": resource_key
69  }).build()
70 
71  from flask import Flask, request
72 
73  app = Flask(__name__)
74 
75  # Helper function to get a property value if it exists and return
76  # the reason why if it doesn't
77 
78  def get_value_helper(flowdata, engine, property_key):
79 
80  engine_properties = getattr(flowdata, engine)
81 
82  try:
83  property_value = getattr(engine_properties, property_key)
84 
85  if property_value.has_value():
86  return property_value.value()
87  else:
88  return property_value.no_value_message()
89  except:
90  return "Not found in cloud"
91 
92  # Create a main route for the device detections
93 
94  @app.route('/')
95  def server():
96 
97  # Create the flowdata object for the device detection
98 
99  flowdata = pipeline.create_flowdata()
100 
101  # Add any information from the request (headers, cookies and any other additional information)
102 
103  flowdata.evidence.add_from_dict(webevidence(request))
104 
105  # Process the flowdata
106 
107  flowdata.process()
108 
109  # Generate the HTML
110 
111  output = "<h2>User Agent Client Hints Example</h2>"
112 
113  output += """
114 
115  <p>
116  By default, the user-agent, sec-ch-ua and sec-ch-ua-mobile HTTP headers
117  are sent.
118  <br />
119  This means that on the first request, the server can determine the
120  browser from sec-ch-ua while other details must be derived from the
121  user-agent.
122  <br />
123  If the server determines that the browser supports client hints, then
124  it may request additional client hints headers by setting the
125  Accept-CH header in the response.
126  <br />
127  Select the <strong>Make second request</strong> button below,
128  to use send another request to the server. This time, any
129  additional client hints headers that have been requested
130  will be included.
131  </p>
132 
133  <button type="button" onclick="redirect()">Make second request</button>
134  <script>
135 
136  // This script will run when button will be clicked and device detection request will again
137  // be sent to the server with all additional client hints that was requested in the previous
138  // response by the server.
139  // Following sequence will be followed.
140  // 1. User will send the first request to the web server for detection.
141  // 2. Web Server will return the properties in response based on the headers sent in the request. Along
142  // with the properties, it will also send a new header field Accept-CH in response indicating the additional
143  // evidence it needs. It builds the new response header using SetHeader[Component name]Accept-CH properties
144  // where Component Name is the name of the component for which properties are required.
145  // 3. When "Make second request" button will be clicked, device detection request will again
146  // be sent to the server with all additional client hints that was requested in the previous
147  // response by the server.
148  // 4. Web Server will return the properties based on the new User Agent CLient Hint headers
149  // being used as evidence.
150 
151  function redirect() {
152  sessionStorage.reloadAfterPageLoad = true;
153  window.location.reload(true);
154  }
155 
156  window.onload = function () {
157  if ( sessionStorage.reloadAfterPageLoad ) {
158  document.getElementById('description').innerHTML = "<p>The information shown below is determined using <strong>User Agent Client Hints</strong> that was sent in the request to obtain additional evidence. If no additional information appears then it may indicate an external problem such as <strong>User Agent Client Hints</strong> being disabled in your browser.</p>";
159  sessionStorage.reloadAfterPageLoad = false;
160  }
161  else{
162  document.getElementById('description').innerHTML = "<p>The following values are determined by sever-side device detection on the first request.</p>";
163  }
164  }
165 
166  </script>
167 
168  <div id="evidence">
169  <strong></br>Evidence values used: </strong>
170  <table>
171  <tr>
172  <th>Key</th>
173  <th>Value</th>
174  </tr>
175 
176  """
177  evidences = pipeline.get_element("cloud").filter_evidence(flowdata)
178  for key, value in evidences.items():
179  if ("header.user-agent" in key or "header.sec-ch" in key):
180  output += "<tr>"
181  output += "<td>" + str(key) + "</td>"
182  output += "<td>" + str(value) + "</td>"
183  output += "</>"
184  output += "</table>"
185  output += "</div>"
186 
187  output += "<div id=description></div>"
188  output += "<div id=\"content\">"
189  output += "<strong>Detection results:</strong></br>"
190  output += "<p>"
191  output += "<b>Hardware Vendor:</b> " + str(get_value_helper(flowdata, "device", "hardwarevendor"))
192  output += "<br />"
193  output += "<b>Hardware Name:</b> " + str(get_value_helper(flowdata, "device", "hardwarename"))
194  output += "<br />"
195  output += "<b>Device Type:</b> " + str(get_value_helper(flowdata, "device", "devicetype"))
196  output += "<br />"
197  output += "<b>Platform Vendor:</b> " + str(get_value_helper(flowdata, "device", "platformvendor"))
198  output += "<br />"
199  output += "<b>Platform Name:</b> " + str(get_value_helper(flowdata, "device", "platformname"))
200  output += "<br />"
201  output += "<b>Platform Version:</b> " + str(get_value_helper(flowdata, "device", "platformversion"))
202  output += "<br />"
203  output += "<b>Browser Vendor:</b> " + str(get_value_helper(flowdata, "device", "browservendor"))
204  output += "<br />"
205  output += "<b>Browser Name:</b> " + str(get_value_helper(flowdata, "device", "browsername"))
206  output += "<br />"
207  output += "<b>Browser Version:</b> " + str(get_value_helper(flowdata, "device", "browserversion"))
208  output += "<br /></div>"
209 
210  # Create a response variable and add response object
211 
212  response = make_response(output)
213 
214  # Some browsers require that extra HTTP headers are explicitly
215  # requested. So set whatever headers are required by the browser in
216  # order to return the evidence needed by the pipeline.
217  # More info on this can be found at
218  # https://51degrees.com/blog/user-agent-client-hints
219 
220  response = set_response_header(flowdata, response)
221 
222  return response