Device Detection services for 51Degrees Pipeline

onpremise/gettingstarted_web/app.py

This example is available in full on GitHub.

This example is available in full on GitHub.

This example requires a local data file. The free 'Lite' data file can be downloaded with the scripts in the data GitHub repository, which this repository includes at cxx/data. Fetch the submodules by running git submodule update --init --recursive, then run sh cxx/data/get-data-files.sh 51Degrees-LiteV4.1.hash from the repository root, which saves the file as cxx/data/device-detection/51Degrees-LiteV4.1.hash.

The Lite data file is only used for illustration, and has limited accuracy and capabilities. The Enterprise data file has every property. Contact us about a copy.

Required PyPi Dependencies:

Overview

The DeviceDetectionPipelineBuilder 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">
{% if utils.data_file_is_old(data.pipeline.get_element("device")) %}
<div class="c-eg-alert">
WARNING: This example is using a data file that is more than {{ utils.DATA_FILE_AGE_WARNING }}
days old. A more recent data file may be needed to correctly detect the latest devices,
browsers, etc. Get the latest lite data file with the scripts in the
<a href="https://github.com/51Degrees/data">data</a>
repository on GitHub. <a href="/contact-us?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-onpremise-gettingstarted_web-templates-index.html&utm_term=data-file-age">Contact us</a>
about the Enterprise data file, which includes automatic daily updates.
</div>
{% endif %}
<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("device").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_enterprise_value(data.pipeline.get_element("device"), 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_enterprise_value(data.pipeline.get_element("device"), 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_enterprise_value(data.pipeline.get_element("device"), 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_enterprise_value(data.pipeline.get_element("device"), 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_enterprise_value(data.pipeline.get_element("device"), 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_enterprise_value(data.pipeline.get_element("device"), 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_enterprise_value(data.pipeline.get_element("device"), 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_enterprise_value(data.pipeline.get_element("device"), 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_enterprise_value(data.pipeline.get_element("device"), 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_enterprise_value(data.pipeline.get_element("device"), 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_enterprise_value(data.pipeline.get_element("device"), 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>
{% if utils.get_data_file_tier(data.pipeline.get_element("device")) == "Lite" %}
<div class="c-eg-message">
<p class="c-eg-message__text">The paid data file adds daily automatic updates, non-human identification and IP intelligence. <a href="/contact-us?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-onpremise-gettingstarted_web-templates-index.html&utm_term=paid-data-file">Contact us</a> to explore the options.</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-onpremise-gettingstarted_web-templates-index.html&utm_term=paid-data-file">Contact us</a>
</div>
{% endif %}
</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.
# *********************************************************************
import os
from pathlib import Path
import sys
from flask.helpers import make_response
from flask import Flask, request, render_template
from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder
javascript_response, json_response, webevidence, set_response_header)
import json
class GettingStartedWeb():
app = Flask(__name__)
def build(self, config, 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
# 'suppress_process_exceptions' is set to True in config.json
# (PipelineOptions.BuildParameters) so a device-detection failure degrades
# gracefully instead of returning a 500 for every request. Use False while
# developing to surface mistakes loudly.
GettingStartedWeb.pipeline = PipelineBuilder().add_logger(logger).build_from_configuration(config)
return self
def run(self):
# The port can be set with the PORT environment variable, as it can
# for the cloud example, so the example can run next to other services.
# The pipeline lives as long as the app, and is closed when the server
# stops, which releases the native data it holds.
with GettingStartedWeb.pipeline:
GettingStartedWeb.app.run(port=int(os.environ.get("PORT", 5001)))
# 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 page. It is closed when the route
# returns, once the page has been rendered from it.
with GettingStartedWeb.pipeline.create_flowdata() as 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-onpremise-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
# Typically, something like this will not be necessary.
# The device detection API will accept an absolute or relative path for the data file.
# However, if a relative path is specified, it will only look in the current working
# directory.
# In our examples, we have many different projects and we don't want to have a copy of
# the data file for every single one.
# In order to handle this, we dynamically search the project directories for the data
# file location and then override the configured setting with the absolute path if
# necessary.
# In a real-world scenario, you can just put the data file in your working directory
# or use an absolute path in the configuration file.
@staticmethod
def build_config():
# Load the configuration file
configFile = Path(__file__).resolve().parent.joinpath("config.json").read_text()
config = json.loads(configFile)
# A data file named in the _51DEGREES_DD_PATH environment variable takes
# the place of the one in config.json. This lets the example run
# against a paid data file without editing the configuration.
envDataFile = ExampleUtils.get_data_file_path()
if envDataFile:
envDataFile = os.path.abspath(envDataFile)
if not os.path.exists(envDataFile):
raise Exception("The device detection data file " +
f"'{envDataFile}' named in the environment variable " +
f"'{ExampleUtils.DD_PATH_ENV_VAR}' does not exist.")
ExampleUtils.set_data_file_in_config(config, envDataFile)
return config
dataFile = ExampleUtils.get_data_file_from_config(config)
foundDataFile = False
if not dataFile:
raise Exception("A data file must be specified in the config.json file.")
# The data file location provided in the configuration may be using an absolute or
# relative path. If it is relative then search for a matching file using the
# ExampleUtils.find_file function.
elif os.path.isabs(dataFile) == False:
newPath = ExampleUtils.find_file(dataFile)
if newPath:
# Add an override for the absolute path to the data file.
ExampleUtils.set_data_file_in_config(config, newPath)
foundDataFile = True
else:
foundDataFile = os.path.exists(dataFile)
if foundDataFile == False:
raise Exception("Failed to find a device detection data file matching " +
f"'{dataFile}'. If using the lite file, then make sure the " +
"data submodule is there, by running " +
"`git submodule update --init --recursive`, and run this " +
"example again to download the file. Otherwise, ensure that the filename " +
"is correct in config.json, or set the environment variable " +
f"'{ExampleUtils.DD_PATH_ENV_VAR}' to the path of the data file.")
return config
def main(argv):
# Configure a logger to output to the console.
logger = Logger(min_level="info")
config = GettingStartedWeb.build_config()
GettingStartedWeb().build(config, logger).run()
if __name__ == "__main__":
main(sys.argv[1:])
Definition onpremise/build/__init__.py:1