Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

python - How to save sessions in a Postgres database?

In one of our new projects, we want to store the session data in to a PostgreSQL database.

I have found several code snippet on the internet to do this, but none were specific for PostgreSQL.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the Flask-Session project; it offers a Flask session implementation that can store data in any SQLAlchemy supported database, including PostgreSQL.

  1. Install one of the supported PostgreSQL client libraries; most people use psycopg2.

  2. Install Flask-SQLAlchemy; it'll pull in SQLAlchemy when you do. This library integrates SQLAlchemy with Flask.

  3. Install Flask-Session and configure it to use the SQLAlchemy session type and a PostgreSQL connection URI; do so by adding the following configuration options to your Flask configuration:

     SESSION_TYPE = "sqlalchemy"
     # URI to connect to the database. postgresql:// uses psycopg2, see the documentation
     SESSION_SQLALCHEMY = "postgresql://<user>:<password>@hostname:port/database"
     # What table in the database to use, default is "sessions"
     SESSION_SQLALCHEMY_TABLE = "sessions"
    
  4. Use the Flask-Session extension in your Flask app; the following code assumes you have a app variable that is the Flask() object, already configured with the above configuration:

    from flask_session import Session
    
    # app has been set and configured
    Session(app)
    
    # alternatively, create a `Session()` object without passing in app
    # and then when ready, use `.init_app(app)`:
    # sess = Session()
    # sess.init_app(app)
    

To emphasise: because Flask-Session uses SQLAlchemy, it works with all database engines supported by SQLAlchemy, not just PostgreSQL. So the above would work for SQLite, MySQL, Oracle, Microsoft SQL Server, Firebird, Sybase, and any number of other databases with third-party SQLAlchemy dialect packages available.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...