How to use rand_uuid method in tempest

Best Python code snippet using tempest_python

identity_verification.py

Source:identity_verification.py Github

copy

Full Screen

1import json2import boto33import logging4import uuid5import random6import time7import os8from base64 import b64decode9from botocore.exceptions import ClientError10logger = logging.getLogger()11sns_client = boto3.client('sns')12ddb_idv = boto3.client('dynamodb')13ddb_users = boto3.resource('dynamodb')14user_table = ddb_users.Table(os.environ['USER_TABLE_NAME'])15def close(session_attributes, fulfillment_state, message):16 response = {17 'sessionAttributes': session_attributes,18 'dialogAction': {19 'type': 'Close',20 'fulfillmentState': fulfillment_state,21 'message': {22 "contentType": "PlainText",23 "content": message24 },25 }26 }27 return response28def elicit_slot(session_attributes, intent_name, slots, slot_to_elicit, message):29 return {30 'sessionAttributes': session_attributes,31 'dialogAction': {32 'type': 'ElicitSlot',33 'intentName': intent_name,34 'slots': slots,35 'slotToElicit': slot_to_elicit,36 'message': message37 }38 }39def delegate(session_attributes, slots):40 return {41 'sessionAttributes': session_attributes,42 'dialogAction': {43 'type': 'Delegate',44 'slots': slots45 }46 }47def try_ex(func):48 """49 Call passed in function in try block. If KeyError is encountered return None.50 This function is intended to be used to safely access dictionary.51 Note that this function would have negative impact on performance.52 """53 try:54 return func()55 except KeyError:56 return None57def get_one_time_code():58 #write onetime code to ddb - with this contact ID. as the primary key59 rand_uuid = str(uuid.uuid4())60 epoch = int(time.time())61 OTP = ''62 for _ in range(6):63 OTP += str(random.randint(0,9))64 var = ddb_idv.put_item(65 TableName=os.environ['OTP_TABLE_NAME'],66 Item={67 'uuid': {'S':str(rand_uuid)},68 'pin': {'S':str(OTP)},69 'timeStamp': {'N':str(epoch)}70 }71 )72 #return one time random 6 digit key73 return rand_uuid, OTP74def send_pin(phone_number, msg):75 #query user phone number from ddb table76 result = sns_client.publish(PhoneNumber=phone_number, Message=msg)77 return result78def get_user_details(user_id):79 #ID verification section - user_id and vcode80 try:81 response = user_table.query(82 ExpressionAttributeValues={83 ':user_id': user_id84 },85 IndexName = 'user_id-index',86 KeyConditionExpression='user_id = :user_id',87 )88 except ClientError as e:89 print(e.response['Error']['Message'])90 else:91 items = response['Items']92 if not items:93 return None94 else:95 email = try_ex(lambda: items[0]["email"])96 phone_num = try_ex(lambda: items[0]['PhoneNumber'])97 customerName = try_ex(lambda: items[0]['firstName'])98 return email, phone_num, customerName99def check_pin(pin, uuid):100 epoch = int(time.time())101 #queries DDB table for the OTP based on the uuid102 result = ddb_idv.get_item(103 TableName=os.environ['OTP_TABLE_NAME'],104 Key={'uuid': {'S':str(uuid)}}105 )106 if result['ResponseMetadata']['HTTPStatusCode'] == 200:107 if 'Item' in result.keys():108 correct_pin = result['Item']['pin']['S']109 timestamp = result['Item']['timeStamp']['N']110 valid = epoch - int(timestamp) < 60111 if not valid:112 print("expired")113 if pin == correct_pin and valid:114 return True115 else:116 return False117 else:118 logger.debug('dynamodb request error')119 return False120# function to perform IDV through verification code sent through email.121def identity_verification(user_id,vcode):122 #ID verification section - user_id and vcode123 try:124 response = user_table.query(125 ExpressionAttributeValues={126 ':user_id': user_id127 },128 IndexName = 'user_id-index',129 KeyConditionExpression='user_id = :user_id',130 )131 except ClientError as e:132 print(e.response['Error']['Message'])133 else:134 items = response['Items']135 if not items:136 return -1137 else:138 # print("Found user")139 # print(items)140 if str(vcode) == str(items[0]["vcode"]):141 return 1142 else:143 return 0144def meter_reading(intent_request):145 slots = intent_request['currentIntent']['slots']146 user_id = intent_request['currentIntent']['slots']['UserId']147 vcode = intent_request['currentIntent']['slots']['vcode']148 print (user_id,vcode)149 print(intent_request['sessionAttributes'])150 output_session_attributes = intent_request['sessionAttributes']151 authenticated = 0152 if output_session_attributes !={}:153 if "auth" in output_session_attributes:154 authenticated = output_session_attributes["auth"]155 if not user_id:156 return elicit_slot(157 output_session_attributes,158 'MeterReading',159 slots,160 'UserId',161 {'contentType': 'PlainText', 'content': 'Thanks for submitting your meter read with us. Before we start, what is your account ID?'}162 )163 elif not vcode:164 #alternatively, use OTP:165 customerinfo = get_user_details(user_id)166 #if not able to find user info with user_id provided167 if not customerinfo:168 return elicit_slot(169 output_session_attributes,170 'MeterReading',171 slots,172 'UserId',173 {'contentType': 'PlainText', 'content': 'Sorry, your user id is incorrect, can you provide me again your user ID?'}174 )175 else:176 email, phone_num, customerName = customerinfo177 if phone_num and customerName:178 rand_uuid, one_time_code = get_one_time_code()179 output_session_attributes['uuid'] = rand_uuid180 output_session_attributes['customer_phone'] = phone_num181 output_session_attributes['customer_name'] = customerName182 slots['Phone'] = phone_num183 msg = 'Hi {}! This is your one time code: '.format(customerName) + one_time_code184 result = send_pin(phone_num, msg)185 output_session_attributes['count'] = 1186 return elicit_slot(187 output_session_attributes,188 'MeterReading',189 slots,190 'vcode',191 {'contentType': 'PlainText', 'content': 'Thank you! We have just sent you a 6 digits verification code to your mobile. Do you mind providing it back to me?'}192 )193 else:194 return close(output_session_attributes, 'Fulfilled', 'Sorry, we are having problem retrieving your information, please contact customer support.')195 elif authenticated ==0:196 #auth = identity_verification(user_id,vcode)197 uuid = try_ex(lambda: output_session_attributes['uuid'])198 # count is number of OPT sent already199 count = int(try_ex(lambda: output_session_attributes['count']))200 auth = check_pin(vcode, uuid)201 print (auth)202 if auth:203 output_session_attributes["auth"] = auth204 return delegate(output_session_attributes, intent_request['currentIntent']['slots'])205 else:206 if count < 2:207 rand_uuid, one_time_code = get_one_time_code()208 output_session_attributes['uuid'] = rand_uuid209 phone_num = slots['Phone']210 customerName = output_session_attributes['customer_name']211 msg = 'Hi {}! This is your one time code: '.format(customerName) + one_time_code212 result = send_pin(phone_num, msg)213 output_session_attributes['count'] = count+1214 return elicit_slot(215 output_session_attributes,216 'MeterReading',217 slots,218 'vcode',219 {'contentType': 'PlainText', 'content': 'Sorry, your verification code is incorrect. Let us try again. We have just sent you another 6 digits verification code to your mobile. Do you mind providing the latest one back to me?'}220 )221 else:222 return close(output_session_attributes, 'Fulfilled', 'Sorry, your verification code is still incorrect, please contact customer support.')223 # authenticated ==1 and we can delegate elicit slot to Lex224 else:225 return delegate(output_session_attributes, intent_request['currentIntent']['slots'])226def water_leak(intent_request):227 slots = intent_request['currentIntent']['slots']228 user_id = intent_request['currentIntent']['slots']['UserId']229 vcode = intent_request['currentIntent']['slots']['vcode']230 print (user_id,vcode)231 print(intent_request['sessionAttributes'])232 output_session_attributes = intent_request['sessionAttributes']233 authenticated = 0234 if output_session_attributes !={}:235 if "auth" in output_session_attributes:236 authenticated = output_session_attributes["auth"]237 if not user_id:238 return elicit_slot(239 output_session_attributes,240 'WaterLeak',241 slots,242 'UserId',243 {'contentType': 'PlainText', 'content': 'Before we start, what is your account number? This should be 7 digits'}244 )245 elif not vcode:246 #alternatively, use OTP:247 customerinfo = get_user_details(user_id)248 #if not able to find user info with user_id provided249 if not customerinfo:250 return elicit_slot(251 output_session_attributes,252 'WaterLeak',253 slots,254 'UserId',255 {'contentType': 'PlainText', 'content': 'Sorry, your account number is incorrect, can you provide your account number again?'}256 )257 else:258 email, phone_num, customerName = customerinfo259 if phone_num and customerName:260 rand_uuid, one_time_code = get_one_time_code()261 output_session_attributes['uuid'] = rand_uuid262 output_session_attributes['customer_phone'] = phone_num263 output_session_attributes['customer_name'] = customerName264 slots['Phone'] = phone_num265 msg = 'Hi {}! This is your one time code: '.format(customerName) + one_time_code266 result = send_pin(phone_num, msg)267 output_session_attributes['count'] = 1268 return elicit_slot(269 output_session_attributes,270 'WaterLeak',271 slots,272 'vcode',273 {'contentType': 'PlainText', 'content': 'Thank you! We have just sent you a 6 digits verification code to your mobile. Do you mind providing it back to me?'}274 )275 else:276 return close(output_session_attributes, 'Fulfilled', 'Sorry, we are having problem retrieving your information, please contact customer support.')277 elif authenticated ==0:278 #auth = identity_verification(user_id,vcode)279 uuid = try_ex(lambda: output_session_attributes['uuid'])280 # count is number of OPT sent already281 count = int(try_ex(lambda: output_session_attributes['count']))282 auth = check_pin(vcode, uuid)283 if auth:284 output_session_attributes["auth"] = auth285 return delegate(output_session_attributes, intent_request['currentIntent']['slots'])286 else:287 if count < 2:288 rand_uuid, one_time_code = get_one_time_code()289 output_session_attributes['uuid'] = rand_uuid290 phone_num = slots['Phone']291 customerName = output_session_attributes['customer_name']292 msg = 'Hi {}! This is your one time code: '.format(customerName) + one_time_code293 result = send_pin(phone_num, msg)294 output_session_attributes['count'] = count+1295 return elicit_slot(296 output_session_attributes,297 'WaterLeak',298 slots,299 'vcode',300 {'contentType': 'PlainText', 'content': 'Sorry, your verification code is incorrect. Let us try again. We have just sent you another 6 digits verification code to your mobile. Do you mind providing the latest one back to me?'}301 )302 else:303 return close(output_session_attributes, 'Fulfilled', 'Sorry, your verification code is still incorrect, please contact customer support.')304 # authenticated ==1 and we can delegate elicit slot to Lex305 else:306 return delegate(output_session_attributes, intent_request['currentIntent']['slots'])307def dispatch(intent_request):308 """309 Called when the user specifies an intent for this bot.310 """311 logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name']))312 intent_name = intent_request['currentIntent']['name']313 # Dispatch to your bot's intent handlers314 if intent_name == 'MeterReading':315 return meter_reading(intent_request)316 elif intent_name == 'WaterLeak':317 return water_leak(intent_request)318 raise Exception('Intent with name ' + intent_name + ' not supported')319def lambda_handler(event, context):320 print(event)321 logger.debug('event.bot.name={}'.format(event['bot']['name']))...

Full Screen

Full Screen

views.py

Source:views.py Github

copy

Full Screen

1# from django.shortcuts import render2import json3# from rest_framework_jwt.serializers import jwt_payload_handler4# import jwt5# from django.contrib.auth.hashers import Argon2PasswordHasher6#7# from rest_framework.decorators import api_view, schema8# import numpy as np9# import django_rq10from datetime import timedelta11# from django.utils import timezone12import django_rq13scheduler = django_rq.get_scheduler('default')14from .models import Sertificates15# from django.http import HttpResponse16from django.http import HttpResponseRedirect, HttpResponse17# from django.urls import reverse18# read env19import environ20from simple_pdf.tasks import delete_later_pdf21from fpdf import FPDF22env = environ.Env(23 DEBUG=(bool, False)24)25environ.Env.read_env('.env')26# Create your views here.27# from rest_framework.permissions import AllowAny, IsAuthenticated28# from rest_framework.views import APIView29# from rest_framework.response import Response30# from rest_framework import status31# from rest_framework.generics import RetrieveUpdateAPIView32# from rest_framework.decorators import permission_classes33# MAILER34# from django.core.mail import EmailMultiAlternatives35# from django.contrib.auth.tokens import PasswordResetTokenGenerator36# from django.core.mail import EmailMessage37# Create your views here.38from urllib.request import urlopen39import urllib.request40import io41import numpy as np42from PIL import ImageFont, ImageDraw, Image43import pandas as pd44import requests45from django.views.decorators.csrf import csrf_exempt46def transform_name(name):47 if len(name) >= 21:48 name_list = name.split()49 name = name_list[0] + " " +name_list[1] + " \n" + name_list[2]50 return name51 else:52 return name53def transform_nameV2(s, n):54 l = s.split()55 for i in range(1, len(l)+1):56 if sum(map(len, l[:i])) + i - 1 > n:57 return ' '.join(l[:i-1]) + " \n" + ' '.join(l[i-1:])58 return s59def hex_to_rgb(value):60 value = value.lstrip('#')61 lv = len(value)62 return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))63@csrf_exempt64def start(request):65 if request.method == 'GET':66 # URL = 'https://s3.eu-central-1.amazonaws.com/cdn.facetoapp.com/media/faces/2019-01-16_121717.7474150000.jpg'67 #68 # with urllib.request.urlopen(URL) as url:69 # f = io.BytesIO(url.read())70 #71 # img = Image.open(f)72 #73 # FONT_PATH = 'https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf'74 #75 # with urllib.request.urlopen(FONT_PATH) as url:76 # f1 = io.BytesIO(url.read())77 #78 # ImageFont.truetype(f1, 13)79 #80 # return render(request, 'pdf_create/login.html')81 return render(request, 'pdf_create/signin.html')82@csrf_exempt83def generate_pdf(request):84 if request.is_ajax() and request.POST:85 #open IMG86 URL_IMG = 'https://s3.eu-central-1.amazonaws.com/cdn.facetoapp.com/media/faces/2019-01-16_121717.7474150000.jpg'87 with urllib.request.urlopen(URL_IMG) as url:88 f = io.BytesIO(url.read())89 img = Image.open(f)90 #open FONT91 URL_FONT = 'https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf'92 with urllib.request.urlopen(URL_FONT) as url:93 font_byte = io.BytesIO(url.read())94 #open CSV95 url = "https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv"96 s = requests.get(url).content97 data_csv = pd.read_csv(io.StringIO(s.decode('utf-8')))98 draw = ImageDraw.Draw(img)99 # # use a bitmap font100 # font = ImageFont.load("arial.pil")101 # draw.text((10, 10), "hello", font=font)102 # use a truetype font103 font = ImageFont.truetype(font_byte, 13)104 draw.text((10, 10), data_csv['Country'][0], font=font, fill=(0, 0, 0, 255))105 img.save('imgs/123.jpg', format='jpeg')106 # msg = EmailMessage('Subject of the Email', 'Body of the email', 'from@email.com', ['to@email.com'])107 # msg.content_subtype = "html"108 # msg.attach_file('pdfs/Instructions.pdf')109 # msg.send()110 # subject, from_email, to = 'confirm your email', 'faceappmailer@gmail.com', 'pupkin11999@gmail.com'111 # text_content = 'Confirmation of registration'112 # html_content = 'Confirm Registretion'113 # msg = EmailMultiAlternatives(subject, text_content, from_email, [to])114 # msg.attach_alternative(html_content, "text/html")115 # msg.attach_file('123.jpg')116 # msg.send()117 return render(request, 'pdf_create/start.html')118@csrf_exempt119def login(request):120 if request.method == "POST":121 # return HttpResponseRedirect(reverse('simple_pdf:login'))122 return render(request, 'pdf_create/index.html')123 if request.method == "GET":124 # return HttpResponseRedirect(reverse('simple_pdf:login'))125 return render(request, 'pdf_create/index.html')126@csrf_exempt127def cutaway(request):128 if request.method == "GET":129 # return render(request, 'pdf_create/carousel.html')130 return render(request, 'pdf_create/choose.html')131 # return HttpResponseRedirect(reverse('simple_pdf:cau')132from textwrap import wrap133from wand.color import Color134from wand.drawing import Drawing135from wand.image import Image136draw = Drawing()137from PIL import Image as PILImage138import uuid139import pathlib140import shutil141@csrf_exempt142def manual_pdf(request):143 if request.is_ajax() and request.POST:144 try:145 names = request.POST.getlist("names[]")146 courses = request.POST.getlist("courses[]")147 town = request.POST['town']148 page_images = []149 rand_uuid = uuid.uuid4()150 s = Sertificates.objects.first()151 s.payment = s.payment + len(courses)152 s.save()153 pathlib.Path('imgs/'+ str(rand_uuid)).mkdir(parents=True, exist_ok=True)154 pathlib.Path('pdfs/'+ str(rand_uuid)).mkdir(parents=True, exist_ok=True)155 for i in np.arange(len(courses)):156 draw = Drawing()157 with Image(filename='imgs/sertf20.jpg') as image:158 draw.font = 'open-sans/Montserrat/Montserrat-Bold.ttf'159 # 19 = 25160 # draw.font_size = 186161 draw.font_size = 25*4162 draw.fill_color = Color('#333333')163 # name = transform_name(names[i])164 name = transform_nameV2(names[i], 21)165 course = transform_nameV2(courses[i], 21)166 # draw.text(340, 2385, name)167 # draw.text(340, 3173, courses[i])168 draw.text(205, 1418 + 30, name)169 draw.text(205, 1888 + 30, course)170 draw.font = 'open-sans/Montserrat/Montserrat-Regular.ttf'171 draw.font_size = 8*5172 # draw.text(684, 5105, town)173 draw.text(339+30, 3040, town)174 # draw.viewbox(340, 2385, 340 + 2300, 2385 + 400)175 draw(image)176 image.save(filename='imgs/'+str(rand_uuid)+'/img_' + str(i) + '.jpg')177 # im1 = PILImage.open("imgs/" + str(rand_uuid) + "/img_0.jpg")178 # for i in np.arange(1, len(names)):179 # im2 = PILImage.open("imgs/"+str(rand_uuid)+"/img_" + str(i) +".jpg")180 # page_images.append(im2)181 # shutil.rmtree('imgs/' + str(rand_uuid))182 pdf1_filename = "pdfs/" + str(rand_uuid) + "/cutway.pdf"183 # im1.save(pdf1_filename, "PDF", resolution=100.0, save_all=True, append_images=page_images)184 pdf = FPDF('P','mm','A4')185 pdf.set_auto_page_break(0)186 for i in np.arange(0, len(names)):187 # im2 = PILImage.open("imgs/" + str(rand_uuid) + "/img_" + str(i) + ".jpg")188 # for image in imagelist:189 pdf.add_page()190 pdf.image("imgs/" + str(rand_uuid) + "/img_" + str(i) + ".jpg",w=200)191 pdf.output(pdf1_filename, "F")192 scheduler.enqueue_in(timedelta(days=1), delete_later_pdf, str(rand_uuid))193 # scheduler.enqueue_in(timedelta(minutes=1), delete_later_pdf, str(rand_uuid))194 data = json.dumps({'success': str(rand_uuid), 'error': None, 'description': None})195 return HttpResponse(data, content_type='application/json')196 except Exception as e:197 data = json.dumps({'success': None, 'error': True, 'description': "Произошла ошибка \n" + str(e)})198 return HttpResponse(data, content_type='application/json')199 200@csrf_exempt201def manual(request):202 if request.method == "GET":203 return render(request, 'pdf_create/manual.html')204 # return HttpResponseRedirect(reverse('simple_pdf:cau')205@csrf_exempt206def exel(request):207 if request.method == "GET":208 return render(request, 'pdf_create/exel.html')209 # return HttpResponseRedirect(reverse('simple_pdf:cau')210from django.shortcuts import render211from django.conf import settings212from django.core.files.storage import FileSystemStorage213import os214@csrf_exempt215def upload_exel(request):216 if request.method == 'POST' and request.FILES['file']:217 try:218 myfile = request.FILES['file']219 fs = FileSystemStorage()220 filename = fs.save(myfile.name, myfile)221 # town = request.POST['town']222 # print(request.POST['town'])223 # uploaded_file_url = fs.url(filename)224 # print(uploaded_file_url)225 rand_uuid = uuid.uuid4()226 pathlib.Path('imgs/'+ str(rand_uuid)).mkdir(parents=True, exist_ok=True)227 pathlib.Path('pdfs/'+ str(rand_uuid)).mkdir(parents=True, exist_ok=True)228 data = pd.read_csv(myfile.name)229 s = Sertificates.objects.first()230 s.payment = s.payment + data.count()[0]231 s.save()232 # draw = Drawing()233 # image_orig = Image(filename='imgs/sertf20.jpg')234 for i in np.arange(data.count()[0]):235 name = data[data.columns[0]][i]236 course = data[data.columns[1]][i]237 town = data[data.columns[2]][i]238 with Image(filename='imgs/sertf20.jpg') as image:239 draw = Drawing()240 draw.font = 'open-sans/Montserrat/Montserrat-Bold.ttf'241 # 19 242 # draw.font_size = 186243 draw.font_size = 25*4244 draw.fill_color = Color('#333333')245 # name = transform_name(name)246 name = transform_nameV2(name, 21)247 course = transform_nameV2(course, 21)248 draw.text(205, 1418 + 30, name)249 draw.text(205, 1888 + 30, course)250 # draw.text(340, 2385, name)251 # draw.text(340, 3173, course)252 # 10253 draw.font_size = 8*5254 # draw.font_size = 100255 draw.font = 'open-sans/Montserrat/Montserrat-Regular.ttf'256 257 # draw.text(684, 5105, town)258 draw.text(339+30, 3040, town)259 draw(image)260 image.save(filename='imgs/' + str(rand_uuid) +'/img_' + str(i) + '.jpg')261 # page_images = []262 # for i in np.arange(1, data.count()[0]):263 # im2 = PILImage.open("imgs/" + str(rand_uuid) + "/img_" + str(i) + ".jpg")264 # page_images.append(im2)265 pdf1_filename = "pdfs/" + str(rand_uuid) + "/cutway.pdf"266 # im1 = PILImage.open("imgs/" + str(rand_uuid) + "/img_0.jpg")267 # im1.save(pdf1_filename, "PDF", resolution=100.0, save_all=True, append_images=page_images)268 pdf = FPDF('P','mm','A4')269 pdf.set_auto_page_break(0)270 for i in np.arange(0, data.count()[0]):271 # im2 = PILImage.open("imgs/" + str(rand_uuid) + "/img_" + str(i) + ".jpg")272 # for image in imagelist:273 pdf.add_page()274 pdf.image("imgs/" + str(rand_uuid) + "/img_" + str(i) + ".jpg",w=200)275 pdf.output(pdf1_filename, "F")276 shutil.rmtree('imgs/' + str(rand_uuid))277 os.remove(myfile.name)278 scheduler.enqueue_in(timedelta(days=1), delete_later_pdf, str(rand_uuid))279 # scheduler.enqueue_in(timedelta(minutes=1), delete_later_pdf, str(rand_uuid))280 data = json.dumps({'success': str(rand_uuid), 'error': None, 'description': None})281 # data = json.dumps({'success': uploaded_file_url})282 return HttpResponse(data, content_type='application/json')283 except Exception as e:284 data = json.dumps({'success': None, 'error': True, 'description': "Произошла ошибка \n" + str(e)})285 return HttpResponse(data, content_type='application/json')286@csrf_exempt287def preview(request, prev_uuid):288 if request.method == "GET":...

Full Screen

Full Screen

sample_log_generator.py

Source:sample_log_generator.py Github

copy

Full Screen

1import uuid2import datetime3from random import randrange4def log_generator(logfile, rand_uuid, num_log=100000):5 start_date = datetime.datetime(100, 1, 1, 11, 34, 59)6 curr_time = datetime7 bunch_size = 1000000 # Experiment with different sizes8 bunch = []9 with open(logfile, "a") as logfile:10 for i in range(num_log):11 random_id = rand_uuid[randrange(len(rand_uuid)+1)]12 curr_date = start_date + curr_time.timedelta(0, 3) # days, seconds, then other fields.13 start_date = curr_date14 display_date = curr_date.time().strftime("%d / %b / %Y: %H: %M: %S -0300")15 timestamp_line = '177.126.180.83 - - ['+display_date+'] "GET /lolcats.jpg HTTP / 1.1" 200 5143 "-"'16 user_id_line = '\"userid = '+str(random_id)+'\"'17 bunch.append(timestamp_line+"\n"+user_id_line+"\n")18 if len(bunch) == bunch_size:19 logfile.writelines("".join(bunch))20 bunch = []21 logfile.writelines("".join(bunch))22__author__ = 'Ejiro'23if __name__ == '__main__':24 # make a random UUID25 rand_uuid = [uuid.uuid4() for i in range(11)]26 # Generate logs27 log_generator("log_test3.txt", rand_uuid, 5)28 log_generator("log_test4.txt", rand_uuid, 9)...

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 tempest 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