colour-science / flask-compress

Compress responses of your Flask application.
MIT License
117 stars 27 forks source link

example with views in a different file as the app? #21

Closed pchtsp closed 2 years ago

pchtsp commented 3 years ago

Hello!

Thanks for the library. I wanted to follow the very-straightforward example you have for compressing only certain views.

But I was not sure how to do that when the view was not in the same file as the flask app declaration (I admit understanding very little of what happens inside these functions). I tried:

app.py

from flask import Flask
from flask_compress import Compress
compress = Compress()

def start_app():
    app = Flask(__name__)
    compress.init_app(app)
    return app

some_view.py

from flask_compress import Compress
compress = Compress()

# Compress this view specifically
@app.route("/test")
@compress.compressed()
def view():
   pass

But I got this error so I guess that can't be done:

AttributeError: 'Compress' object has no attribute 'enabled_algorithms'

I found this PR where the airflow guys proposed a slight change. I finished using their approach here which does work:

https://github.com/apache/airflow/pull/13517/files

But I imagine there's a better way to solve that.

Thanks again!

alexprengere commented 3 years ago

Indeed the issue is that you have to call init_app to properly initialize all the values of Compress instances. What you should do in the view.py is to import the compress object, after the init_app. This means, in your example, that you first need to call start_app.

from .app import compress

# start_app needs be be called before 

@app.route("/test")
@compress.compressed()
def view():
   pass