51Degrees Device Detection Python  4.1

Device Detection services for 51Degrees Pipeline

cloud/web.py

This example demonstrates how to enhance results by incorporating evidence from client-side JavaScript. This approach is required to perform certain tasks such as identify iPhone and iPad models or get the screen resolution for a desktop device.

Properties containing JavaScript snippets are populated by engines in the Pipeline and these are then bundled together into a single JavaScript block by the 'JsonBuilder' and 'JavaScriptBuilder' elements. This JavaScript is then used to obtain the additional evidence from the client and pass it back to the server. The updated results can then be used immediately on the client-side or on subsequent requests to the server.

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.

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 
24 
29 
30 from fiftyone_devicedetection.devicedetection_pipelinebuilder import DeviceDetectionPipelineBuilder
31 from fiftyone_pipeline_core.web import webevidence
32 import json
33 
34 # First create the device detection pipeline with the desired settings.
35 
36 # You need to create a resource key at https://configure.51degrees.com
37 # and paste it into the code, replacing !!YOUR_RESOURCE_KEY!! below.
38 
39 resourceKey = "!!YOUR_RESOURCE_KEY!!"
40 
41 if resourceKey == "!!YOUR_RESOURCE_KEY!!":
42  print("""
43  You need to create a resource key at
44  https://configure.51degrees.com and paste it into the code,
45  'replacing !!YOUR_RESOURCE_KEY!!
46  To get a resourcekey with the properties used in this example go to https://configure.51degrees.com/fzzSBD8R
47  """)
48 else:
49 
50  # Here we add some callback settings for the page to make a request with extra evidence from the client side, in this case the Flask /json route we will make below
51 
52  javascriptBuilderSettings = {
53  "endpoint": "/json"
54  }
55 
56  pipeline = DeviceDetectionPipelineBuilder({"resourceKey": resourceKey, "javascriptBuilderSettings": javascriptBuilderSettings}).build()
57 
58  from flask import Flask, request
59 
60  app = Flask(__name__)
61 
62  # First we make a JSON route that will be called from the client side and will return
63  # a JSON encoded property database using any additional evidence provided by the client
64 
65  @app.route('/json', methods=['POST'])
66  def jsonroute():
67 
68  # Create the flowData object for the JSON route
69  flowData = pipeline.create_flowdata()
70 
71  # Add any information from the request (headers, cookies and additional
72  # client side provided information)
73 
74  flowData.evidence.add_from_dict(webevidence(request))
75 
76  # Process the flowData
77 
78  flowData.process()
79 
80  # Return the JSON from the JSONBundler engine
81 
82  return json.dumps(flowData.jsonbundler.json)
83 
84  # Helper function to get a property value if it exists and return
85  # the reason why if it doesn't
86  def getValueHelper(flowdata, engine, propertyKey):
87 
88  engineProperties = getattr(flowdata, engine)
89 
90  propertyValue = getattr(engineProperties, propertyKey)
91 
92  if propertyValue.has_value():
93  return propertyValue.value()
94  else:
95  return propertyValue.no_value_message()
96 
97  # In the main route we dynamically update the screen's device property display
98  # using the above JSON route
99 
100  @app.route('/')
101  def server():
102 
103  # Create the flowData object for the JSON route
104  flowData = pipeline.create_flowdata()
105 
106  # Add any information from the request (headers, cookies and additional
107  # client side provided information)
108 
109  flowData.evidence.add_from_dict(webevidence(request))
110 
111  # Process the flowData
112 
113  flowData.process()
114 
115  # Generate the HTML
116 
117  output = "<h1>Client side evidence</h1>"
118 
119  # Add the JavaScript created by the pipeline
120  output += "<script>"
121  output += flowData.javascriptbuilder.javascript
122  output += "</script>"
123 
124  # Print results from server side processing
125  output += "<p><b>The following values are determined by sever-side device detection on the first request:</b></p>"
126 
127  output += "<b>Hardware Vendor:</b> " + getValueHelper(flowData, "device", "hardwarevendor")
128  output += "<br />"
129  output += "<b>Hardware Name:</b> " + str(getValueHelper(flowData, "device", "hardwarename"))
130  output += "<br />"
131  output += "<b>Device Type:</b> " + getValueHelper(flowData, "device", "devicetype")
132  output += "<br />"
133  output += "<b>Platform Vendor:</b> " + getValueHelper(flowData, "device", "platformvendor")
134  output += "<br />"
135  output += "<b>Platform Name:</b> " + getValueHelper(flowData, "device", "platformname")
136  output += "<br />"
137  output += "<b>Browser Vendor:</b> " + getValueHelper(flowData, "device", "browservendor")
138  output += "<br />"
139  output += "<b>Browser Name:</b> " + getValueHelper(flowData, "device", "browsername")
140  output += "<br />"
141  output += "<b>Browser Version:</b> " + getValueHelper(flowData, "device", "browserversion")
142  output += "<br />"
143  output += "<b>Screen width (pixels):</b> " + str(getValueHelper(flowData, "device", "screenpixelswidth"))
144  output += "<br />"
145  output += "<b>Screen height (pixels):</b> " + str(getValueHelper(flowData, "device", "screenpixelsheight"))
146 
147 
148  output += """
149 
150  <p>The information shown below is determined from JavaScript running on the client-side that is able to obtain additional evidence. If no additional information appears then it may indicate an external problem such as JavaScript being disabled in your browser.</p>
151 
152  <p>Note that the 'Hardware Name' field is intended to illustrate detection of Apple device models as this cannot be determined server-side. This can be tested to some extent using most emulators such as those in the 'developer tools' menu in Google Chrome. However, using real devices will result in more precise model numbers.</p>
153 
154  <p id=hardwarename></p>
155  <p id=screenpixelwidth></p>
156  <p id=screenpixelheight></p>
157  <script>
158  window.onload = function(){
159  fod.complete(function (data) {
160  if(data.device["hardwarename"]){
161  document.getElementById('hardwarename').innerHTML = "<strong>Updated Hardware Name from client-side evidence:</strong> " + data.device["hardwarename"];
162  }
163  document.getElementById('screenpixelwidth').innerHTML = "<strong>Screen width (pixels): " + data.device.screenpixelswidth + "</strong>"
164  document.getElementById('screenpixelheight').innerHTML = "<strong>Screen height (pixels): " + data.device.screenpixelsheight + "</strong>"
165  });
166  }
167  </script>
168  """
169 
170  return output