pallets-eco / flask-session

Server side session extension for Flask
https://flask-session.readthedocs.io
BSD 3-Clause "New" or "Revised" License
507 stars 238 forks source link

MongoDBSessionInterface to use the default database name in connection URI #259

Closed yarreg closed 1 week ago

yarreg commented 4 months ago

Hello,

I have been using flask-sessions for session management and encountered an inconvenience while setting up MongoDBSessionInterface. When configuring a MongoDB client with a connection URI, the database name must be provided separately even though it is included in the URI. This leads to redundant and less intuitive code.

In the MongoDB world, it is typical to configure the connection using a URI, which includes all necessary details such as the host, port, and database name. This simplifies the configuration process.

Current Implementation: To use MongoDB as a session store, the current implementation requires creating a MongoClient and then explicitly providing the database name again when initializing MongoDBSessionInterface:

app = Flask()
mongo_client = MongoClient("mongodb://localhost/db_name")
app.session_interface = MongoDBSessionInterface(app, client=mongo_client, db=mongo_client.get_database().name)

In contrast, the setup for using Redis as a session store is more straightforward and requires fewer steps:

redis = Redis(host='localhost', port=6379, db=0)
app.session_interface = RedisSessionInterface(app, client=redis)

Proposal: Allow MongoDBSessionInterface to extract the database name directly from the MongoClient if the database name is included in the URI:

app = Flask()
mongo_client = MongoClient("mongodb://localhost/db_name")
app.session_interface = MongoDBSessionInterface(app, client=mongo_client)

This enhancement would align the MongoDB configuration/initialization process more closely with that of Redis etc and improve the developer experience, leveraging the typical MongoDB configuration practice of using a connection URI.

Thanks.