1
votes

I developed a Flask application on localhost (running Python 3). It works, but when transferred to my shared hosting account (running Python 2), it doesn't. I fixed all the issues related to Python versions. But the session is not working. Its value does not persists between requests.

I tried to recreate the problem with simpler code (test.py), the commented out part is how session is configured in my application:

import sys
sys.path.insert(0, '/home/user_name/public_html')

from flask import Flask, request, session
from flask.ext.session import Session
from tempfile import mkdtemp
from cs50 import SQL
from constants import *

app = Flask(__name__)

#app.config["SESSION_TYPE"] = "filesystem"
#app.config["SESSION_PERMANENT"] = False
#app.config["SESSION_FILE_DIR"] = mkdtemp()
Session(app)

@app.route('/set/')
def set():
    session['key'] = 'value'
    return 'ok'

@app.route('/get/')
def get():
    return "{}".format(session.get('key'))

If you go to /set/, you will see ok. But on /get/ you will see None.

And here's my CGI file (which I need only for shared hosting, not for localhost):

#!/home/user_name/public_html/cgi-bin/flask/bin/python
import sys
sys.path.insert(0, '/home/user_name/public_html')

# Enable CGI error reporting
import cgitb
cgitb.enable()

import os
from wsgiref.handlers import CGIHandler

app = None
try:
    import test
    app = test.app
except Exception, e:
    print "Content-type: text/html"
    print
    cgitb.handler()
    exit()

#os.environ['SERVER_PORT'] = '80'
#os.environ['REQUEST_METHOD'] = 'POST'

class ScriptNameStripper(object):
   def __init__(self, app):
       self.app = app

   def __call__(self, environ, start_response):
       environ['SCRIPT_NAME'] = ''
       return self.app(environ, start_response)

app = ScriptNameStripper(app)

try:
    CGIHandler().run(app)
except Exception, e:
    print "Content-type: text/html"
    print
    cgitb.handler()
    exit()

In case .htaccess file is needed:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /cgi-bin/mas.cgi/$1 [L]

Googling didn't help, and other similar questions on Stackoverflow don't fix it. Any solution/help is welcomed. Thanks!

1
anyone? no one? - Mustaghees
Are you sure that session was written to file? try to change return 'ok' to return json.dumps(session) - Danila Ganchar
@DanilaGanchar it raises this error: <FileSystemSession {'key': 'value'}> is not JSON serializable - Mustaghees
change dumps to print or write session values into log file. Just make sure that session was written - Danila Ganchar

1 Answers

0
votes

I am still not sure if session was being written or not (as @Danila Ganchar pointed out), but only commenting out the 3rd configuration line solved the issue.

So the changes made in test.py are:

app.config["SESSION_TYPE"] = "filesystem"
app.config["SESSION_PERMANENT"] = False
#app.config["SESSION_FILE_DIR"] = mkdtemp()

I guess mkdtemp() wasn't working as it was on localhost.