Device Detection services for 51Degrees Pipeline

cloud/gettingstarted_web/app.py

This example is available in full on GitHub.

This example is available in full on GitHub.

To run this example, you will need to create a Resource Key. The Resource Key stores your selected properties and any associated License Keys that allow more requests or access to paid properties.

You can create a Resource Key at configure.51degrees.com.

Required PyPi Dependencies:

Overview

The DeviceDetectionCloudPipelineBuilder class is used to create a Pipeline instance from the configuration that is supplied. The fiftyone_pipeline_core.web module contains helpers which deal with automatically populating evidence from a web request.

flowdata.evidence.add_from_dict(webevidence(request))

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.

set_response_header(flowdata, response)

The results of detection can be accessed by through the flowdata object once processed. This can then be used to interrogate the data.

flowdata.process()
device = flowdata.device
hardware_vendor = device.hardwarevendor

Results can also be accessed in client-side code by using the fod object. See the JavascriptBuilderElement for details on available settings such as changing the fod name.

window.onload = function () {
fod.complete(function(data) {
var hardwareName = data.device.hardwarename;
alert(hardwareName.join(", "));
}
}

View

{#
*********************************************************************
* 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>

App

# *********************************************************************
# This Original Work is copyright of 51 Degrees Mobile Experts Limited.
# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House,
# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU.
#
# 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.
# *********************************************************************
from flask import Flask, request, render_template
from flask.helpers import make_response
from fiftyone_devicedetection_cloud.devicedetection_cloud_pipelinebuilder import DeviceDetectionCloudPipelineBuilder
javascript_response, json_response, webevidence, set_response_header)
import os
import sys
class GettingStartedWeb():
app = Flask(__name__)
def build(self, resource_key, logger):
# 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
javascript_builder_settings = {
"endpoint": "/json",
"minify": True,
# The enable_cookies setting is needed if you want to work with results from client-side
# evidence on the server. For example, precise Apple models or screen dimensions.
# This will store the results of client-side detection scripts on the client as cookies.
# On subsequent requests, these cookies will be included in the payload and will be
# used by the device detection API when it runs.
"enable_cookies": True
}
pipeline_settings = {
"resource_key": resource_key,
"javascript_builder_settings": javascript_builder_settings,
# Set to True so a device-detection failure degrades gracefully instead of
# returning a 500 for every request. Use False while developing to surface
# mistakes loudly. Errors are still recorded on flowdata.errors / the logger.
"suppress_process_exceptions": True,
}
# If a cloud endpoint is set in the environment, point the pipeline at it.
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)))
# First we make a JSON route that will be called from the client side and will return
# a JSON encoded property database using any additional evidence provided by the client.
# json_response processes the request and sets the cache headers, so a browser keeps a
# good answer for 30 minutes and never keeps one made while processing failed.
@staticmethod
@app.route('/json', methods=['POST'])
def jsonroute():
return json_response(GettingStartedWeb.pipeline, request)
# Next we serve the client-side JavaScript from its own route. The other
# Pipeline APIs ship a web integration that intercepts '/51Degrees.core.js'
# for this, so the page can reference the script by that name. There is no
# such integration for Flask, so the example wires up the route itself.
# Query parameters are evidence, so the per-request 'fod-js-enable-cookies'
# override is picked up and applied by the JavaScriptBuilder engine.
@staticmethod
@app.route('/51Degrees.core.js')
def core_js():
return javascript_response(GettingStartedWeb.pipeline, request)
# In the main route we dynamically update the screen's device property display
# using the above JSON route
@staticmethod
@app.route('/')
def server():
# Create the flowdata object for the JSON route
flowdata = GettingStartedWeb.pipeline.create_flowdata()
# Add any information from the request (headers, cookies and additional
# client side provided information)
flowdata.evidence.add_from_dict(webevidence(request))
# Process the flowdata
flowdata.process()
response = make_response()
# Some browsers require that extra HTTP headers are explicitly
# requested. So set whatever headers are required by the browser in
# order to return the evidence needed by the pipeline.
# More info on this can be found at
# /blog/user-agent-client-hints?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=server
set_response_header(flowdata, response)
# Generate the HTML
response.set_data(render_template(
'index.html',
data=flowdata,
utils=ExampleUtils,
response=response))
return response
def main(argv):
# Use the command line args to get the resource key if present.
# Otherwise, get it from the environment variable.
resource_key = argv[0] if len(argv) > 0 else ExampleUtils.get_resource_key()
# Configure a logger to output to the console.
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