I am trying to store some session data using Django and Angular2.
I noticed something strange, or do not understand. I was stuck on this for a while on my project. Instead, I tried to test a simple example to understand what's happening. Finally, I was able to store the session data when I made the requests using POSTMAN, and the sessionId was recognized.
However when I made the request through my Angular app, the session data saving was successful but it was unable to access the saved session data on the next request.
I also noticed that when done with Angular, a new session is created on every request. So it's not recognizing the session and creating a new session each time.
Any ideas on what might be causing this? Thank you for your help.
Django Views
class TestSaveSessionView(APIView):
authentication_classes = (TokenAuthentication,)
def post(self, request):
# set new data
request.session['user_id'] = 20
request.session['team'] = 'Barcelona'
return Response("Session Data Saved")
class TestAccessSessionView(APIView):
authentication_classes = (TokenAuthentication,)
def post(self, request):
response = ""
print("USER ID", request.session.get('user_id'))
if request.session.get('user_id'):
user_id = request.session.get('user_id')
response += "User Id : {0} <br>".format(user_id)
if request.session.get('team'):
team = request.session.get('team')
response += "Team : {0} <br>".format(team)
if not response:
return Response("No session data")
else:
return Response(response)
Angular Service
export class TestSessionService {
constructor(private http: HttpClient) { }
baseUrl: string = environment.apiURL;
getAuthenticationHeaders() {
const token = localStorage.getItem('token');
const httpHeaders = new HttpHeaders(
{
'Content-Type': 'application/json; charset-utf-8', 'Authorization': 'Token ' + token
}
);
return { headers: httpHeaders };
}
testSaveSession(): Observable<any> {
const body = {
};
return this.http.post(this.baseUrl + 'checkout/test_save_session/', body, this.getAuthenticationHeaders());
}
testAccessSession(): Observable<any> {
const body = {
};
return this.http.post(this.baseUrl + 'checkout/test_access_session/', body, this.getAuthenticationHeaders());
}
}
Results w/ Postman
"Session Data Saved"
"User Id : 20 Team : Barcelona"
Results w/ Angular
"Session Data Saved"
"No Session Data"
I am using 'django.contrib.sessions' in INSTALLED_APPS. I noticed that when I make the request to access the session data over Chrome, Django is unable to find the Cookie called "sessionid".
In the browser's development environment, Application --> Cookies. The sessionid is there.
class SessionMiddleware(MiddlewareMixin):
# RemovedInDjango40Warning: when the deprecation ends, replace with:
# def __init__(self, get_response):
def __init__(self, get_response=None):
self._get_response_none_deprecation(get_response)
self.get_response = get_response
self._async_check()
engine = import_module(settings.SESSION_ENGINE)
self.SessionStore = engine.SessionStore
def process_request(self, request):
print("sessionid is ", request.COOKIES.get(settings.SESSION_COOKIE_NAME))
session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
request.session = self.SessionStore(session_key)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…