corvid
corvid

Reputation: 11187

keeping "global" variables in flask blueprints

Let's say I have a fairly basic main app then a series of Blueprints which lead to other pages. I then have modules that will read a csv and use the data to do the functions

from py_csv_entry import entry
class python_csv:
  def __init__(self, csv_location):
    self.data = []
    self.read_csv(csv_location)

  def read_csv(self):
    with open(csv_location + 'python_csv.csv') as csv_data:
      read = csv.reader(csv_data):
      for row in read:
        self.data.append(entry(*row))

I want to use this module in my blueprint to contain the data.

on an app, I would usually do:

app.config['python'] = python_csv('/path/to/file')

when I try to do this with the Blueprint, it raises the following error:

AttributeError: 'Blueprint' object has no attribute 'config'

in the terms of a blueprint, how would you bind a global variable?

Upvotes: 1

Views: 2544

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121952

If this is unchanging data that is just generally 'global', just keep it global. Just put it in your module, read the CSV when the module loads, and use that data.

Blueprints otherwise take their configuration from the app object; configuration is stuff that changes from one application (site) from the next, but lets you reuse your blueprints. As such configuration is tied to applications, and blueprints merely read that configuration.

Blueprints are just groups of views, associated signal handlers (before_request, after_request, etc.), letting you reuse that group or easily disable the group of views as one. They still operate in the context of a Flask application, so they will always have access to the application configuration.

As such, if you want the path to the CSV module to be configurable, set that in your application configuraton, and use the Blueprint.record_once() hook to read the CSV file based on the application configuration.

Upvotes: 5

Related Questions