0

I am making a simple Flask REST API that processes some text and returns some json.

All the code that processes the text is inside a class:

class TextParser:
  def __init__(self, file_in, ....):
    # COSTLY FUNCTION THAT LOADS DATA FROM MULTIPLE SOURCES

  def parse_text(self, text):
    # fast function that returns the wanted json

The API is also included in a python package and so it is started from python code as:


def start_api(path_to_load="file_one.in", ...):
  app = Flask(__name__, static_folder="static")
  app.config["JSON_AS_ASCII"] = False

  # I load the parser here as it takes a while to load
  text_parser = TextParser()
  # I also register some blueprints
  app.register_blueprint(...)
  app.run(host="localhost", port=5000)

I cut some of my code as is extense. What I want is to load TextParser once and then to be able to use inside the blueprints to call the parse_text method, no need to instantiate the object again as the data that it loads is static.

How can I achieve this in flask?

Gonzalo Hernandez
  • 665
  • 2
  • 6
  • 24

1 Answers1

0

by the official api

class flask.Blueprint(name, import_name, static_folder=None, static_url_path=None, template_folder=None, url_prefix=None, subdomain=None, url_defaults=None, root_path=None)

the constructor of the Blueprint cannot take any arg for shared object (most of the args need to be String)

so you can create a new MyBlueprint class that extend Blueprint and can store the shared object

my suggestion is to refactor the TextParser as a singleton, so it won't be created and load the data as it instantiate

shahaf
  • 3,828
  • 2
  • 22
  • 31