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

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

Related

Cannot use module aioflask(Python). ImportError: cannot import name '_app_ctx_stack' from 'flask.ctx'

I need to use aioflask for seting webhooks for my telegram-bot. Here my code, where I set webhook:
from aioflask import Flask, request
...
app = Flask(__name__)
...
#app.route('/')
async def webhook():
await bot.delete_webhook()
await bot.set_webhook(url=APP_URL)
return '!', 200
...
But, when I run app, it give me this error:
Traceback (most recent call last):
File "D:/Python_Projects/FilmMarketBot/check.py", line 1, in <module>
from aioflask import Flask, request
File "D:\Python_Projects\FilmMarketBot\venv\lib\site-packages\aioflask\__init__.py", line 2, in <module>
from .app import Flask
File "D:\Python_Projects\FilmMarketBot\venv\lib\site-packages\aioflask\app.py", line 14, in <module>
from .ctx import AppContext, RequestContext
File "D:\Python_Projects\FilmMarketBot\venv\lib\site-packages\aioflask\ctx.py", line 4, in <module>
from flask.ctx import AppContext as OriginalAppContext, \
ImportError: cannot import name '_app_ctx_stack' from 'flask.ctx' (D:\Python_Projects\FilmMarketBot\venv\lib\site-packages\flask\ctx.py)
Please, tell how can I fix it. ...Why always me?
There seems to be a breaking change in Flask 2.2.0, which causes this incompatibility. As a workaround you can downgrade your Flask package to 2.1.3. This change solved the issue for me.
Reported the issue on GitHub: https://github.com/miguelgrinberg/aioflask/issues/10

Flask AssertionError: View function mapping is overwriting an existing endpoint function: home

I'm trying to code a social network with flask on python anywhere
, everything was working fine before and without touching the imports I started to receive this error when I run routes.py
Traceback (most recent call last):
File "/home/OurHub/mysite/routes.py", line 13, in <module>
def home():
File "/usr/local/lib/python3.9/site-packages/flask/scaffold.py", line 433, in decorator
self.add_url_rule(rule, endpoint, f, **options)
File "/usr/local/lib/python3.9/site-packages/flask/scaffold.py", line 54, in wrapper_func
return f(self, *args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1084, in add_url_rule
raise AssertionError(
AssertionError: View function mapping is overwriting an existing endpoint function: home
I tried to put everything in a single file and I don't have two functions that have the same name
here is the start of my routes.py code
import os
import secrets
from PIL import Image
from flask import render_template, url_for, flash, redirect, request, abort
from __init__ import app, db, bcrypt
from forms import FormCreerCompte, FormConnecter, ModifierCompte, FormPoste
from modelsdb import Profil, Poste
from flask_login import login_user, current_user, logout_user, login_required
#app.route("/")
#app.route("/home")
def home():
page = request.args.get('page',1, type=int)
posts = Poste.query.paginate(page=page, per_page=5)
return render_template('page1.html', posts=posts)
and the code from the innit file:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
app = Flask(__name__)
app.config['SECRET_KEY'] = '6dfde280ba245'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://OurHub:ninjQ#OurHub.mysql.pythonanywhere-services.com/OurHub$default'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view= 'connecter'
login_manager.login_message_category = 'primary'
import routes
After a lot of research, I tried to delete a piece of code that I had commented in my html file and it worked! Maybe because the html comment "<!-->" doesn't work with python code inserts "{%%}". The error still appears when I run route, but the application works fine, I was looking for the error in the wrong place after all.

How to start Flask and Flask-SocketIO via the command line flask run

I started with an application that has several webservices defined. I was able to start the application via flask run on the command line. Afterwards, I integrated flask-sckoetio (i.e. I added the lines from flask_socketio import SocketIO, emit and socketio = SocketIO(app)) and now I'm not able anymore to start the server via flask run.
from flask import Flask, request, abort
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app)
#app.route('/do_sth', methods=['POST'])
def do_sth():
return ""
I get the following message on the console:
* Serving Flask-SocketIO app "webservices.py"
* Forcing debug mode off
WebSocket transport not available. Install eventlet or gevent and gevent-websocket for improved perform
ance.
c:\program files\python36\lib\site-packages\flask_socketio\__init__.py:496: Warning: Silently ignoring
app.run() because the application is run from the flask command line executable. Consider putting app.
run() behind an if __name__ == "__main__" guard to silence this warning.
use_reloader=use_reloader, **kwargs)
So I updated my code to this:
from flask import Flask, request, abort
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app)
#app.route('/do_sth', methods=['POST'])
def do_sth():
return ""
if __name__ == '__main__':
socketio.run(app)
But I still get the same error message and the server doesn't start. However, if I just execute the script everything works. But why is flask run not possible anymore?
It happens because of variable __name__ is equal to "__main__" only when the file called directly with a command like python file.py. But your file was imported and his __name__ variable is setted to name of a module which import them.
Solution:
Just delete string if __name__ == "__main__":
Did you install eventlet or gevent, which are mentioned in the error message?
They are also listed under requirements in flask-socketIO documentation.
Try installing them first.
After installing one of them, you can just use flask run to start your application.

Raising Error: NotRegistered when I use Flask with Celery

Description
Hi, I'm learning Celery, and I read a blog.>>
Celery and the Flask Application Factory Pattern - miguelgrinberg.com
So I wrote a small program to run Flask with Celery
Code
app.__init__.py
from flask import Flask
from celery import Celery
celery = Celery(__name__, broker='amqp://127.0.0.1:5672/')
def create_app():
app = Flask(__name__)
#celery.task
def add(x, y):
print x+y
#app.route('/')
def index():
add.delay(1, 3)
return 'Hello World!'
return app
manage.py
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run()
celery_worker_1.py
from app import celery, create_app()
f_app = create_app()
f_app.app_context().push()
celery_worker_2.py
from app import celery, create_app
#celery.task
def foo():
print 'Balabala...'
f_app = create_app()
f_app.app_context().push()
Problem
When I run the Flask server and celery useing:
celery -A celery_worker_1 worker -l
the Celery raised NotRegistered Error:
Traceback (most recent call last): File "D:\Python27\lib\site-packages\billiard\pool.py", line 363, in workloop
result = (True, prepare_result(fun(*args, **kwargs))) File "D:\Python27\lib\site-packages\celery\app\trace.py", line 349, in
_fast_trace_task
return _tasks[task].__trace__(uuid, args, kwargs, request)[0] File "D:\Python27\lib\site-packages\celery\app\registry.py", line 26, in __missing__
raise self.NotRegistered(key) NotRegistered: 'app.add'
But instead of using celery_worker_2:
celery -A celery_worker_2 worker -l info
the task run correctly:
[2015-11-28 15:45:56,299: INFO/MainProcess] Received task: app.add[cbe5e1d6-c5df-4141-9db1-e6313517c202]
[2015-11-28 15:45:56,302: WARNING/Worker-1] 4
[2015-11-28 15:45:56,371: INFO/MainProcess] Task app.add[cbe5e1d6-c5df-4141-9db1-e6313517c202] succeeded in 0.0699999332428s: None
Why can't the Celery run correctly with the code of celery_worker_1?
PS: I'm not good at English, you can point it out to me if you can't understand, I'd like to describe again. ThankS!

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)