Search code examples
pythonbasehttpserver

Python: BaseHTTPServer global var?


I'm new to python and wondering if it is possible using BaseHTTPServer to store a global var that is accessible to all requests? Basically I have an async process that requires a POST back into the server as a separate request from the original request, that I would like to write back through to the original request, via a token I'd generate.


Solution

  • No.

    To maintain state, you'll need a web framework that supports global variables across requests, or some kind of session management.

    Flask is super easy to get up and running and has sessions available.

    import flask
    
    app = flask.Flask(__name__)
    
    @app.route('/')
    def index():
        flask.session['post_token'] = MakeToken()
        return '...Content...'
    
    @app.route('/poster', methods=['POST'])
    def poster():
        if flask.session['post_token']:
            DO STUFF HERE
    
    
    # set the secret key.  keep this really secret:
    app.secret_key = 'A0Zr98j/3yX R~XHH!jxxxRT'