\r\n

51Degrees Device Detection Python  4.3

Device Detection services for 51Degrees Pipeline

cloud/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.

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 
27 
28 from flask.helpers import make_response
29 from fiftyone_devicedetection_cloud.devicedetection_cloud_pipelinebuilder import DeviceDetectionCloudPipelineBuilder
30 from fiftyone_pipeline_core.web import *
31 import json
32 
33 # First create the device detection pipeline with the desired settings.
34 
35 # You need to create a resource key at https://configure.51degrees.com
36 # and paste it into the code, replacing !!YOUR_RESOURCE_KEY!! below.
37 # Alternatively, add a resource_key environment variable
38 import os
39 if "resource_key" in os.environ:
40  resource_key = os.environ["resource_key"]
41 else:
42  resource_key = "!!YOUR_RESOURCE_KEY!!"
43 
44 if resource_key == "!!YOUR_RESOURCE_KEY!!":
45  print("""
46  You need to create a resource key at
47  https://configure.51degrees.com and paste it into the code,
48  'replacing !!YOUR_RESOURCE_KEY!!
49  make sure to include the HardwareName, HardwareProfile and HardwareVendor, DeviceType,
50  PlatformVendor, PlatformName, BrowserVendor, BrowserName, BrowserVersion, ScreenWidth
51  and ScreenHeight properties used by this example
52  """)
53 else:
54 
55  # 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
56 
57  javascript_builder_settings = {
58  "endpoint": "/json"
59  }
60 
61  pipeline = DeviceDetectionCloudPipelineBuilder({
62  "resource_key": resource_key,
63  "javascript_builder_settings": javascript_builder_settings
64  }).build()
65 
66  from flask import Flask, request
67 
68  app = Flask(__name__)
69 
70  # First we make a JSON route that will be called from the client side and will return
71  # a JSON encoded property database using any additional evidence provided by the client
72 
73  @app.route('/json', methods=['POST'])
74  def jsonroute():
75 
76  # Create the flowdata object for the JSON route
77  flowdata = pipeline.create_flowdata()
78 
79  # Add any information from the request (headers, cookies and additional
80  # client side provided information)
81 
82  flowdata.evidence.add_from_dict(webevidence(request))
83 
84  # Process the flowdata
85 
86  flowdata.process()
87 
88  # Return the JSON from the JSONBundler engine
89 
90  return json.dumps(flowdata.jsonbundler.json)
91 
92  # Helper function to get a property value if it exists and return
93  # the reason why if it doesn't
94  def get_value_helper(flowdata, engine, property_key):
95 
96  engine_properties = getattr(flowdata, engine)
97 
98  property_value = getattr(engine_properties, property_key)
99 
100  if property_value.has_value():
101  return property_value.value()
102  else:
103  return property_value.no_value_message()
104 
105  # In the main route we dynamically update the screen's device property display
106  # using the above JSON route
107 
108  @app.route('/')
109  def server():
110 
111  # Create the flowdata object for the JSON route
112  flowdata = pipeline.create_flowdata()
113 
114  # Add any information from the request (headers, cookies and additional
115  # client side provided information)
116 
117  flowdata.evidence.add_from_dict(webevidence(request))
118 
119  # Process the flowdata
120 
121  flowdata.process()
122 
123  # Generate the HTML
124 
125  output = "<h1>Client side evidence</h1>"
126 
127  # Add the JavaScript created by the pipeline
128  output += "<script>"
129  output += flowdata.javascriptbuilder.javascript
130  output += "</script>"
131 
132  # Print results from server side processing
133  output += "<p><b>The following values are determined by sever-side device detection on the first request:</b></p>"
134 
135  output += "<b>Hardware Vendor:</b> " + get_value_helper(flowdata, "device", "hardwarevendor")
136  output += "<br />"
137  output += "<b>Hardware Name:</b> " + str(get_value_helper(flowdata, "device", "hardwarename"))
138  output += "<br />"
139  output += "<b>Device Type:</b> " + get_value_helper(flowdata, "device", "devicetype")
140  output += "<br />"
141  output += "<b>Platform Vendor:</b> " + get_value_helper(flowdata, "device", "platformvendor")
142  output += "<br />"
143  output += "<b>Platform Name:</b> " + get_value_helper(flowdata, "device", "platformname")
144  output += "<br />"
145  output += "<b>Browser Vendor:</b> " + get_value_helper(flowdata, "device", "browservendor")
146  output += "<br />"
147  output += "<b>Browser Name:</b> " + get_value_helper(flowdata, "device", "browsername")
148  output += "<br />"
149  output += "<b>Browser Version:</b> " + get_value_helper(flowdata, "device", "browserversion")
150  output += "<br />"
151  output += "<b>Screen width (pixels):</b> " + str(get_value_helper(flowdata, "device", "screenpixelswidth"))
152  output += "<br />"
153  output += "<b>Screen height (pixels):</b> " + str(get_value_helper(flowdata, "device", "screenpixelsheight"))
154 
155 
156  output += """
157 
158  <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>
159 
160  <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>
161 
162  <p id=hardwarename></p>
163  <p id=screenpixelwidth></p>
164  <p id=screenpixelheight></p>
165  <script>
166  window.onload = function(){
167  fod.complete(function (data) {
168  if(data.device["hardwarename"]){
169  document.getElementById('hardwarename').innerHTML = "<strong>Updated Hardware Name from client-side evidence:</strong> " + data.device["hardwarename"];
170  }
171  document.getElementById('screenpixelwidth').innerHTML = "<strong>Screen width (pixels): " + data.device.screenpixelswidth + "</strong>"
172  document.getElementById('screenpixelheight').innerHTML = "<strong>Screen height (pixels): " + data.device.screenpixelsheight + "</strong>"
173  });
174  }
175  </script>
176  """
177 
178  # Create a response variable and add response object
179  response = make_response(output)
180 
181  # Some browsers require that extra HTTP headers are explicitly
182  # requested. So set whatever headers are required by the browser in
183  # order to return the evidence needed by the pipeline.
184  # More info on this can be found at
185  # https://51degrees.com/blog/user-agent-client-hints
186 
187  response = set_response_header(flowdata, response)
188 
189  return response