如何将会话保存在Postgres数据库中? [英] How to save sessions in a Postgres database?

查看:95
本文介绍了如何将会话保存在Postgres数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的一个新项目中,我们希望将会话数据存储到PostgreSQL数据库中。

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

我在互联网上找到了几个代码段来执行此操作,但是没有一个特定于PostgreSQL。

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

推荐答案

使用 Flask-Session项目;它提供了Flask会话实现,可以将数据存储在任何 SQLAlchemy支持的数据库中,包括PostgreSQL。

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


  1. 安装支持的PostgreSQL客户端库;大多数人使用 psycopg2

  2. 安装 Flask-SQLAlchemy ;这样做时,它会拉入SQLAlchemy。该库将SQLAlchemy与Flask集成。

  3. 安装Flask-Session并将其配置为使用SQLAlchemy会话类型和PostgreSQL连接URI。为此,请在Flask配置中添加以下配置选项:

  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"


  • 使用烧瓶- Flask应用中的会话扩展;以下代码假定您有一个 app 变量,它是 Flask()对象,已经使用上述配置进行了配置:

  • 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)
    


  • 要强调的是:由于Flask-Session使用SQLAlchemy,因此它可以与 SQLAlchemy支持的所有数据库引擎一起使用,而不仅仅是PostgreSQL。因此,以上内容适用于SQLite,MySQL,Oracle,Microsoft SQL Server,Firebird,Sybase以及任何其他具有第三方SQLAlchemy方言包的数据库。

    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.

    这篇关于如何将会话保存在Postgres数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆