When I run my local application with flask-socketio I can access session using from flask import session, but when I run it with gunicorn on server (gunicorn --worker-class eventlet -w 1 app:app) it return me session.keys() as Array[0].
How could I fix it to establish this local-proxy with session on server?
Thanks
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
#app.before_request
def before_request():
session['key_1'] = 'Hello,'
session['key_2'] = 'World'
#app.route('/')
def index():
return render_template('index.html')
#socketio.on('connect', namespace='/')
def socket_connect():
session_keys = session.keys()
emit('connect response', {
'session_keys': session_keys
})
#socketio.on('disconnect', namespace='/')
def socket_disconnect():
print('Client disconnected', request.sid)
if __name__ == '__main__':
socketio.run(app)
I found a solution.
Session was dissapearing and could not be shared to socketio, because I added redirect page rules on cloudflare for my domain.
When I changed Forwarding type of all rules to 302 - Temporary everything worked well.
Related
from flask import Flask, escape, request
app = Flask(__name__)
run_with_ngrok()
#app.route('/')
def hello():
name = request.args.get("name", "World")
return f'Hello, {escape(name)}!'
When I run the this from terminal with "flask run" it doesn't print an ngrok link.
Im i an virtual env and i have tried running it with python "file name" and it did not work.
if you are trying to expose your ip through ngrok, you can try tunneling with ngrok on terminal for the flask app's port
your app code should look like :
from flask import Flask, escape, request
app = Flask(__name__)
#app.route('/')
def hello():
name = request.args.get("name", "World")
return f'Hello, {escape(name)}!'
if __name__ == "__main__":
app.run(port=5000)
you can tunnel the flask app port with the following command:
ngrok http 5000
here the port 5000 denotes the flask app port.
I think you forgot to add this part to end of your file
if __name__ == "__main__":
app.run()
from flask_ngrok import run_with_ngrok
from flask import Flask, escape, request
app = Flask(__name__)
app.secret_key = '33d5f499c564155e5d2795f5b6f8c5f6'
run_with_ngrok(app)
#app.route('/')
def hello():
name = request.args.get("name", "World")
return f'Hello, {escape(name)}!'
if __name__ == "__main__":
app.run(debug=True)
We can grab token from ngrok.com website by signin
In terminal we need to run like
ngrok config add-authtoken <your_token>
ngrok http 5000
for flask it is 5000 and for other application it would be different
And we also need to run our application side by side
I am trying to deploy my flask application to aws app runner, locally everything works perfectly. But I can't figure out how to redirect to another page of my website in app runner
My code looks similar to this
from flask import Flask, url_for
from waitress import serve
app = Flask(__name__)
#app.route("/hello")
def hello():
return "Hello"
#app.route("/redirect_to")
def redirect_to():
return "Redirected successfully!"
#app.route("/redirect_from")
def redirect_from():
return redirect(url_for("redirect_to"))
if __name__ == "__main__":
serve(app, host="0.0.0.0", port=8000)
App runner provided "Default domain" that redirects all traffic to my app, that is running on 0.0.0.0:8000. When I request default-domain.awsapprunner.com/hello, it successfully redirects to 0.0.0.0:8000/hello, but when I try to request default-domain.awsapprunner.com/redirect_from page loads forever. I think it happens because my app redirects to 0.0.0.0, and app runner expects that all traffic comes to default-domain.awsapprunner.com but I am not sure
What is the best way to fix this problem?
from flask import Flask, url_for, redirect
from waitress import serve
app = Flask(__name__)
#app.route("/hello")
def hello():
return "Hello"
#app.route("/redirect_to")
def redirect_to():
return "Redirected successfully!"
#app.route("/redirect_from")
def redirect_from():
return redirect("http://YOUR_APP_URL.com/redirect_to")
if __name__ == "__main__":
serve(app, host="0.0.0.0", port=8000)
I built a very simple flask app that uses socketIo in order to make a simple chatapp, where you can write messages.
In my js file i built a function that every few seconds sends the current location of the user using geolocation.
Because im using the geolocation, i need my to use https instead of http that the flask created.
I found out about SSLify and tried it, but because im using also the socketIo it ran on http and not on https. In apps without socketIo it works, what is the problem?
this is my flask app:
from flask import Flask, render_template
from flask_socketio import SocketIO
from flask_sslify import SSLify
app = Flask(__name__)
app.config['SECRET_KEY'] = 'jsbcfsbfjefebw237u3gdbdc'
socketio = SocketIO(app)
sslify = SSLify(app)
#app.route('/')
def index():
return render_template('./ChatApp.html')
def messageRecived():
print('message was received!!!')
#socketio.on('my event')
def handle_my_custom_event(json):
print('recived my event: ' + str(json))
socketio.emit('my response', json, callback=messageRecived)
if __name__ == '__main__':
socketio.run(app, debug=True, host='0.0.0.0')
The reason it does not work is that Flask-SSLify is applied to your Flask application (the app instance), and not to Socket.IO (the socketio instance).
To my knowledge there is no equivalent to Flask-SSLify for the Socket.IO server, so you will need to either build it yourself as a WSGI middleware, or else implement the HTTP to HTTPS redirection in a reverse proxy that sits above your Python server, such as nginx or Apache.
I have been searching everywhere for tutorials on how to create and implement webhooks which listen for events within a back-end API. For instance, if I had a server written in python flask, how would I listen to server-side events (example: user has created 100 total records) which then executes some more back-end code or requests external data?
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return {"status": 200}
#Some webhook code listening for events in the server
if __name__ == '__main__':
app.run()
What do I write to listen for server events?
You can use flask feature called before_request it like this
from flask import Flask, jsonify, current_app, request
app = Flask(__name__)
#app.before_request
def hook_request():
Flask.custom_variable = {
"message": "hello world",
"header": request.args.get("param", None)
}
#app.route('/')
def home():
variable = current_app.custom_variable
return jsonify({
"variable": variable,
})
if __name__ == '__main__':
app.run()
and to test it
like this
→ curl http://localhost:5000/
{"message":"hello world"}
→ curl http://localhost:5000\?param\=example
{"variable":{"header":"example","message":"hello world"}}
I'm trying to understand how sessions work in flask_session extension. I have server-side code:
from flask import Flask, session
from flask_session import Session
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'top-secret!'
app.config['SESSION_TYPE'] = 'filesystem'
Session(app)
socketio = SocketIO(app, manage_session=False)
#socketio.on('get-session')
def get_session():
print(session.get('value', 'NO'))
#socketio.on('set-session')
def set_session(data):
session['value'] = data
print(session.get('value', 'NO'))
if __name__ == '__main__':
socketio.run(app)
and client:
from socketIO_client import SocketIO
with SocketIO('localhost', 5000) as socketio:
socketio.emit('set-session', '3')
socketio.emit('get-session')
I get following output on server:
3
NO
But i want to get:
3
3
I can't understand why session variable is not preserved. Would appreciate any help.
UPD: execution of the above code results in two different files in \flask_session directory