How to use session_id method in pytest-mozwebqa

Best Python code snippet using pytest-mozwebqa_python

session.py

Source:session.py Github

copy

Full Screen

...81 cookie_domain = self._config.cookie_domain82 httponly = self._config.httponly83 self.session_id = web.cookies().get(cookie_name)84 # protection against session_id tampering85 if self.session_id and not self._valid_session_id(self.session_id):86 self.session_id = None87 self._check_expiry()88 if self.session_id:89 d = self.store[self.session_id]90 self.update(d)91 self._validate_ip()92 93 if not self.session_id:94 self.session_id = self._generate_session_id()95 if self._initializer:96 if isinstance(self._initializer, dict):97 self.update(deepcopy(self._initializer))98 elif hasattr(self._initializer, '__call__'):99 self._initializer()100 101 self.ip = web.ctx.ip102 def _check_expiry(self):103 # check for expiry104 if self.session_id and self.session_id not in self.store:105 if self._config.ignore_expiry:106 self.session_id = None107 else:108 return self.expired()109 def _validate_ip(self):110 # check for change of IP111 if self.session_id and self.get('ip', None) != web.ctx.ip:112 if not self._config.ignore_change_ip:113 return self.expired() 114 115 def _save(self):116 if not self.get('_killed'):117 self._setcookie(self.session_id)118 self.store[self.session_id] = dict(self._data)119 else:120 self._setcookie(self.session_id, expires=-1)121 122 def _setcookie(self, session_id, expires='', **kw):123 cookie_name = self._config.cookie_name124 cookie_domain = self._config.cookie_domain125 httponly = self._config.httponly126 secure = self._config.secure127 web.setcookie(cookie_name, session_id, expires=expires, domain=cookie_domain, httponly=httponly, secure=secure)128 129 def _generate_session_id(self):130 """Generate a random id for session"""131 while True:132 rand = os.urandom(16)133 now = time.time()134 secret_key = self._config.secret_key135 session_id = sha1("%s%s%s%s" %(rand, now, utils.safestr(web.ctx.ip), secret_key))136 session_id = session_id.hexdigest()137 if session_id not in self.store:138 break139 return session_id140 def _valid_session_id(self, session_id):141 rx = utils.re_compile('^[0-9a-fA-F]+$')142 return rx.match(session_id)143 144 def _cleanup(self):145 """Cleanup the stored sessions"""146 current_time = time.time()147 timeout = self._config.timeout148 if current_time - self._last_cleanup_time > timeout:149 self.store.cleanup(timeout)150 self._last_cleanup_time = current_time151 def expired(self):152 """Called when an expired session is atime"""153 self._killed = True154 self._save()...

Full Screen

Full Screen

util.py

Source:util.py Github

copy

Full Screen

1from .models import SpotifyToken2from django.utils import timezone3from datetime import timedelta4from .credentials import CLIENT_ID, CLIENT_SECRET5from requests import get, post, put6BASE_URL = "https://api.spotify.com/v1/me/"7def get_user_tokens(session_id):8 user_tokens = SpotifyToken.objects.filter(user=session_id)9 if user_tokens.exists():10 return user_tokens[0]11 return None12# session_id is the session key of the user13def update_or_create_user_tokens(session_id, access_token, token_type, expires_in, refresh_token):14 tokens = get_user_tokens(session_id)15 # token expires in now + time got from spotify api16 expires_in = timezone.now() + timedelta(seconds=expires_in)17 if tokens:18 tokens.access_token = access_token19 tokens.refresh_token = refresh_token20 tokens.expires_in = expires_in21 tokens.token_type = token_type22 tokens.save(update_fields=['access_token',23 'refresh_token', 'expires_in', 'token_type'])24 else:25 tokens = SpotifyToken(user=session_id, access_token=access_token,26 refresh_token=refresh_token, token_type=token_type, expires_in=expires_in)27 tokens.save()28# check if the token is expired or not and refresh token in case of expiration29def is_spotify_authenticated(session_id):30 tokens = get_user_tokens(session_id)31 if tokens:32 expiry = tokens.expires_in33 if expiry <= timezone.now():34 refresh_spotify_token(session_id)35 36 return True37 return False38def refresh_spotify_token(session_id):39 refresh_token = get_user_tokens(session_id).refresh_token40 # request a refreshed token to spotify41 response = post('https://accounts.spotify.com/api/token', data={42 'grant_type': 'refresh_token',43 'refresh_token': refresh_token,44 'client_id': CLIENT_ID,45 'client_secret': CLIENT_SECRET46 }).json()47 access_token = response.get('access_token')48 token_type = response.get('token_type')49 expires_in = response.get('expires_in')50 # refresh token stays the same, so we don't need to get new one. Otherwise we will get constraint error51 # refresh_token = response.get('refresh_token')52 update_or_create_user_tokens(53 session_id, access_token, token_type, expires_in, refresh_token)54# send request to spotify55def execute_spotify_api_request(session_id, endpoint, post_=False, put_=False):56 tokens = get_user_tokens(session_id)57 headers = {'Content-Type': 'application/json',58 'Authorization': "Bearer " + tokens.access_token}59 if post_:60 post(BASE_URL + endpoint, headers=headers)61 if put_:62 put(BASE_URL + endpoint, headers=headers)63 # we care only about response in get request64 response = get(BASE_URL + endpoint, {}, headers=headers)65 try:66 return response.json()67 except:68 return {'Error': 'Issue with request'}69def play_song(session_id):70 return execute_spotify_api_request(session_id, "player/play", put_=True)71def pause_song(session_id):72 return execute_spotify_api_request(session_id, "player/pause", put_=True)73def skip_song(session_id):...

Full Screen

Full Screen

session_db_auth.py

Source:session_db_auth.py Github

copy

Full Screen

...20 return21 new_user = UserSession(user_id=user_id, session_id=session_id)22 new_user.save()23 return session_id24 def user_id_for_session_id(self, session_id=None):25 """26 user_id_for_session_id.27 """28 if not session_id:29 return30 try:31 us_list = UserSession.search({session_id: session_id})32 for us in us_list:33 created_at = us.get('created_at', None)34 if not created_at:35 return36 if (datetime.now() > created_at +37 timedelta(seconds=self.session_duration)):38 return...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pytest-mozwebqa automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful