Best Python code snippet using avocado_python
powser.py
Source:powser.py
...44 return (False, 'Please get a new PoW challenge.') if with_msg else False45 valid_until, prefix = row46 if int(time()) > valid_until:47 return (False, 'This PoW challenge is expired.') if with_msg else False48 result = self._verify_hash(prefix, answer)49 if not result:50 return (False, 'The answer is incorrect.') if with_msg else False51 self._update_row(ip)52 return (True, 'Okay.') if with_msg else True53 def clean_expired(self):54 self.db.execute('DELETE FROM pow WHERE valid_until < strftime("%s", "now")')55 self.db.commit()56 def close(self):57 self.db.close()58 def _verify_hash(self, prefix, answer):59 h = hashlib.sha256()60 h.update((prefix + answer).encode())61 bits = ''.join(bin(i)[2:].zfill(8) for i in h.digest())62 return bits.startswith('0' * self.difficulty)63 def _update_row(self, ip):64 self._insert_count += 165 if self.clean_expired_rows_per > 0 and self._insert_count % self.clean_expired_rows_per == 0:66 self.clean_expired()67 prefix = secrets.token_urlsafe(self.prefix_length)[:self.prefix_length].replace('-', 'B').replace('_', 'A')68 now = int(time())69 valid_until = now + self.default_expired_time70 data = {71 'ip': ip,72 'valid_until': valid_until,73 'prefix': prefix74 }75 self.db.execute('INSERT OR REPLACE INTO pow VALUES(:ip, :valid_until, :prefix)', data)76 self.db.commit()77 return prefix, valid_until - now78 def _create_table(self):79 self.db.execute('''80 CREATE TABLE IF NOT EXISTS pow (81 ip TEXT PRIMARY KEY,82 valid_until INTEGER,83 prefix TEXT84 )85 ''')86 self.db.commit()87if __name__ == '__main__':88 powser = Powser(db_path='./pow.sqlite3')89 ip = '240.240.240.240'90 prefix, time_remain = powser.get_challenge(ip)91 print(f'''92sha256({prefix} + ???) == {'0'*powser.difficulty}({powser.difficulty})...93IP: {ip}94Time remain: {time_remain} seconds95You need to await {time_remain - powser.min_refresh_time} seconds to get a new challenge.96''')97 last = int(time())98 i = 099 while not powser._verify_hash(prefix, str(i)):100 i += 1101 print(int(time()) - last, 'seconds')102 print(f"sha256({prefix} + {i}) == {'0'*powser.difficulty}({powser.difficulty})")103 print(powser.verify_client(ip, str(i), with_msg=True))...
users_lib.py
Source:users_lib.py
...39 abort(400, 'Payload is empty.')40 if any(x not in payload.keys() for x in required_fields):41 abort(400, 'Missing required fields in payload.')42 user = db.session.query(models.Users).filter_by(email=payload['email']).first()43 if not user or not _verify_hash(payload['password'], user.password):44 abort(400, 'Invalid credentials.')45 # Generate JWT46 auth_token = user.encode_auth_token(user.id)47 print(type(auth_token), auth_token)48 # Set user as logged in49 login_user(user, remember=payload.get('remember_me', False))50 return jsonify({'status': 'success', 'message': 'Login successful.', 'auth_token': auth_token.decode()}), 20051def user_logout():52 auth_token = _get_auth_token(request.headers)53 if not auth_token:54 return jsonify({'status': 'error', 'message': 'Invalid authorizaiton token.'}), 40155 resp = models.Users.decode_auth_token(auth_token)56 if isinstance(resp, str):57 return jsonify({'status': 'error', 'message': resp}), 40158 disable_token = models.DisabledToken(token=auth_token)59 db.session.add(disable_token)60 db.session.commit()61 return jsonify({'status': 'success', 'message': 'Logout successful.'})62def gen_api_key(payload):63 user = db.session.query(models.Users).filter_by(id=current_user.id).first()64 if not user:65 abort(401, 'Unauthorized')66 if not _verify_hash(payload['password'], user.password):67 abort(400, 'Invalid credentials.')68 api_key = db.session.query(models.ApiKeys).filter_by(user_id=current_user.id).first()69 api_key.key = str(uuid4())70 db.session.commit()71 return jsonify({'status': 'success', 'key': api_key.key}), 20072def get_api_key():73 api_key = db.session.query(models.ApiKeys).filter_by(user_id=current_user.id).first()74 return jsonify({'key': api_key.key}), 20075def get_timezone():76 user = db.session.query(models.Users).filter_by(id=current_user.id).first()77 return jsonify({'timezone': user.tz}), 20078def set_timezone(payload):79 user = db.session.query(models.Users).filter_by(id=current_user.id).first()80 user.tz = payload.get('timezone', user.tz)81 db.session.commit()82 return jsonify({'status': 'success'}), 20083# ---------------------------84# Internal Functions85# ---------------------------86def _generate_hash(password):87 return sha256_crypt.hash(password)88def _verify_hash(password, password_hash):89 return sha256_crypt.verify(password, password_hash)90def _get_user(email):91 user = db.session.query(models.Users).filter_by(email=email).first()92 return user._asdict() if user else None93def _verify_password(email, password):94 user = db.session.query(models.Users).filter_by(email=email).first()95 return _verify_hash(password, user.password)96def _get_auth_token(headers):97 auth_header = headers.get('Authorization', None)98 auth_token = auth_header.split(" ")[1] if auth_header else None...
views.py
Source:views.py
...6import urllib7from django_project.settings import SECRET_KEY, PIVOTAL_API_TOKEN, \8 TOGGL_WORKSPACE_ID, TOGGL_API_TOKEN9import toggl10def _verify_hash(project_id, label, hash_key):11 if not (project_id and label and hash_key):12 raise Http404('Project not found')13 key = "|".join((project_id, label, SECRET_KEY))14 true_hash = hashlib.sha256(key).hexdigest()15 print true_hash, hash_key16 if true_hash != hash_key:17 raise Http404('Project not found')18def _get_json(url):19 print "getting url", url20 res = requests.get(url, headers={"X-TrackerToken": PIVOTAL_API_TOKEN})21 if res.status_code != 200:22 raise Exception('error with pivotal tracker: %s' % res.content)23 return res.json()24def _get_stories(project_id, label):25 url = "https://www.pivotaltracker.com" \26 "/services/v5/projects/%s/stories" \27 "?with_label=%s" % (project_id, label)28 return _get_json(url)29def _get_story(project_id, story_id):30 url = "https://www.pivotaltracker.com" \31 "/services/v5/projects/%s/stories/%s" \32 % (project_id, story_id)33 return _get_json(url)34def _get_tasks(project_id, story_id):35 url = "https://www.pivotaltracker.com" \36 "/services/v5/projects/%s/stories/%s/tasks" \37 % (project_id, story_id)38 return _get_json(url)39def _get_comments(project_id, story_id):40 url = "https://www.pivotaltracker.com" \41 "/services/v5/projects/%s/stories/%s/comments" \42 % (project_id, story_id)43 return _get_json(url)44def stories(request, project_id, tag_filter, hash_key):45 _verify_hash(project_id, tag_filter, hash_key)46 context = {47 'stories': _get_stories(project_id, tag_filter),48 'show_completed': request.GET.get('show_completed'),49 }50 return render(request, 'pivotal_stories.html', context)51def story_details(request, project_id, tag_filter, hash_key, story_id):52 _verify_hash(project_id, tag_filter, hash_key)53 context = {54 'story': _get_story(project_id, story_id),55 'comments': _get_comments(project_id, story_id),56 'tasks': _get_tasks(project_id, story_id),57 }58 return render(request, 'pivotal_story_detail.html', context)59def tasks(request, project_id, tag_filter, hash_key, story_id):60 _verify_hash(project_id, tag_filter, hash_key)61 context = {62 'story': _get_story(project_id, story_id),63 'tasks': _get_tasks(project_id, story_id),64 }65 return render(request, 'pivotal_tasks.html', context)66def tasks(request, project_id, tag_filter, hash_key, story_id):67 _verify_hash(project_id, tag_filter, hash_key)68 found_project = None69 for project in toggl.get_projects(TOGGL_WORKSPACE_ID):70 if project.get('name').endswith('#%s' % story_id):71 found_project = project72 break73 if not found_project:74 return [{'none found'}]75 data = toggl.get_project_hours(TOGGL_WORKSPACE_ID, found_project.get('id'))...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!