How do I access Flask Session inside a slack_bolt handler?

444 views Asked by At

I have a Slack App that handles commands and actions, that follows the documented way of handling requests using a SlackRequestHandler for flask. However, I would like to use the flask session inside the slack_bolt function, and understandably it won't let me because it has no access to the request at that point in the code, and sessions don't exist without a request. However, I should be able to access the flask session somehow, given that the slack_bolt function is called by the SlackRequestHandler inside the flask view, which does have a request context. My question is, how can I access the session within the slack_bolt handler below?

from flask import Flask, request, Response, session
from flask_session import Session

import slack
from slackeventsapi import SlackEventAdapter
from slack_bolt import App
from slack_bolt.adapter.flask import SlackRequestHandler

flask_app = Flask(__name__)
SESSION_TYPE = "filesystem"
flask_app.config.from_object(__name__)
Session(flask_app)

bolt_app = App(token=os.environ['SLACK_TOKEN'], signing_secret=os.environ['SIGNING_SECRET'])
handler = SlackRequestHandler(bolt_app)

@flask_app.route('/route1', methods=['POST'])
def route1():
    return handler.handle(request)
    session['test] = 'value1' # This works fine

@bolt_app.command('/route1')
def handle_route1(body, ack, respond, client, logger):
    ack()
    session['test'] = 'value2' # This is what I am trying to do without success

The error I get is:

Failed to run listener function (error: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.)

I tried using:

with app.request_context(####):
    session['test']= 'value2'

But I don't know how to get the context object to pass to request_context, or even if this is the right thing to do. Thank you very much for any help!

0

There are 0 answers