`_,
and then add and commit files under the ``assets`` directory there as usual. Open a pull request, and once it's merged
it will be automatically uploaded to the S3 bucket and be available on the domain.
For example, if you add a file to the repo under ``assets/pdf/the-dude-abides.pdf``, it will be available
as https://assets.mozilla.net/pdf/the-dude-abides.pdf. Once that is done you can link to that URL from bedrock
as you would any other URL.
Writing Migrations
------------------
Bedrock uses Django's built-in Migrations framework for its database migrations, and has no custom
database routing, etc. So, no big surprises here – write things as you regularly would.
*However*, as with any complex system, care needs to be taken with schema changes that
drop or rename database columns. Due to the way the rollout process works (ask for
details directly from the team), an absent column can cause some of the rollout to
enter a crashloop.
To avoid this, split your changes across releases, such as below.
For column renames:
* Release 1: Add your new column
* Release 2: Amend the codebase to use it instead of the old column
* Release 3: Clean up - drop the old, deprecated column, which should not be referenced in code at this point.
For column drops:
* Release 1: Update all code that uses the relevant column, so that nothing interacts with it any more.
* Release 2: Clean up - drop the old, deprecated column.
With both paths, check for any custom schema or data migrations that might reference the deprecated column.
Writing Views
-------------
You should rarely need to write a view for mozilla.org. Most pages are
static and you should use the ``page`` function documented above.
If you need to write a view and the page is translated or translatable
then it should use the ``l10n_utils.render()`` function to render the
template.
.. code-block:: python
from lib import l10n_utils
from django.views.decorators.http import require_safe
@require_safe
def my_view(request):
# do your fancy things
ctx = {"template_variable": "awesome data"}
return l10n_utils.render(request, "app/template.html", ctx)
Make sure to namespace your templates by putting them in a directory
named after your app, so instead of templates/template.html they would
be in templates/blog/template.html if ``blog`` was the name of your app.
The ``require_safe`` ensures that only ``GET`` or ``HEAD`` requests will make it
through to your view.
If you prefer to use Django's Generic View classes we have a convenient
helper for that. You can use it either to create a custom view class of
your own, or use it directly in a ``urls.py`` file.
.. code-block:: python
# app/views.py
from lib.l10n_utils import L10nTemplateView
class FirefoxRoxView(L10nTemplateView):
template_name = "app/firefox-rox.html"
# app/urls.py
urlpatterns = [
# from views.py
path("firefox/rox/", FirefoxRoxView.as_view()),
# directly
path("firefox/sox/", L10nTemplateView.as_view(template_name="app/firefox-sox.html")),
]
The ``L10nTemplateView`` functionality is mostly in a template mixin called ``LangFilesMixin`` which
you can use with other generic Django view classes if you need one other than ``TemplateView``.
The ``L10nTemplateView`` already ensures that only ``GET`` or ``HEAD`` requests will be served.
Variation Views
~~~~~~~~~~~~~~~
We have a generic view that allows you to easily create and use a/b testing
templates. If you'd like to have either separate templates or just a template
context variable for switching, this will help you out. For example.
.. code-block:: python
# urls.py
from django.urls import path
from bedrock.utils.views import VariationTemplateView
urlpatterns = [
path("testing/",
VariationTemplateView.as_view(template_name="testing.html",
template_context_variations=["a", "b"]),
name="testing"),
]
This will give you a context variable called ``variation`` that will either be an empty
string if no param is set, or ``a`` if ``?v=a`` is in the URL, or ``b`` if ``?v=b`` is in the
URL. No other options will be valid for the ``v`` query parameter and ``variation`` will
be empty if any other value is passed in for ``v`` via the URL. So in your template code
you'd simply do the following:
.. code-block:: jinja
{% if variation == 'b' %}This is the B variation of our test. Enjoy!
{% endif %}
If you'd rather have a fully separate template for your test, you can use the
``template_name_variations`` argument to the view instead of ``template_context_variations``.
.. code-block:: python
# urls.py
from django.urls import path
from bedrock.utils.views import VariationTemplateView
urlpatterns = [
path("testing/",
VariationTemplateView.as_view(template_name="testing.html",
template_name_variations=["1", "2"]),
name="testing"),
]
This will not provide any extra template context variables, but will instead look for
alternate template names. If the URL is ``testing/?v=1``, it will use a template named
``testing-1.html``, if ``v=2`` it will use ``testing-2.html``, and for everything else it will
use the default. It simply puts a dash and the variation value between the template
file name and file extension.
It is theoretically possible to use the template name and template context versions
of this view together, but that would be an odd situation and potentially inappropriate
for this utility.
You can also limit your variations to certain locales. By default the variations will work
for any localization of the page, but if you supply a list of locales to the ``variation_locales``
argument to the view then it will only set the variation context variable or alter the template
name (depending on the options explained above) when requested at one of said locales. For example,
the template name example above could be modified to only work for English or German like so
.. code-block:: python
# urls.py
from django.urls import path
from bedrock.utils.views import VariationTemplateView
urlpatterns = [
path("testing/",
VariationTemplateView.as_view(template_name="testing.html",
template_name_variations=["1", "2"],
variation_locales=["en-US", "de"]),
name="testing"),
]
Any request to the page in for example French would not use the alternate template even if a
valid variation were given in the URL.
.. note::
If you'd like to add this functionality to an existing Class-Based View, there is
a mixin that implements this pattern that should work with most views:
``bedrock.utils.views.VariationMixin``.
.. _geo-location:
Geo Template View
~~~~~~~~~~~~~~~~~
Now that we have our :abbr:`CDN (Content Delivery Network)` configured properly, we can also just swap out templates
per request country. This is very similar to the above, but it will simply use
the proper template for the country from which the request originated.
.. code-block:: python
from bedrock.base.views import GeoTemplateView
class CanadaIsSpecialView(GeoTemplateView):
geo_template_names = {
"CA": "mozorg/canada-is-special.html",
}
template_name = "mozorg/everywhere-else-is-also-good.html"
For testing purposes while you're developing or on any deployment that is not
accessed via the production domain (www.mozilla.org) you can append your URL
with a ``geo`` query param (e.g. ``/firefox/?geo=DE``) and that will take
precedence over the country from the request header.
Other Geo Stuff
~~~~~~~~~~~~~~~
There are a couple of other tools at your disposal if you need to change things
depending on the location of the user. You can use the
``bedrock.base.geo.get_country_from_request`` function in a view and it will
return the country code for the request (either from the :abbr:`CDN (Content Delivery Network)` or the query param,
just like above).
.. code-block:: python
from bedrock.base.geo import get_country_from_request
def dude_view(request):
country = get_country_from_request(request)
if country == "US":
# do a thing for the US
else:
# do the default thing
The other convenience available is that the country code, either from the :abbr:`CDN (Content Delivery Network)`
or the query param, is avilable in any template in the ``country_code`` variable.
This allows you to change anything about how the template renders based on the
location of the user.
.. code-block:: jinja
{% if country_code == "US" %}
GO MURICA!
{% else %}
Yay World!
{% endif %}
Reference:
* Officially assigned list of `ISO country codes `_.
Metrics Collection with Markus
------------------------------
Markus is a metrics library that we use in our project for collecting and reporting statistics about
our code's operation. It provides a simple and consistent way to record custom metrics from your
application, which can be crucial for monitoring and performance analysis.
Markus supports a variety of backends, including Datadog, Statsd, and Logging. This means you can
choose the backend that best fits your monitoring infrastructure and requirements. Each backend has
its own set of features and capabilities, but Markus provides a unified interface to all of them.
Once the metrics are collected by Markus they are then forwarded to Telegraf. Telegraf is an agent
for collecting and reporting metrics, which we use to process and format the data before it's sent
to Grafana.
Grafana is a popular open-source platform for visualizing metrics. It allows us to create dashboards
with panels representing the metrics we're interested in, making it easy to understand the data at a
glance.
Here's an example of how to use Markus to record a metric:
.. code-block:: python
from bedrock.base import metrics
# Counting events
metrics.incr("event_name")
# Timing events
metrics.timing("event_name", 123)
# Or timing events with context manager
with metrics.timer("event_name"):
# code to time goes here
In addition to recording the metric values, Markus also allows you to add tags to your metrics. Tags
are key-value pairs that provide additional context about the metric, making it easier to filter and
aggregate the data in Grafana. For example, you might tag a metric with the version of your
application, the user's country, or the result of an operation. To add tags to a metric in Markus,
you can pass them as a dictionary to the metric recording method. Here's an example:
.. code-block:: python
# Counting events with tags
metrics.incr("event_name", tags=[f"version:{version}", f"country:{country}"])
For more information, refer to the `Markus documentation `_.
Coding Style
------------
Bedrock uses the following open source tools to follow coding styles and conventions,
as well as applying automatic code formatting:
* `ruff `_ for Python style, code quality rules, and import ordering.
* `black `_ for Python code formatting.
* `Prettier `_ for JavaScript code formatting.
* `ESLint `_ for JavaScript code quality rules.
* `Stylelint `_ for Sass/CSS style and code quality rules.
For front-end HTML & CSS conventions, bedrock uses Mozilla's Protocol design system for
building components. You can read the `Protocol documentation site `_
for more information.
Mozilla also has some more general coding styleguides available, although some of
these are now rather outdated:
* `Mozilla Python Style Guide `_
* `Mozilla HTML Style Guide `_
* `Mozilla JS Style Guide `_
* `Mozilla CSS Style Guide `_
Test coverage
-------------
When the Python tests are run, a coverage report is generated, showing which lines of the
codebase have tests that execute them, and which do not. You can view this report in your
browser at ``file:///path/to/your/checkout/of/bedrock/python_coverage/index.html``.
When adding code, please aim to provide solid test coverage, using the coverage report as
a guide. This doesn't necessarily mean every single line needs a test, and 100% coverage
doesn't mean 0% defects.
Configuring your Code Editor
----------------------------
Bedrock includes an ``.editorconfig`` file in the root directory that you can
use with your code editor to help maintain consistent coding styles. Please
see `editorconfig.org `_. for a list of supported
editors and available plugins.
Working with Protocol Design System
-----------------------------------
Bedrock uses the `Protocol Design System `_ to quickly produce consistent, stable components. There are different methods -- depending on the component -- to import a Protocol component into our codebase.
One method involves two steps:
1. Adding the `correct markup <#styles-and-components>`_ or importing the `appropriate macro <#macros>`_ to the page's HTML file.
2. Importing the necessary Protocol styles to a page's SCSS file.
The other method is to `import CSS bundles <#import-css-bundles>`_ onto the HTML file. However, this only works for certain components, which are listed below in the respective section.
Styles and Components
~~~~~~~~~~~~~~~~~~~~~
The base templates in Bedrock have global styles from Protocol that apply to every page. When we need to extend these styles on a page-specific basis, we set up Protocol in a page-specific SCSS file.
For example, on a Firefox product page, we might want to use Firefox logos or wordmarks that do not exist on every page.
To do this, we add Protocol ``mzp-`` classes to the HTML:
.. code-block:: html
// bedrock/bedrock/firefox/templates/firefox/{specific-page}.html
Firefox Browser
Then we need to include those Protocol styles in the page's SCSS file:
.. code-block:: css
/* bedrock/media/css/firefox/{specific-page}.scss */
/* if we need to use protocol images, we need to set the $image-path variable */
$image-path: '/media/protocol/img';
/* mozilla is the default theme, so if we want a different one, we need to set the $brand-theme variable */
$brand-theme: 'firefox';
/* the lib import is always essential: it provides access to tokens, functions, mixins, and theming */
@import '~@mozilla-protocol/core/protocol/css/includes/lib';
/* then you add whatever specific protocol styling you need */
@import '~@mozilla-protocol/core/protocol/css/components/logos/wordmark';
@import '~@mozilla-protocol/core/protocol/css/components/logos/wordmark-product-firefox';
.. note::
If you create a new SCSS file for a page, you will have to include it in that page's CSS bundle by updating
`static-bundles.json <#asset-bundling>`_ file.
Macros
~~~~~~
The team has created several `Jinja macros `_ out of Protocol components to simplify the usage of components housing larger blocks of code (i.e. Billboard). The code housing the custom macros can be found in our `protocol macros file `_. These Jinja macros include parameters that are simple to define and customize based on how the component should look like on a given page.
To use these macros in files, we simply import a macro to the page's HTML code and call it with the desired arguments, instead of manually adding Protocol markup. We can import multiple macros in a comma-separated fashion, ending the import with ``with context``:
.. code-block:: html
// bedrock/bedrock/firefox/templates/firefox/{specific-page}.html
{% from "macros-protocol.html" import billboard with context %}
{{ billboard(
title='This is Firefox.',
ga_title='This is Firefox',
desc='Firefox is an awesome web browser.',
link_cta='Click here to install',
link_url=url('firefox.new')
)}}
Because not all component styles are global, we still have to import the page-specific Protocol styles in SCSS:
.. code-block:: css
/* bedrock/media/css/firefox/{specific-page}.scss */
$brand-theme: 'firefox';
@import '~@mozilla-protocol/core/protocol/css/includes/lib';
@import '~@mozilla-protocol/core/protocol/css/components/billboard';
Import CSS Bundles
~~~~~~~~~~~~~~~~~~
We created pre-built CSS bundles to be used for some components due to their frequency of use. This method only requires an import into the HTML template. Since it’s a separate CSS bundle, we don’t need to import that component in the respective page CSS.
The CSS bundle import only works for the following components:
* Split
* Card
* Picto
* Callout
* Article
* Newsletter form
* Emphasis box
Include a CSS bundle in the template's ``page_css`` block along with any other page-specific bundles, like so:
.. code-block:: html
{% block page_css %}
{{ css_bundle('protocol-split') }}
{{ css_bundle('protocol-card') }}
{{ css_bundle('page-specific-bundle') }}
{% endblock %}