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.
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">
{% 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>
import os
from pathlib import Path
import sys
from flask.helpers import make_response
from flask import Flask, request, render_template
javascript_response, json_response, webevidence, set_response_header)
import json
class GettingStartedWeb():
app = Flask(__name__)
def build(self, config, logger):
GettingStartedWeb.pipeline = PipelineBuilder().add_logger(logger).build_from_configuration(config)
return self
def run(self):
with GettingStartedWeb.pipeline:
GettingStartedWeb.app.run(port=int(os.environ.get("PORT", 5001)))
@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():
with GettingStartedWeb.pipeline.create_flowdata() as 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
@staticmethod
def build_config():
configFile = Path(__file__).resolve().parent.joinpath("config.json").read_text()
config = json.loads(configFile)
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.")
elif os.path.isabs(dataFile) == False:
newPath = ExampleUtils.find_file(dataFile)
if newPath:
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):
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
Definition example_utils.py:1