flask google analytics
Install Flask-GoogleAnalytics Extension:
bash pip install Flask-GoogleAnalytics
Import and Initialize Flask Extension: ```python from flask import Flask from flask_googleanalytics import GoogleAnalytics
app = Flask(name) ga = GoogleAnalytics(app) ```
Configuration: Set your Google Analytics tracking ID in the Flask app configuration.
python app.config['GOOGLEANALYTICS_ID'] = 'Your-Tracking-ID'
Include the Google Analytics JavaScript code in your HTML templates: Add the following line inside the
<head>
tag of your HTML templates.html {{ ga.get_code() | safe }}
Track Page Views: Automatically track page views by adding the
@ga.collect
decorator to your route functions.python @app.route('/') @ga.collect def home(): return 'Home Page'
Custom Events and Dimensions: Use
@ga.event
and@ga.dimension
decorators to track custom events and dimensions. ```python @app.route('/custom-event') @ga.event(category='MyCategory', action='CustomAction') def custom_event(): return 'Custom Event Tracked'
@app.route('/custom-dimension') @ga.dimension(index=1, value='CustomValue') def custom_dimension(): return 'Custom Dimension Tracked' ```
Disable Tracking for Development: Disable tracking in the development environment by setting the configuration.
python app.config['GOOGLEANALYTICS_DEBUG'] = True
Run Flask App: Run your Flask app as usual to start the development server.
bash flask run
View Google Analytics Dashboard: Access your Google Analytics dashboard to view the tracked data for your Flask application.