FastAPI server-side HTTP sessions management libraries #11510
-
First Check
Commit to Help
Example CodeThis question is not code related. I don't have a problem. DescriptionPlease help me with the following query. I have only learned FastAPI during this past three weeks. I have done a bit Flask before. With Flask, we can use the Flask-Session package to manage server-side HTTP sessions: we can write our temporary session data into a MySQL table. I have been looking for an equivalence package in FastAPI, I have not been able to find one. Would you be able to suggest something, please? Thank you and best regards. Operating SystemOther Operating System DetailsThis question is not related to any operating system. FastAPI Version0.110.2 Pydantic Version2.7.1 Python VersionPython 3.10.1 Additional ContextThis is the first FastAPI so-called web-server application which I have written. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
There is a library called starsessions, which could be what you need. |
Beta Was this translation helpful? Give feedback.
-
Hi @hasansezertasan, I have successfully used the Have you come across this before, please? If you have, would be able to point out what I have missed, please? I am reproducing the post below. Thank you. pytest can't seem to access Redis session storeHi, Thank you for this library. I'm learning FastAPI and I find this library very helpful. I have used its Redis session store without any problem in my application proper. However, my integration test using What have I missed please? Content of import pytest
from fastapi.testclient import TestClient
from . import test_main
@pytest.fixture(scope='module')
def app():
return test_main.app
@pytest.fixture(scope='module')
def test_client(app):
return TestClient(app) Following is the def __login_page_context(inc_not_login_msg=False):
context = {"title": "FastAPI Login"}
if inc_not_login_msg:
context.update({"message": "This session has not been logged in before"})
return context
@router.post("/logout", response_class=HTMLResponse)
async def logout(request: Request):
context = __login_page_context(
inc_not_login_msg=request.session.get("access_token")==None)
request.session.clear()
return templates.TemplateResponse(request=request, name="auth/login.html", context=context) When the test gets to this endpoint, The integration test is not able to clear the session content from Redis. While the application is able to. That is, the application works as expected. The call below has no effect during test, the corresponding Redis session does not get cleared: request.session.clear() And this is my test method: @pytest.mark.auth_integration
def test_integration_valid_login(test_client):
"""
Test /auth/token path with a valid credential.
"""
try:
login_data = {
"username": "[email protected]",
"password": "password"
}
response = test_client.post(
"/auth/token",
data=login_data,
headers={ 'Content-Type': 'application/x-www-form-urlencoded'}
)
assert response != None
assert response.status_code == HTTPStatus.OK.value
status = response.json()
assert status['access_token'] == '[email protected]'
assert status['token_type'] == 'bearer'
print("\ncookie session -> ", test_client.cookies.get('session'))
finally:
# Logout. Clean up server sessions.
test_client.post('/auth/logout')
And Thank you and best regards, ...behai. |
Beta Was this translation helpful? Give feedback.
-
With the helps of ChatGPT, I have the solution for it: @pytest.mark.behai_only
def test_integration_valid_login(test_client):
"""
Test /auth/token path with a valid credential.
"""
try:
login_data = {
'username': '[email protected]',
'password': 'password'
}
response = test_client.post(
'/auth/token',
data=login_data,
headers={'Content-Type': 'application/x-www-form-urlencoded'}
)
assert response != None
assert response.status_code == HTTPStatus.OK.value
status = response.json()
assert status['access_token'] == '[email protected]'
assert status['token_type'] == 'bearer'
session_cookie = response.cookies.get('session')
finally:
test_client.cookies = {'session': session_cookie}
test_client.post('/auth/logout') |
Beta Was this translation helpful? Give feedback.
There is a library called starsessions, which could be what you need.