flask google analytics

  1. Install Flask-GoogleAnalytics Extension: bash pip install Flask-GoogleAnalytics

  2. Import and Initialize Flask Extension: ```python from flask import Flask from flask_googleanalytics import GoogleAnalytics

app = Flask(name) ga = GoogleAnalytics(app) ```

  1. Configuration: Set your Google Analytics tracking ID in the Flask app configuration. python app.config['GOOGLEANALYTICS_ID'] = 'Your-Tracking-ID'

  2. 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 }}

  3. 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'

  4. 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' ```

  1. Disable Tracking for Development: Disable tracking in the development environment by setting the configuration. python app.config['GOOGLEANALYTICS_DEBUG'] = True

  2. Run Flask App: Run your Flask app as usual to start the development server. bash flask run

  3. View Google Analytics Dashboard: Access your Google Analytics dashboard to view the tracked data for your Flask application.