The module can also handling setting response headers (e.g. Accept-CH for User-Agent Client Hints) and serving requests for client-side JavaScript and JSON resources.
The results of detection can be accessed by through the flowdata object once processed. This can then be used to interrogate the data.
{#
*********************************************************************
* This Original Work is copyright of 51 Degrees Mobile Experts Limited.
* Copyright 2022 51 Degrees Mobile Experts Limited, 5 Charlotte Close,
* Caversham, Reading, Berkshire, United Kingdom RG4 7BY.
*
* This Original Work is licensed under the European Union Public Licence (EUPL)
* v.1.2 and is subject to its terms as set out below.
*
* If a copy of the EUPL was not distributed with this file, You can obtain
* one at https://opensource.org/licenses/EUPL-1.2.
*
* The 'Compatible Licences' set out in the Appendix to the EUPL (as may be
* amended by the European Commission) shall be deemed incompatible for
* the purposes of the Work and the provisions of the compatibility
* clause in Article 5 of the EUPL shall not apply.
*
* If using the Work as, or as part of, a network application, by
* including the attribution notice(s) required under Article 5 of the EUPL
* in the end user terms of the application under an appropriate heading,
* such notice(s) shall fulfill the requirements of that article.
* ********************************************************************* #}
<head>
<title>Web Integration Example</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/examples-main.min.css') }}">
</head>
<div class="c-eg-page">
<h2 class="c-eg-page__title">Web integration example</h2>
<p class="c-eg-page__lead">
This example demonstrates the use of the Pipeline API to perform device detection within a
simple Flask web project. It highlights automatic handling of the Accept-CH header, used to
request User-Agent Client Hints from the browser, and client-side evidence collection to
identify Apple device models and properties such as screen size.
</p>
<p class="c-eg-page__lead">
When the first request is made, browsers that support client hints will typically send a
subset of client hints values along with the User-Agent header. If device detection determines
that the browser does support client hints then it will request that additional client hints
headers are sent with future requests by sending the Accept-CH header with the response. Note
that if you have visited this page previously the Accept-CH value will have been cached, so all
requested headers will be sent on the first request. Private browsing or incognito mode will
let you see the true first request experience.
</p>
<noscript>
<div class="c-eg-alert">
WARNING: JavaScript is disabled in your browser. This means that the callback discussed
further down this page will not fire and UACH headers will not be sent.
</div>
</noscript>
<div id="content">
<h3 class="c-eg-page__heading">Response headers</h3>
<p class="c-eg-page__lead">The following response headers were set.</p>
<table class="c-eg-table">
<thead class="c-eg-table__head">
<tr class="c-eg-table__row">
<th class="c-eg-table__cell">Key</th>
<th class="c-eg-table__cell">Value</th>
</tr>
</thead>
<tbody>
{% for key, value in response.headers.items() %}
<tr class="c-eg-table__row c-eg-table__row--present">
<td class="c-eg-table__cell c-eg-table__cell--key">{{ key }}</td>
<td class="c-eg-table__cell">{{ value }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% if "Accept-CH" not in response.headers %}
<div class="c-eg-alert">
WARNING: There is no Accept-CH header in the response. This may indicate that your
browser does not support User-Agent Client Hints. This is not necessarily a problem,
but if you want to try detection using User-Agent Client Hints, make sure your browser
<a href="https://developer.mozilla.org/en-US/docs/Web/API/User-Agent_Client_Hints_API#browser_compatibility">supports them</a>.
</div>
{% endif %}
<h3 class="c-eg-page__heading">Evidence used</h3>
<p class="c-eg-legend">
Evidence was
<span class="c-eg-legend__swatch c-eg-legend__swatch--used">used</span>
/
<span class="c-eg-legend__swatch c-eg-legend__swatch--present">present</span>
for detection
</p>
<table class="c-eg-table">
<thead class="c-eg-table__head">
<tr class="c-eg-table__row">
<th class="c-eg-table__cell">Key</th>
<th class="c-eg-table__cell">Value</th>
</tr>
</thead>
<tbody>
{% for key, value in data.evidence.get_all().items() %}
{% if data.pipeline.get_element("cloud").get_evidence_key_filter().filter_evidence_key(key) %}
<tr class="c-eg-table__row c-eg-table__row--used">
{% else %}
<tr class="c-eg-table__row c-eg-table__row--present">
{% endif %}
<td class="c-eg-table__cell c-eg-table__cell--key">{{ key }}</td>
<td class="c-eg-table__cell">{{ value }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<h3 class="c-eg-page__heading">Device data</h3>
<p class="c-eg-page__lead">
The following values are determined by server-side device detection on the first request.
</p>
<table class="c-eg-table">
<thead class="c-eg-table__head">
<tr class="c-eg-table__row">
<th class="c-eg-table__cell">Key</th>
<th class="c-eg-table__cell">Value</th>
</tr>
</thead>
<tbody>
<tr class="c-eg-table__row c-eg-table__row--alt"><td class="c-eg-table__cell c-eg-table__cell--key">Hardware Vendor:</td><td class="c-eg-table__cell">{{ utils.get_human_readable(data.device, "hardwarevendor") }}</td></tr>
<tr class="c-eg-table__row"><td class="c-eg-table__cell c-eg-table__cell--key">Hardware Name:</td><td class="c-eg-table__cell">{{ utils.get_human_readable(data.device, "hardwarename") }}</td></tr>
<tr class="c-eg-table__row c-eg-table__row--alt"><td class="c-eg-table__cell c-eg-table__cell--key">Device Type:</td><td class="c-eg-table__cell">{{ utils.get_human_readable(data.device, "devicetype") }}</td></tr>
<tr class="c-eg-table__row"><td class="c-eg-table__cell c-eg-table__cell--key">Platform Vendor:</td><td class="c-eg-table__cell">{{ utils.get_human_readable(data.device, "platformvendor") }}</td></tr>
<tr class="c-eg-table__row c-eg-table__row--alt"><td class="c-eg-table__cell c-eg-table__cell--key">Platform Name:</td><td class="c-eg-table__cell">{{ utils.get_human_readable(data.device, "platformname") }}</td></tr>
<tr class="c-eg-table__row"><td class="c-eg-table__cell c-eg-table__cell--key">Platform Version:</td><td class="c-eg-table__cell">{{ utils.get_human_readable(data.device, "platformversion") }}</td></tr>
<tr class="c-eg-table__row c-eg-table__row--alt"><td class="c-eg-table__cell c-eg-table__cell--key">Browser Vendor:</td><td class="c-eg-table__cell">{{ utils.get_human_readable(data.device, "browservendor") }}</td></tr>
<tr class="c-eg-table__row"><td class="c-eg-table__cell c-eg-table__cell--key">Browser Name:</td><td class="c-eg-table__cell">{{ utils.get_human_readable(data.device, "browsername") }}</td></tr>
<tr class="c-eg-table__row c-eg-table__row--alt"><td class="c-eg-table__cell c-eg-table__cell--key">Browser Version:</td><td class="c-eg-table__cell">{{ utils.get_human_readable(data.device, "browserversion") }}</td></tr>
<tr class="c-eg-table__row"><td class="c-eg-table__cell c-eg-table__cell--key">Screen width (pixels):</td><td class="c-eg-table__cell">{{ utils.get_human_readable(data.device, "screenpixelswidth") }}</td></tr>
<tr class="c-eg-table__row c-eg-table__row--alt"><td class="c-eg-table__cell c-eg-table__cell--key">Screen height (pixels):</td><td class="c-eg-table__cell">{{ utils.get_human_readable(data.device, "screenpixelsheight") }}</td></tr>
{# The device id identifies the matched hardware, platform and browser profiles,
so it is the compact form of everything else in this table. #}
<tr class="c-eg-table__row"><td class="c-eg-table__cell c-eg-table__cell--key">Device Id:</td><td class="c-eg-table__cell">{{ utils.get_human_readable(data.device, "deviceid") }}</td></tr>
</tbody>
</table>
<h3 class="c-eg-page__heading">Client-side evidence and Apple models</h3>
<p class="c-eg-page__lead">
The information below is determined after a callback to the server with additional evidence
gathered by JavaScript on the client. The callback also includes any additional client hints
headers that have been requested. For Apple devices the server cannot tell the exact model,
so the callback shows a smaller set of possible models than the first request. To work with
these values on the server, the 'enable_cookies' setting must be 'True' as in this example,
which stores the additional client-side evidence as cookies. Refreshing the page then shows
the refined values appear in the server-side results.
</p>
</div>
<div class="c-eg-message">
<p class="c-eg-message__text">Want to try on-premise? <a href="/contact-us?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-cloud-gettingstarted_web-templates-index.html&utm_term=try-on-premise">Contact us</a> to discuss requirements.</p>
<a class="b-btn c-eg-message__cta" href="/contact-us?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-cloud-gettingstarted_web-templates-index.html&utm_term=try-on-premise">Contact us</a>
</div>
</div>
{#
51Degrees.core.js is built by the fiftyone_pipeline_core package and served by the
matching route in app.py. It includes a JSON representation of the contents of flow
data, i.e. the results from device detection, and raises the 'complete' event with the
refined flow data. The shared examples.js helper subscribes to it and appends a results
table into #content.
#}
<script src="/51Degrees.core.js"></script>
<script src="{{ url_for('static', filename='js/examples.min.js') }}"></script>
<script>
window.onload = function () {
fodExamples.bindDeviceCallback({ targetId: "content" });
};
</script>
from flask import Flask, request, render_template
from flask.helpers import make_response
javascript_response, json_response, webevidence, set_response_header)
import os
import sys
class GettingStartedWeb():
app = Flask(__name__)
def build(self, resource_key, logger):
javascript_builder_settings = {
"endpoint": "/json",
"minify": True,
"enable_cookies": True
}
pipeline_settings = {
"resource_key": resource_key,
"javascript_builder_settings": javascript_builder_settings,
"suppress_process_exceptions": True,
}
cloud_endpoint = ExampleUtils.get_cloud_endpoint()
if cloud_endpoint:
pipeline_settings["cloud_endpoint"] = cloud_endpoint
GettingStartedWeb.pipeline = DeviceDetectionCloudPipelineBuilder(
**pipeline_settings).add_logger(logger).
build()
return self
def run(self):
GettingStartedWeb.app.run(port=int(os.environ.get("PORT", 5000)))
@staticmethod
@app.route('/json', methods=['POST'])
def jsonroute():
return json_response(GettingStartedWeb.pipeline, request)
@staticmethod
@app.route('/51Degrees.core.js')
def core_js():
return javascript_response(GettingStartedWeb.pipeline, request)
@staticmethod
@app.route('/')
def server():
flowdata = GettingStartedWeb.pipeline.create_flowdata()
flowdata.evidence.add_from_dict(webevidence(request))
flowdata.process()
response = make_response()
set_response_header(flowdata, response)
response.set_data(render_template(
'index.html',
data=flowdata,
utils=ExampleUtils,
response=response))
return response
def main(argv):
resource_key = argv[0] if len(argv) > 0 else ExampleUtils.get_resource_key()
logger = Logger(min_level="info")
if (resource_key):
GettingStartedWeb().
build(resource_key, logger).run()
else:
logger.log("error",
"No resource key specified in environment variable " +
f"'{ExampleUtils.RESOURCE_KEY_ENV_VAR}'. The 51Degrees " +
"cloud service is accessed using a 'ResourceKey'. " +
"For more detail see " +
"/documentation/_services__cloud__resource_keys.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-cloud-gettingstarted_web-app.py&utm_term=resource-key-required. " +
"A resource key with the properties required by this " +
"example can be created for free at " +
"https://configure.51degrees.com/g3gMZdPY?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-cloud-gettingstarted_web-app.py&utm_term=resource-key-required. " +
"Once complete, populated the environment variable " +
"mentioned at the start of this message with the key.")
if __name__ == "__main__":
main(sys.argv[1:])
Definition onpremise/build/__init__.py:1
Definition devicedetection_cloud_pipelinebuilder.py:1
Definition example_utils.py:1