Device Detection services for 51Degrees Pipeline

onpremise/useragentclienthints_web/app.py

This example demonstrates how a User-Agent Client Hints (UACH) round trip works with the 51Degrees on-premise device detection API.

This example demonstrates how a User-Agent Client Hints (UACH) round trip works with the 51Degrees on-premise device detection API. By default the user-agent, sec-ch-ua and sec-ch-ua-mobile HTTP headers are sent. If device detection determines that the browser supports client hints then it requests additional client hints headers by setting the Accept-CH header in the response. Selecting the "Make second request" button reloads the page so those additional headers are included as evidence.

The pipeline is configured with the required UACH properties that follow the format SetHeader[Component name][Response header name], e.g. for browser, platform and hardware component properties to be set in the Accept-CH response header include SetHeaderBrowserAccept-CH, SetHeaderPlatformAccept-CH and SetHeaderHardwareAccept-CH properties respectively.

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:

View

{#
*********************************************************************
* 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.
* ********************************************************************* #}
<head>
<title>User-Agent Client Hints 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">User-Agent Client Hints example</h2>
<p class="c-eg-page__lead">
By default, the user-agent, sec-ch-ua and sec-ch-ua-mobile HTTP headers are sent. This means
that on the first request, the server can determine the browser from sec-ch-ua while other
details must be derived from the user-agent. If the server determines that the browser supports
client hints, then it may request additional client hints headers by setting the Accept-CH
header in the response.
</p>
<p class="c-eg-page__lead">
Select the <strong>Make second request</strong> button below to send another request to the
server. This time, any additional client hints headers that have been requested will be included
as evidence.
</p>
<div class="c-eg-button-row">
<button type="button" class="b-btn" onclick="redirect()">Make second request</button>
</div>
<div id="content">
<h3 class="c-eg-page__heading">Evidence values 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>
<div id="description"></div>
<h3 class="c-eg-page__heading">Detection results</h3>
<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>
</tbody>
</table>
</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-useragentclienthints_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-useragentclienthints_web-templates-index.html&utm_term=paid-data-file">Contact us</a></div>
{% endif %}
</div>
<script>
// This script runs when the "Make second request" button is clicked and a device
// detection request is sent to the server again with all the additional client hints
// that were requested in the previous response by the server.
// The following sequence is followed:
// 1. The user sends the first request to the web server for detection.
// 2. The web server returns the properties in the response based on the headers sent
// in the request. Along with the properties, it also sends a new Accept-CH header in
// the response indicating the additional evidence it needs. It builds the new
// response header using SetHeader[Component name]Accept-CH properties where Component
// Name is the name of the component for which properties are required.
// 3. When the "Make second request" button is clicked, the device detection request is
// sent to the server again with all the additional client hints that were requested
// in the previous response by the server.
// 4. The web server returns the properties based on the new User-Agent Client Hint
// headers being used as evidence.
function redirect() {
sessionStorage.reloadAfterPageLoad = true;
window.location.reload(true);
}
window.onload = function () {
if (sessionStorage.reloadAfterPageLoad) {
document.getElementById('description').innerHTML = "<p class=\"c-eg-page__lead\">The information shown below is determined using <strong>User-Agent Client Hints</strong> that were sent in the request to obtain additional evidence. If no additional information appears then it may indicate an external problem such as <strong>User-Agent Client Hints</strong> being disabled in your browser.</p>";
sessionStorage.reloadAfterPageLoad = false;
}
else {
document.getElementById('description').innerHTML = "<p class=\"c-eg-page__lead\">The following values are determined by server-side device detection on the first request.</p>";
}
};
</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 import Flask, request, render_template
from flask.helpers import make_response
from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder
from fiftyone_pipeline_core.web import webevidence, set_response_header
import json
class UserAgentClientHintsWeb():
app = Flask(__name__)
def build(self, config, logger):
# '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.
UserAgentClientHintsWeb.pipeline = PipelineBuilder().add_logger(logger).build_from_configuration(config)
return self
def run(self):
# The pipeline lives as long as the app, and is closed when the server
# stops, which releases the native data it holds.
with UserAgentClientHintsWeb.pipeline:
UserAgentClientHintsWeb.app.run(port=5001)
# The main route performs device detection and renders the results. On the
# second request, any additional client hints headers requested via the
# Accept-CH response header from the first request will be included as evidence.
@staticmethod
@app.route('/')
def server():
# Create the flowdata object for the device detection. It is closed
# when the route returns, once the page has been rendered from it,
# which releases the results of the detection straight away.
with UserAgentClientHintsWeb.pipeline.create_flowdata() as flowdata:
# Add any information from the request (headers, cookies and any other
# additional 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-useragentclienthints_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)
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.")
return config
def main(argv):
# Configure a logger to output to the console.
logger = Logger(min_level="info")
config = UserAgentClientHintsWeb.build_config()
UserAgentClientHintsWeb().build(config, logger).run()
if __name__ == "__main__":
main(sys.argv[1:])
Definition onpremise/build/__init__.py:1