Flask-Caching craches on accessing endpoint - flask

I started from scratch the project but get this error
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Exception possibly due to cache backend.
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask_caching/__init__.py", line 451, in decorated_function
rv = self.cache.get(cache_key)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask_caching/__init__.py", line 259, in cache
return app.extensions["cache"][self]
KeyError: <flask_caching.Cache object at 0x7fbec92bfac0>
127.0.0.1 - - [21/Apr/2021 14:02:42] "GET /test HTTP/1.1" 200 -
When I try to cache a simple function:
The structure of my app is:
| - app.py
| - api
| - __init__.py
| - main_api.py
So first I initiate the app.py
from flask import Flask
from flask_caching import Cache
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
from api import api as api_bp
app.register_blueprint(api_bp)
Second I create the main_api.py
from flask import jsonify
from . import api
from app import cache
import random
#api.route('/test', methods=['GET', 'POST'])
#cache.cached(timeout=2)
def rand():
return jsonify(random.randint(1, 10))
init.py is simple as abc
from flask import Blueprint
api = Blueprint('api', __name__)
from . import main_api
Used Python3.8 and Installed dependencies
click==7.1.2
Flask==1.1.2
Flask-Caching==1.10.1
itsdangerous==1.1.0
Jinja2==2.11.3
MarkupSafe==1.1.1
Werkzeug==1.0.1

Related

ImportError occurs when launching flask application using `gunicorn -c ` command

I use gunicorn to work with flask application. Here's my project structure.
flask-application
|-- non_web/
| |--...
|
|-- web/
|--app/
| |--api/
| | |--...
| |--...
| |--__init__.py # Here's def create_app()
|
|--config.py # Here's config of flask application
|--config_gunicorn.py # Here's config of gunicorn
|--run.py
When I execute command line [XXX#XXXX flask-application]# gunicorn -c web/config_gunicorn.py web.run:app, here raised a error ImportError: cannot import name 'XXX' from 'web.run' (/root/flask-application/web/run.py)
Here's run.py
```python
from web.app import create_app
app, whitelist = create_app(conf_type='default')
if __name__ == '__main__':
app.run(host=app.config['HOST'], port=app.config['PORT'])
```
Here's __init__.py
```python
from flask import Flask
import redis
from ..config import config
def create_app(conf_type):
app = Flask(__name__)
app.config.from_object(obj=config[conf_type])
config[conf_type].init_app(app=app)
from .api import api as api_blueprint
app.register_blueprint(blueprint=api_blueprint,
url_prefix='/api')
whitelist = redis.StrictRedis(host=config[conf_type].REDIS_HOST,
port=config[conf_type].REDIS_PORT,
db=config[conf_type].REDIS_DB_WHITELIST,
decode_responses=True)
return app, whitelist
```
And config_gunicorn.py follows this: github.com/benoitc/gunicorn/blob/master/examples/example_config.py
It goes well when launching run.py without gunicorn on windows. Is there any help ? Thanks.
Here comes my answer. It turn out to be related with returned whitelist object of def create_app(). By creating a connection pool, I solved this problem when working with gunicorn. This post Correct Way of using Redis Connection Pool in Python helped me a lot.

flask NoAppException but flask run works

I have the following structure:
app_dir/
| myapi/
| __init__.py
| myapi_app.py
where myapi_app.py is
from myapi import create_app, db
app = create_app()
and myapi/__init__.py is
import logging
import os
from logging.handlers import RotatingFileHandler
from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
from myapi.config import Config
db = SQLAlchemy()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
db.init_app(app)
...
return app
When I set FLASK_APP=myapi_app.py and run flask run from the app_dir directory, the flask service starts. However, when I make a request, I get the following error: flask.cli.NoAppException: Could not import "myapi_app". Where am I going wrong?
Your problem is that you are setting $FLASK_APP to the file in which the app variable is stored, you should instead set it to the python object path, e.g.
FLASK_APP=myapi_app:app
However, this is not necessary, as you could also just do:
FLASK_APP=myapi
as Flask will look for a create_app function in the package on its own.

Why does Flask + SocketIO + Gevent give me SSL EOF errors?

This is a simple code snippet that consistently repeats the issue I'm having. I'm using Python 2.7.12, Flask 0.11, Flask-SocketIO 2.7.1, and gevent 1.1.2. I understand that this is probably an issue better brought up to the responsible package's mailing list, but I can't figure out which one is responsible. However, I'm pretty sure it is a problem with gevent because that's what raises the exception.
from flask import Flask
from flask_socketio import SocketIO
from gevent import monkey
monkey.patch_all()
import ssl
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
socketio = SocketIO(app, async_mode='gevent')
#app.route('/')
def index():
return "Hello World!"
#socketio.on('connect')
def handle_connect_event():
print('Client connected')
if __name__ == '__main__':
socketio.run(app, host='127.0.0.1', port=8443,
certfile='ssl/server/server.cer', keyfile='ssl/server/server.key',
ca_certs='ssl/server/ca.cer', cert_reqs=ssl.CERT_REQUIRED,
ssl_version=ssl.PROTOCOL_TLSv1_2)
And here is the error I get when the client connects:
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/gevent/greenlet.py", line 534, in
result = self._run(*self.args, **self.kwargs)
File "/usr/lib/python2.7/site-packages/gevent/baseserver.py", line 25, in
return handle(*args_tuple)
File "/usr/lib/python2.7/site-packages/gevent/server.py", line 126, in wr
ssl_socket = self.wrap_socket(client_socket, **self.ssl_args)
File "/usr/lib/python2.7/site-packages/gevent/_sslgte279.py", line 691, i
ciphers=ciphers)
File "/usr/lib/python2.7/site-packages/gevent/_sslgte279.py", line 271, i
raise x
SSLEOFError: EOF occurred in violation of protocol (_ssl.c:590)
<Greenlet at 0x7fdd593c94b0: _handle_and_close_when_done(<bound method WSGInd method WSGIServer.do_close of <WSGIServer a, (<socket at 0x7fdd590f4410 SSLEOFError
My system also has OpenSSL version 1.0.2.j if that helps. Any thoughts would be appreciated!
Use patch_all on top of the code. Even before flask and socketio import.
from gevent import monkey
monkey.patch_all()
from flask import Flask
from flask_socketio import SocketIO
import ssl

flask and passenger "TypeError: 'module' object is not callable"

I'm trying to run flask on a server with passenger. This is my passenger_wsgi.py file:
import sys, os
INTERP = os.path.join(os.environ['HOME'], 'flask_env', 'bin', 'python')
if sys.executable != INTERP:
os.execl(INTERP, INTERP, *sys.argv)
sys.path.append(os.getcwd())
from wtf import app as application
# Uncomment next two lines to enable debugging
from werkzeug.debug import DebuggedApplication
application = DebuggedApplication(application, evalex=True)
There is an app.py file under wtf folder. There is also __init__.py in there so python recognizes it as a module directory. However it gives me this error:
Traceback (most recent call last)
File "/home/hiepha19/flask_env/lib/python2.6/site-packages/werkzeug/debug/__init__.py", line 88, in debug_application
app_iter = self.app(environ, start_response)
TypeError: 'module' object is not callable
When you import app you are importing the app module (which most likely has an app name inside it which points to your Flask app. What you want to do is import that name and register it:
from wtf.app import app as application
# Note the extra app
It is worth noting that you do not need to do this manually - simply run Flask using the run method on the app and pass the argument debug=True to get the same behavior:
from wtf.app import app
if __name__ == '__main__':
app.run(debug=True)

Flask context and python-rq

I have a Flask application with blueprints that is structured like this:
application.py
project/
form_emailer.py
blueprints/
example_form.py
wtforms-models/
example_form_model.py
templates/
example_form_template.html
I'm trying to use RQ to send emails in the background (using Flask-Mail) because our SMTP uses the Gmail servers, which can take a few seconds to complete. My function in form_emailer.py looks like this:
from flask import Flask
from flask.ext.mail import Mail, Message
from application import app, q
mail = Mail(app)
def _queue_message(message):
mail.send(message)
def sendemail(recipients, subject, body):
"""
This function gets called in a Flask blueprint.
"""
message = Message(recipients=recipients, subject=subject, body=body)
q.enqueue(_queue_message, message)
My (simplified) application.py looks like this. I'm breaking convention by using "import *" in order to simplify additions there (our __init__.py in those packages dynamically import all modules):
from flask import Flask
from redis import Redis
from rq import Queue
app = Flask(__name__)
q = Queue(connection=Redis())
from project.blueprints import *
from project.forms import *
if __name__ == "__main__":
app.run()
I have an rqworker running in the same virtual environment where my application is running, and the worker detects the task. However, I'm getting the following traceback and can't figure out how to fix this:
16:41:29 *** Listening on high, normal, low...
16:43:26 low: project.form_emailer._queue_message(<flask_mail.Message object at 0x299d690>) (bd913b3a-4e7f-4efb-b51c-8ae11d37ac00)
16:43:27 ImportError: cannot import name sendemail
Traceback (most recent call last):
...
File "./project/blueprints/example_form.py", line 4, in <module>
from project.form_emailer import sendemail
ImportError: cannot import name sendemail
I suspect this has to do with Flask's application context, but my initial attempts to use with app.app_context(): are failing; the worker is not even able to import the function I want to use. What am I doing wrong here?