GithubHelp home page GithubHelp logo

mbr / flask-kvsession Goto Github PK

View Code? Open in Web Editor NEW
168.0 13.0 53.0 528 KB

A drop-in replacement for Flask's session handling using server-side sessions.

Home Page: http://pythonhosted.org/Flask-KVSession/

License: MIT License

Python 100.00%

flask-kvsession's Introduction

Flask-KVSession

Flask-KVSession is an MIT-licensed server-side session replacement for Flask's signed client-based session management. Instead of storing data on the client, only a securely generated ID is stored on the client, while the actual session data resides on the server.

This has two major advantages:

  • Clients no longer see the session information
  • It is possible to securely destroy sessions to protect against replay attacks.

Other things are possible with server side session that are impossible with clients side sessions, like inspecting and manipulating data in absence of the client.

Flask-KVSession uses the simplekv-package for storing session data on a variety of backends, including redis, memcached, SQL databases using SQLAlchemy, mongoDB or just flat files.

Integration with Flask is seamless, once the extension is loaded for a Flask application, it transparently replaces Flask's own Session management. Any application working with sessions should work the same with Flask-KVSession (if it does not, file a bug!).

Documentation and development

Development happens on github, you can find the documentation on PyPI.

flask-kvsession's People

Contributors

jarppa avatar jgibson avatar markhildreth avatar mbr avatar simonsapin avatar ssidorenko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flask-kvsession's Issues

Issues with destroying the session manually

Hi,

destroying the Flask session calling session.destroy works fine. Due to the fact that the session id also used by another app I would like to destroy the session cookie and the stored session id as well when the logout view is called.

Is there a way to do that? Removing the session id manually from the store in the logout view results in a new generated session (including session id and cookie).

Thanks in advance.

New release?

PR #36 was merged in Aug 2015, but the last release on PyPi was in May 2015. Any chance we could get a new release on PyPi?

AttributeError: 'module' object has no attribute 'reply'

I'm using kvsession 0.3.1 and have started getting the object has no attribute 'reply' error. I'm really not sure if it is something I'm doing wrong or not. My app seems pretty straightforward. I'm using the in-memory store.

The debug output from Flask is below. What else do you need from me?

Thanks for the help.

AttributeError

AttributeError: 'module' object has no attribute 'reply'
Traceback (most recent call last)

File "C:\Users\Joshua\Dropbox\PythonScripts\fulsawsum\env\lib\site-packages\flask\app.py", line 1518, in __call__

return self.wsgi_app(environ, start_response)

File "C:\Users\Joshua\Dropbox\PythonScripts\fulsawsum\env\lib\site-packages\flask\app.py", line 1502, in wsgi_app

with self.request_context(environ):

File "C:\Users\Joshua\Dropbox\PythonScripts\fulsawsum\env\lib\site-packages\flask\ctx.py", line 154, in __enter__

self.push()

File "C:\Users\Joshua\Dropbox\PythonScripts\fulsawsum\env\lib\site-packages\flask\ctx.py", line 138, in push

self.session = self.app.open_session(self.request)

File "C:\Users\Joshua\Dropbox\PythonScripts\fulsawsum\env\lib\site-packages\flask\app.py", line 745, in open_session

return self.session_interface.open_session(self, request)

File "C:\Users\Joshua\Dropbox\PythonScripts\fulsawsum\env\lib\site-packages\flaskext\kvsession.py", line 189, in open_session

self.store.get(sid_s))

[console ready]
>>> dump()
Local variables in frame
app 

<flask.app.Flask object at 0x02D9E9D0>

sid 

<flaskext.kvsession.SessionID object at 0x030A6B30>

request 

<Request 'http://127.0.0.1:5000/login' [GET]>

key 

'm5W8-R$CeFruqEC4E5wE'

session_cookie  

u'74cf58bad9857ee2_500f2f54.EC2iF3rAdFgwWgmASMVZOPjw17I'

self    

<flaskext.kvsession.KVSessionInterface object at 0x02DE88B0>

sid_s   

'74cf58bad9857ee2_500f2f54'

Lots of session collisions

It appears that the ID generation is not sufficiently random or there is some other issue. I see frequent session ID collisions. These collisions are actually a major security risk as I'm seeing users getting logged in as other users (their session data is being overwritten by that of another user). This opens us up to a potential session hijacking problem if a malicious user can find a way to easily reproduce.

  • Python 2.7.5
  • Platforms Produced On: Amazon Linux, CentOS, Ubuntu, and Mac OS X
  • Flask 0.10.1
  • SimpleKV 0.9.2

This issue is incredibly similar to a previous one (#12). Here's a basic stack trace:

IntegrityError: (IntegrityError) duplicate key value violates unique constraint "sessions_pkey" DETAIL: Key (key)=(e0e17c94f388ba70_53d2ed1f) already exists. 'INSERT INTO sessions (key, value) VALUES (%(key)s, %(value)s)' {'key': 'e0e17c94f388ba70_53d2ed1f', 'value': <psycopg2._psycopg.Binary object at 0x49d2c88>}
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1479, in full_dispatch_request
    response = self.process_response(response)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1693, in process_response
    self.save_session(ctx.session, response)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 837, in save_session
    return self.session_interface.save_session(self, session, response)
File "/usr/lib/python2.7/site-packages/flaskext/kvsession.py", line 189, in save_session
    self.serialization_method.dumps(dict(session)))
File "/usr/lib/python2.7/site-packages/simplekv/__init__.py", line 137, in put
    return self._put(key, data)
File "/usr/lib/python2.7/site-packages/simplekv/db/sql.py", line 56, in _put
    'value': data
File "/usr/lib64/python2.7/site-packages/sqlalchemy/engine/base.py", line 720, in execute
    return meth(self, multiparams, params)
File "/usr/lib64/python2.7/site-packages/sqlalchemy/sql/elements.py", line 317, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
File "/usr/lib64/python2.7/site-packages/sqlalchemy/engine/base.py", line 817, in _execute_clauseelement
    compiled_sql, distilled_params
File "/usr/lib64/python2.7/site-packages/sqlalchemy/engine/base.py", line 947, in _execute_context
    context)
File "/usr/lib64/python2.7/site-packages/sqlalchemy/engine/base.py", line 1108, in _handle_dbapi_exception
    exc_info
File "/usr/lib64/python2.7/site-packages/sqlalchemy/util/compat.py", line 185, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb)
File "/usr/lib64/python2.7/site-packages/sqlalchemy/engine/base.py", line 940, in _execute_context
    context)
File "/usr/lib64/python2.7/site-packages/sqlalchemy/engine/default.py", line 435, in do_execute
    cursor.execute(statement, parameters)

Unfortunately there are no minimal steps to reproduce except to keep producing new flask sessions until the error occurs. The most consistent reproduction has been when using JMeter to do load testing.

My recommendation is that the way session IDs are generated be completely changed. You should be using something for which collisions are guaranteed to be incredibly rare - perhaps switching to UUIDs for the ID portion of the key would be better.

cookie/session getting lost when session not modified during a request

When using this as a drop-in replacement for flask's default session object, the cookie can unexpectedly get lost if a request is made without a modification to the session.

When making requests via browser loads, the behavior is not reproducible, probably becuase browsers manage their own cookies across requests such that when an empty cookie is received, the old cookie is used.

The behavior is reproducible if you manage cookies manually on a per-request basis e.g. via requests or curl

Example:

server.py

from flask import Flask, session, request
from flask_kvsession import KVSessionExtension
from simplekv.memory.redisstore import RedisStore
import redis

app = Flask(__name__)
app.secret_key = 'foo'
# toggle for default session
KVSessionExtension(RedisStore(redis.StrictRedis()), app)
@app.route('/')
def index():
    if 'x' not in session:
        session['x'] = 0
    return str(session['x'])
@app.route('/test')
def test():
    session['x'] = session.get('x', 0) + 1
    return str(session['x'])
app.run(debug=True)

client.py

import requests
gcookie = {}
for i in range(10):
    res = requests.get('http://localhost:5000/' + (i%2==0 and 'test' or ''),
                       cookies = gcookie,)
    gcookie = res.cookies
    print res.content

Start server.py then client.py, comparing default sessions with kvsession

expected behavior (default sessions): client will print increasing numbers like 1 1 2 2 3 3 ...

observed behavior (kvsession): client will print 1 1 1 1 1 1...

This seems to happen when session.modified is False, in save_session the response won't contain the session cookie. One can either store the session cookie in the client and continue using it when one isn't returned, or by forcing a session.modified = True in e.g. before_request.

Would it be a good idea to add some carryover behavior for when the session is not modified, to maintain behavior parity with the default session? Or is it standard to just leave it to the client? Thanks!

Session saved every request even if not modified

Supposedly "The session class will save data to the store only when necessary". I noticed that even if the session is not updated on a request, KVSession still write it out (I'm using Redis, and noticed this while monitoring Redis write activity). I noticed this code here (last two lines)

class KVSession(CallbackDict, SessionMixin):
...
    def __init__(self, initial=None):
        def _on_update(d):
            d.modified = True

        CallbackDict.__init__(self, initial, _on_update)

        if not initial:
            self.modified = False

Right now, if the session already contains any data, modified is always True (picking up the default value from SessionMixin). The only case "modified" starts off as True when the KVSession is initialized is for a brand new session.

Respect SESSION_COOKIE_HTTPONLY and SESSION_COOKIE_SECURE

Cookies generated by flask-kvsession do not appear to respect the Flask app configurations SESSION_COOKIE_HTTPONLY and SESSION_COOKIE_SECURE values for setting the respective cookie flags.

The flask-kvsession configuration documentation does not claim to, so I view this as more of a feature request.

How to use memcache with simplekv/ kv-session?

I am trying to use memcache with simplekv, But as mentioned in the documentation, I get an IO error when I try to clear the cache (during the cleanup_session() part of the code).

from simplekv.memory.memcachestore import MemcacheStore
import memcache
import redis
import datetime

store = RedisStore(redis.StrictRedis())

store = MemcacheStore(memcache.Client(['127.0.0.1:11211'], debug = 0))
store.ttl_support = True
app = create_app(name)
current_kvsession = KVSessionExtension(store, app)
for key in app.kvsession_store.keys():
logger.debug(key)
m = current_kvsession.key_regex.match(key)
logger.debug('found %s', m)
logger.debug(app.kvsession_store.delete(key))

Since memcache doesnt support app.kvsession_store.keys(). Do I need to remember the key somewhere so that I wont have to pull it out of memcache? Let me know if more explaination is needed.

Request for example App

So far, I have been using the test app in the tests folder as an example. Is there some way, we can add a reference to the same in the documentation?
Any other flask app examples are also greatly appreciated.

There is a problem when using kvsession in python2.6

This is the error got when I tried to use kvsession with python2.6. Can you make some code changes so that this can be used with the older python version as well, as till date a lot of people are still on python 2.6.

init.py", line 192, in save_session
ttl = current_app.permanent_session_lifetime.total_seconds()

AttributeError: 'datetime.timedelta' object has no attribute 'total_seconds'

gunicorn and multiple workers

If I use multiple workers it breaks flask kv sessions however setting the num workers to one and everything functions OK.

Is this a limitation or a bug, and is there anything I can do to help fix it?

File store sometimes fails

I randomly get these request failures in my logfiles:

Traceback (most recent call last):
  File "c:\python27\lib\site-packages\wfastcgi.py", line 826, in main
    result = handler(record.params, response.start)
  File "c:\python27\lib\site-packages\flask\app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File ".\flask_app.py", line 16, in __call__
    return self.app(environ, start_response)
  File "c:\python27\lib\site-packages\flask\app.py", line 1978, in wsgi_app
    ctx.push()
  File "c:\python27\lib\site-packages\flask\ctx.py", line 332, in push
    self.session = self.app.open_session(self.request)
  File "c:\python27\lib\site-packages\flask\app.py", line 912, in open_session
    return self.session_interface.open_session(self, request)
  File "C:\www\flask_app\virtualenv\lib\site-packages\flask_kvsession\__init__.py", line 160, in open_session
    current_app.kvsession_store.get(sid_s)
EOFError

Any ideas?

session.regenerate() Force User To Sign Out

I implemented a logic to refresh user last access to the system and stop user from being signed out after session expires. My session expires after 10 minutes. I implemented this logic this way:

@vapor_app.before_request
def before_request():
    g.user = current_user
    session.permanent = True
    session.regenerate()

This logic works just fine when I use the system. But as soon as I refresh the page once (With F5), it logs me out of the system. How should I refresh last access date and avoid this error.

Table already defined on this metadata instance

I am using kvsession in a flask app and it works as expected. I ran into this while running tests:

Traceback (most recent call last):
  File "/home/user/project/tests/base.py", line 20, in setUpClass
    cls.app = get_app('testing')
  File "/home/user/project/__init__.py", line 30, in get_app
    session_store = SQLAlchemyStore(engine, db.Model.metadata, 'kvsession')
  File "/home/user/.virtualenvs/project/local/lib/python2.7/site-packages/simplekv/db/sql.py", line 21, in __init__
    Column('value', LargeBinary, nullable=False)
  File "/home/user/.virtualenvs/project/local/lib/python2.7/site-packages/sqlalchemy/sql/schema.py", line 398, in __new__
    "existing Table object." % key)
InvalidRequestError: Table 'kvsession' is already defined for this MetaData instance.  Specify 'extend_existing=True' to redefine options and columns on an existing Table object.

It somehow happens because the tests call the initialization twice. I could not work around this, any ideas?

Using SQLAlchemy data stored as binary and wrapped as binary when opened

Python 3.5 + MySQL

When data is stored to a session it is pickled and stored as a binary string:

ex:

session["card"] = "'PP000007C|'
# pickled as:
b'\x80\x03}q\x00(X\x06\x00\x00\x00_freshq\x01\x89X\x05\x00\x00\x00cardsq\x02X\n\x00\x00\x00PP000007C|q\x03u.'

When we later try to get the data, it is pulled as a bytes object out of the database and wrapped again as a string:

For example on that same string above it is pulled out of the database as:
b"b'\x80\x03}q\x00(X\x06\x00\x00\x00_freshq\x01\x89X\x05\x00\x00\x00cardsq\x02X\n\x00\x00\x00PP000007C|q\x03u.'"

As you can see, the binary string is stored again cast as a binary string.

Relevant files:
flask_kvsession__init__.py
Line 186:

# save the session, now its no longer new (or modified)
data = self.serialization_method.dumps(dict(session))

# in this case, data == b'\x80\x03}q\x00(X\x06\x00\x00\x00_freshq\x01\x89X\x05\x00\x00\x00cardsq\x02X\n\x00\x00\x00PP000007C|q\x03u.'

`session.regenerate()` raises an error if called on the first request

I recently faced the following error:

AttributeError: 'KVSession' object has no attribute 'sid_s'

When calling session.regenerate() in my flask project. I guess this issue is very similar to this one.

This happens when session.regenerate() is called on the first request. Whether it is a GET or POST doesn't matter, and the aforementioned error is raised.

Adding:

if not hasattr(session, 'sid_s'):
  session.sid_s = None

Before the call fixes the issues, but is hardly a long-term and clean solution.

I understood the rationale of raising an error when the programmer makes a mistake, however it doesn't seem like calling regenerate() on a first request is a mistake. Or is it ?

I see no way of checking whether a session exists so its quite hard to avoid.

CSRF Token Protection

Flask-KVSession seems to be having issues with CSRF protection token generation. It seems that it doesn't get stored or rather, "disappears" from the storage occasionally. It's very inconsistent whether I can get it to replicant or not but usually an easy way is to open two different browsers and trying to login to both using different but valid credentials.

How I initialize flask-kvsession

@create_app
    store = MemcacheStore(mc=pylibmc.Client(app.config['MEMCACHE_SERVERS'], binary=True,
                                        behaviors={'distribution': 'consistent'})
    )

    KVSessionExtension(store, app)

How csrf token is being generated

def generate_csrf_token():
    if '_csrf_token' not in session:
        session['_csrf_token'] = randomstring()
        app.logger.debug("Generating a CSRF token")
        app.logger.debug(session['_csrf_token'])
    return session['_csrf_token']

I see that it actually stores it but then when the application goes to try and verify it, it doesn't work and says that session['_csrf_token'] doesn't exist. Any ideas?

EOFError in Flask-KVSession 0.6.2

I am using Flask-KVSession (version 0.6.2). It does what it has to do. But when there are consecutive requests to webserver, following exception is repeated like a flood.

2016-06-10_05:41:58.97125 2016-06-10 05:41:58 [29567] [ERROR] Error handling request 2016-06-10_05:41:58.97127 Traceback (most recent call last): 2016-06-10_05:41:58.97128 File "/usr/lib/pymodules/python2.7/gunicorn/workers/async.py", line 45, in handle 2016-06-10_05:41:58.97128 self.handle_request(listener, req, client, addr) 2016-06-10_05:41:58.97129 File "/usr/lib/pymodules/python2.7/gunicorn/workers/ggevent.py", line 151, in handle_request 2016-06-10_05:41:58.97129 super(GeventWorker, self).handle_request(*args) 2016-06-10_05:41:58.97129 File "/usr/lib/pymodules/python2.7/gunicorn/workers/async.py", line 93, in handle_request 2016-06-10_05:41:58.97130 respiter = self.wsgi(environ, resp.start_response) 2016-06-10_05:41:58.97130 File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__ 2016-06-10_05:41:58.97140 return self.wsgi_app(environ, start_response) 2016-06-10_05:41:58.97141 File "<flask_app_deploy_file.py>", line 18, in __call__ 2016-06-10_05:41:58.97142 File "/usr/lib/python2.7/dist-packages/werkzeug/contrib/fixers.py", line 144, in __call__ 2016-06-10_05:41:58.97142 return self.app(environ, start_response) 2016-06-10_05:41:58.97142 File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1813, in wsgi_app 2016-06-10_05:41:58.97143 ctx.push() 2016-06-10_05:41:58.97143 File "/usr/lib/python2.7/dist-packages/flask/ctx.py", line 321, in push 2016-06-10_05:41:58.97152 self.session = self.app.open_session(self.request) 2016-06-10_05:41:58.97161 File "/usr/lib/python2.7/dist-packages/flask/app.py", line 825, in open_session 2016-06-10_05:41:58.97162 return self.session_interface.open_session(self, request) 2016-06-10_05:41:58.97162 File "/usr/lib/pymodules/python2.7/flask_kvsession/__init__.py", line 159, in open_session 2016-06-10_05:41:58.97163 current_app.kvsession_store.get(sid_s) 2016-06-10_05:41:58.97163 EOFError 2016-06-10_05:41:58.97187 ERROR: Error handling request

I posted same question on http://stackoverflow.com/questions/37745600/eoferror-in-flask-kvsession-0-6-2 but nobody replied.
I can't use Flask-KVSession due to this bug.

Flask-KVSession does not respect HTTPOnly or Secure options

Flask has the following options:

SESSION_COOKIE_HTTPONLY
SESSION_COOKIE_SECURE

These options are used to indicate if the HTTPOnly and Secure flags are set on the cookie, respectively. When KVSession is used as the session implementation, these options are ignored and all cookies are set without the HTTPOnly and Secure flags.

Is this project still actively maintained?

Sorry for creating an issue for this question, I'm considering using this package but I'm concerned it might not be actively maintained. Looking at the commits/issues/PRs it seems this project might be unmaintained, is that correct?

Security concern of re-using session

I've implemented this using 0.6.2 and realized that the session is preserved across logins. This is a security concern because over the time that the session is valid the session alone may be valid and re-played.

Ideally I would have a non-repeating key for each logged in instance, or the session would get deleted upon log-out.

Invalidating sessions based on time inactive instead of time created

I want to set this up so that each time a user loads a page, it keeps track of when that was, and if a timeout (PERMANENT_SESSION_LIFETIME probably) is greater then that, clear the session.

As it stands, it looks like the created timestamp is encoded in they key for this entry. Thus, to update the timestamp when the user accesses a page, it would need to get the data from that kv map, create a new entry with a new timestamp encoded in the key, delete the old key, and get the new cookie to the client. Yuck.

I was thinking that I would do something instead where there were two fields in the kv map.

  • uniq_str
  • uniq_str_accessed

Where the first one has the session data and the second one mapped to a timestamp for the last time a page was accessed. Then I can just add a "update timestamp" call in app.before_requeset() to keep the timestamp up to date, and have clear_sessions() remove sessions accordingly.

What are your thoughts on this? Does this seem like a good way to go about it? Would you be interested in a patch that enables this as an option, or should I make this just for me?

session.new not being "fired"

Hi. I have a Flask app that needs to set a custom cookie when new sessions are created, something like this:

@app.after_request
def record_session(response):
    if session.new:
        app.logger.debug('================ NEW SESSION')

This works as expected when using Flask's default cookie storage, but when I switch to flask-kvsession, session.new is always False. Any insights, is this a bug? Thanks!

session.destroy() throws an error - AttributeError: 'KVSession' object has no attribute 'sid_s'

Should the init method set sid_s?

Rough output from error page.

File "/..../testapp.py", line 475, in load_signed_request

session.destroy()

[console ready]
>>> session <KVSession {}>
>>>

File "/..../python2.7/site-packages/Flask_KVSession-0.4dev-py2.7.egg/flaskext/kvsession.py", line 132, in destroy

if self.sid_s:

[console ready]
>>> self flaskext.kvsession.KVSession({})
>>> self.store <simplekv.memory.DictStore object at 0x101b3b950>
>>> dir(self) ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'clear', 'copy', 'destroy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'modified', 'new', 'on_update', 'permanent', 'pop', 'popitem', 'regenerate', 'setdefault', 'store', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues'  ]
>>>

AttributeError: 'KVSession' object has no attribute 'sid_s'

IntegrityError: (IntegrityError) duplicate key value violates unique constraint "sessions_pkey"

Hi,

For some reasons I suddenly get the error blow this message. I get this error two times per request of a page of my site.

Do you have any idea what's going on or how I can debug this?

Thank you.

Best regards,
Daniel

Traceback (most recent call last):
   File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 125, in handle_request
     respiter = self.wsgi(environ, resp.start_response)
  File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__
     return self.wsgi_app(environ, start_response)
   File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
     response = self.make_response(self.handle_exception(e))
   File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
    response = self.full_dispatch_request()
   File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1362, in full_dispatch_request
    response = self.process_response(response)
   File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1566, in process_response
    self.save_session(ctx.session, response)
   File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 804, in save_session
    return self.session_interface.save_session(self, session, response)
  File "/app/.heroku/python/lib/python2.7/site-packages/flaskext/kvsession.py", line 216, in save_session
     self.serialization_method.dumps(dict(session)))
  File "/app/.heroku/python/lib/python2.7/site-packages/simplekv/__init__.py", line 140, in put
     return self._put(key, data)
  File "/app/.heroku/python/lib/python2.7/site-packages/simplekv/db/sql.py", line 60, in _put
'value': data
   File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 664, in execute
 params)
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 764, in _execute_clauseelement
 compiled_sql, distilled_params
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 878, in _execute_context
 context)
  File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 871, in _execute_context
context)
   File "/app/.heroku/python/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 320, in do_execute
 cursor.execute(statement, parameters)
IntegrityError: (IntegrityError) duplicate key value violates unique constraint "sessions_pkey"
DETAIL:  Key (key)=(59f227dad1041450_5172e5ed) already exists.
 'INSERT INTO sessions (key, value) VALUES (%(key)s, %(value)s)' {'key': '59f227dad1041450_5172e5ed', 'value': <psycopg2._psycopg.Binary object at 0x2a4d878>}

Session ID from URL instead of cookies

I am working on a web application (a facebook application) which does not support cookies. I have implemented this application using flask and I am using server side sessions, implemented by Flask kvsession.

I am able to pass a key (session_key, dict key for store) to the browser and get it back using URL rewriting. How should I get back the session object from the keystore?

def open_session(self, app, request):
    key = app.secret_key

    if key is not None:
        session_key = request.args.get('session_key', None)
        if session_key:
            session_cookie = session_key
        else:
            session_cookie = request.cookies.get(
                app.config['SESSION_COOKIE_NAME'],
                None
            )

......

s = KVSession(self.serialization_method.loads(
                    self.store.get(sid_s))
                )

are there any other things like open session that I am supposed to do?

Thanks.

new simplekv versions no longer compatible

https://github.com/mbr/simplekv/releases/tag/0.11.0

App 217 stderr: Traceback (most recent call last):
App 217 stderr:   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1982, in wsgi_app
App 217 stderr:     response = self.full_dispatch_request()
App 217 stderr:   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1615, in full_dispatch_request
App 217 stderr:     return self.finalize_request(rv)
App 217 stderr:   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1632, in finalize_request
App 217 stderr:     response = self.process_response(response)
App 217 stderr:   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1858, in process_response
App 217 stderr:     self.save_session(ctx.session, response)
App 217 stderr:   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 924, in save_session
App 217 stderr:     return self.session_interface.save_session(self, session, response)
App 217 stderr:   File "/usr/local/lib/python2.7/dist-packages/flask_kvsession/__init__.py", line 193, in save_session
App 217 stderr:     store.put(session.sid_s, data, ttl)
App 217 stderr:   File "/usr/local/lib/python2.7/dist-packages/simplekv/decorator.py", line 73, in put
App 217 stderr:     self._dstore.put(self._map_key(key), *args, **kwargs))
App 217 stderr:   File "/usr/local/lib/python2.7/dist-packages/simplekv/decorator.py", line 104, in _map_key
App 217 stderr:     self._check_valid_key(key)
App 217 stderr:   File "/usr/local/lib/python2.7/dist-packages/simplekv/__init__.py", line 190, in _check_valid_key
App 217 stderr:     raise ValueError('%r is not a unicode string' % key)```

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.