Best Python code snippet using tavern
views.py
Source:views.py
1from datetime import datetime, date2from decimal import Context3from typing import List4from django.db.backends.utils import format_number5from django.shortcuts import redirect, render6from django.views.decorators.cache import cache_control7from sample.models import *8from django.contrib import messages9from decouple import config10import random11from django.http import HttpResponse12from django.db import connection13# Create your views here.14class_mapping = {"seat1A": "AC First Class(1A)",15 "seat2A": "AC 2 Tier(2A)",16 "seatFC": "First Class(FC)",17 "seat3A": "AC 3 Tier(3A)",18 "seat3E": "AC 3 Economy(3E)",19 "seatCC": "AC Chair Car(CC)",20 "seatSL": "Sleeper(SL)",21 "seat2S": "Second Sitting(2S)"}22def deleteTicket(request, pnr):23 cursor = connection.cursor()24 cursor.execute("DELETE FROM sample_ticket WHERE pnr=%s", [pnr])25 cursor.execute("DELETE FROM sample_passengers WHERE pnr_number=%s", [pnr])26 cursor.close()27 messages.info(request, 'Refund Successfull!!!')28 return render(request, 'index.html')29def refund(request, pnr):30 cursor = connection.cursor()31 cursor.execute(32 "SELECT baseRate,date FROM sample_ticket WHERE pnr=%s", [pnr])33 inst = cursor.fetchall()34 price = inst[0][0]35 journey_date = inst[0][1]36 current_date = date.today()37 deduction = 038 if((journey_date - current_date).days >= 2):39 deduction = price*(0.25)40 price = price - deduction41 request.session['track'] = {'price': price,42 'pnr': pnr,43 'deduction': deduction}44 context = {45 "price": price,46 "pnr": pnr,47 "deduction": deduction48 }49 return render(request, 'refundPage.html', context)50def deleteAfter(request, id):51 cursor = connection.cursor()52 cursor.execute("SELECT baseRate,ticketCost FROM sample_ticket WHERE pnr=%s", [53 request.session['temp']['pnr']])54 inst = cursor.fetchall()55 rate = inst[0][0]56 tc = inst[0][1]57 print(rate, tc)58 cursor.execute("DELETE FROM sample_passengers WHERE id=%s", [id])59 cursor.execute("SELECT * FROM sample_ticket WHERE pnr=%s",60 [request.session['temp']['pnr']])61 ticket = cursor.fetchall()62 cursor.execute("SELECT * FROM sample_passengers WHERE pnr_number=%s",63 [request.session['temp']['pnr']])64 passengers = cursor.fetchall()65 if(len(passengers) == 0):66 return refund(request, request.session['temp']['pnr'])67 else:68 cursor.execute("UPDATE sample_ticket SET ticketCost=%s WHERE pnr=%s", [69 (tc-rate), request.session['temp']['pnr']])70 context = {71 "ticket": ticket,72 "members": passengers,73 }74 return render(request, 'pnr.html', context)75@cache_control(no_cache=True, must_revalidate=True, no_store=True)76def deleteIndividual(request, id):77 cursor = connection.cursor()78 result = 079 cursor.execute("SELECT * FROM sample_passengers WHERE id=%s", [id])80 result = len(cursor.fetchall())81 if(result != 0):82 cursor.execute("DELETE FROM sample_passengers WHERE id=%s", [id])83 # Getting Seat Count84 cursor.execute("SELECT "+str(request.session['temp']['class'])+" FROM sample_train WHERE name=%s AND date=%s", [85 request.session['temp']['train_name'], request.session['temp']['date']])86 seats = cursor.fetchone()[0]87 cursor.execute("UPDATE sample_train SET "+str(request.session['temp']['class'])+"=%s WHERE name=%s AND date=%s", [88 (seats+1), request.session['temp']['train_name'], request.session['temp']['date']])89 # Again Checking For Seat Count From DB to update the webpage90 cursor.execute("SELECT "+str(request.session['temp']['class'])+" FROM sample_train WHERE name=%s AND date=%s", [91 request.session['temp']['train_name'], request.session['temp']['date']])92 seats = cursor.fetchone()[0]93 trigger = True94 if(seats == 0):95 trigger = False96 else:97 trigger = True98 messages.info(request, 'Deleted Successfully!')99 cursor.execute("SELECT * FROM sample_passengers WHERE pnr_number=%s",100 [request.session['temp']['pnr']])101 passengers = cursor.fetchall()102 context = {103 "created": passengers,104 "train_name": request.session['temp']['train_name'],105 "berth": class_mapping[request.session['temp']['class']],106 "train_number": request.session['temp']['train_number'],107 "available": seats,108 "trigger": trigger,109 "ticket_cost": request.session['temp']['ticket_cost']110 }111 cursor.close()112 return render(request, 'book.html', context)113def pnr(request):114 cursor = connection.cursor()115 cursor.execute("SELECT * FROM sample_ticket WHERE pnr=%s AND ticket_no=%s", [request.POST.get(116 "PNR"), request.POST.get("ticket_number")])117 ticket = cursor.fetchall()118 print(ticket)119 cursor.execute("SELECT * FROM sample_passengers WHERE pnr_number=%s", [request.POST.get(120 "PNR")])121 passengers = cursor.fetchall()122 request.session['temp'] = {123 "pnr": request.POST.get(124 "PNR"),125 "ticket": request.POST.get("ticket_number")126 }127 context = {128 "ticket": ticket,129 "members": passengers,130 }131 cursor.close()132 return render(request, 'pnr.html', context)133@cache_control(no_cache=True, must_revalidate=True, no_store=True)134def index(request):135 return render(request, 'index.html')136@cache_control(no_cache=True, no_store=True)137def book(request):138 train_name = ""139 train_number = 0140 base_price = 0141 cursor = connection.cursor()142 cursor.execute("SELECT train FROM (SELECT DISTINCT A.train,A.start,B.end FROM sample_routes A CROSS JOIN sample_routes B) as a WHERE start=%s AND end=%s", [143 str(request.POST.get('from')).upper(), str(request.POST.get('destination')).upper()])144 train_name = cursor.fetchone()[0]145 cursor.execute("SELECT id,rate FROM sample_routes WHERE train=%s AND start=%s", [146 train_name, request.POST.get('from')])147 start_position = cursor.fetchall()148 cursor.execute("SELECT id,rate FROM sample_routes WHERE train=%s AND end=%s", [149 train_name, request.POST.get('destination')])150 end_position = cursor.fetchall()151 if(start_position[0][0] == end_position[0][0]):152 base_price = start_position[0][1]153 else:154 base_price = abs(start_position[0][1]-end_position[0][1])155 print(base_price)156 cursor.execute(157 'SELECT train_number FROM sample_train_seats WHERE train_name=%s', [train_name])158 train_number = cursor.fetchone()[0]159 ticket_no = 11111+random.randint(1, 100)160 pnr = 1123436511+random.randint(1, 100)161 request.session['temp'] = {162 "train_name": train_name,163 "from": request.POST.get("from"),164 "destination": request.POST.get("destination"),165 "date": request.POST.get("date"),166 "time": request.POST.get("time"),167 "train_number": train_number,168 "class": request.POST.get("class"),169 "ticket_no": ticket_no,170 "pnr": pnr,171 "base_price": base_price,172 }173 cursor.execute("SELECT "+request.session['temp']['class']+" FROM sample_berth_cost WHERE train_name=%s", [174 request.session['temp']['train_name']])175 add_on = cursor.fetchone()[0]176 request.session['temp']['add_on'] = add_on177 cursor.execute(178 'SELECT * FROM sample_train WHERE name=%s AND date=%s;', [train_name, request.POST.get('date')])179 instance = cursor.fetchone()180 ticket_cost = base_price + (base_price*(add_on/100))181 request.session['temp']['ticket_cost'] = ticket_cost182 if(instance != None):183 request.session['temp']['class'] = request.POST.get("class")184 cursor.execute("SELECT "+request.session['temp']['class']+" FROM sample_train WHERE name=%s AND date=%s;", [185 train_name, request.POST.get('date')])186 available = cursor.fetchall()[0]187 trigger = True188 if(available == 0):189 trigger = False190 else:191 trigger = True192 context = {193 "train_name": instance[1].upper(),194 "train_number": instance[2],195 "berth": class_mapping[request.POST.get("class")],196 "available": available,197 "trigger": trigger,198 "ticket_cost": ticket_cost}199 else:200 cursor.execute(201 "SELECT * FROM sample_train_seats WHERE train_name=%s", [train_name])202 nested_values = cursor.fetchall()203 print(nested_values)204 cursor.execute("INSERT INTO sample_train(name,number,date,seat1A,seat2A,seat2S,seat3A,seat3E,seatCC,seatFC,seatSC,total_seats) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);",205 [train_name, train_number, request.POST.get("date"),206 nested_values[0][3],207 nested_values[0][4],208 nested_values[0][5],209 nested_values[0][6],210 nested_values[0][7],211 nested_values[0][8],212 nested_values[0][9],213 nested_values[0][10],214 nested_values[0][11]])215 cursor.execute("SELECT * FROM sample_train WHERE name=%s AND date=%s",216 [request.session['temp']['train_name'], request.session['temp']['date']])217 instance = cursor.fetchall()[0]218 cursor.execute("SELECT "+request.POST.get("class")+" FROM sample_train WHERE name=%s AND date=%s", [219 train_name, request.POST.get('date')])220 available = cursor.fetchone()[0]221 trigger = True222 if(available == 0):223 trigger = False224 else:225 trigger = True226 context = {227 "train_name": instance[1].upper(),228 "train_number": instance[2],229 "berth": class_mapping[request.POST.get("class")],230 "available": available,231 "trigger": trigger,232 "ticket_cost": ticket_cost233 }234 cursor.close()235 return render(request, 'book.html', context)236@cache_control(no_cache=True, no_store=True)237def create(request):238 if(request.method == "POST"):239 name = request.POST.get("name")240 aadhar = request.POST.get("aadhar")241 age = request.POST.get("age")242 gender = request.POST.get("gender")243 food = request.POST.get("food").upper()244 if(len(name) <= 49 and len(str(aadhar)) == 12 and len(gender) < 49 and len(food) <= 10):245 cursor = connection.cursor()246 try:247 cursor.execute("INSERT INTO sample_ticket(ticket_no,train_name,train_number,pnr,date,time,seat_class,start,destination) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)",248 [request.session['temp']['ticket_no'],249 request.session['temp']['train_name'],250 request.session['temp']['train_number'],251 request.session['temp']['pnr'],252 request.session['temp']['date'],253 request.session['temp']['time'],254 request.session['temp']['class'],255 request.session['temp']['from'],256 request.session['temp']['destination'],257 ])258 except(Exception):259 pass260 cursor.execute("INSERT INTO sample_passengers(name,aadhar_no,age,gender,food,pnr_number) VALUES(%s,%s,%s,%s,%s,%s)",261 [name, aadhar, age, gender, food, request.session["temp"]["pnr"]])262 cursor.execute("SELECT * FROM sample_passengers WHERE pnr_number=%s",263 [request.session['temp']['pnr']])264 passengers = cursor.fetchall()265 cursor.execute("SELECT "+str(request.session['temp']['class'])+" FROM sample_train WHERE name=%s AND date=%s", [266 request.session['temp']['train_name'], request.session['temp']['date']])267 seats = cursor.fetchone()[0]268 cursor.execute("UPDATE sample_train SET "+str(request.session['temp']['class'])+"=%s WHERE name=%s AND date=%s", [269 (seats-1), request.session['temp']['train_name'], request.session['temp']['date']])270 cursor.execute("SELECT "+str(request.session['temp']['class'])+" FROM sample_train WHERE name=%s AND date=%s", [271 request.session['temp']['train_name'], request.session['temp']['date']])272 seats = cursor.fetchone()[0]273 trigger = True274 if(seats == 0):275 trigger = False276 else:277 trigger = True278 context = {279 "created": passengers,280 "train_name": request.session['temp']['train_name'],281 "berth": class_mapping[request.session['temp']['class']],282 "train_number": request.session['temp']['train_number'],283 "available": seats,284 "trigger": trigger,285 "ticket_cost": request.session['temp']['ticket_cost']286 }287 cursor.close()288 return render(request, 'book.html', context)289 return render(request, 'create.html')290def display(request):291 cursor = connection.cursor()292 cursor.execute("SELECT * FROM sample_passengers WHERE pnr_number=%s",293 [request.session['temp']['pnr']])294 inst = cursor.fetchall()295 cursor.execute("UPDATE sample_ticket SET baseRate=%s,ticketCost=%s WHERE pnr=%s", [296 request.session['temp']['ticket_cost'], (len(inst)*request.session['temp']['ticket_cost']), request.session['temp']['pnr']])297 if(len(inst) == 0):298 cursor.close()299 return HttpResponse("<html><body><h1>Cannot Book Ticket !!!</h1><br><h3>No Passengers Were Added</h3></body></html>")300 else:301 rate = float("{:.2f}".format(302 len(inst)*(request.session['temp']['ticket_cost'])))303 context = {304 "obj": request.session['temp'],305 "inst": inst,306 "rate": rate307 }308 cursor.close()309 return render(request, 'display.html', context)310'''311 cursor.execute("INSERT INTO sample_ticket(ticket_no,train_name,train_number,pnr,date,time,seat_class,start,destination) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)",312 [request.session['temp']['ticket_no'],313 request.session['temp']['train_name'],314 request.session['temp']['train_number'],315 request.session['temp']['pnr'],316 request.session['temp']['date'],317 request.session['temp']['time'],318 request.session['temp']['class'],319 request.session['temp']['from'],320 request.session['temp']['destination'],321 ])...
migrate_values.py
Source:migrate_values.py
1import copy2import sys3import yaml4## path mappings for values to be extracted to new paths5VALUES_MAPPINGS = [6 # globals7 ("clusterName", "global.clusterConfig.name"),8 ("sysdig.accessKey", "global.sysdig.accessKey"),9 ("sysdig.existingAccessKeySecret", "global.sysdig.accessKeySecret"),10 ("image.registry", "global.image.registry"),11 # agent-only12 ("auditLog", "agent.auditLog"),13 ("collectorSettings", "agent.collectorSettings"),14 ("daemonset", "agent.daemonset"),15 ("ebpf", "agent.ebpf"),16 ("extraVolumes", "agent.extraVolumes"),17 ("gke", "agent.gke"),18 ("image.repository", "agent.image.repository"),19 ("image.tag", "agent.image.tag"),20 ("image.pullPolicy", "agent.image.pullPolicy"),21 ("leaderelection", "agent.leaderelection"),22 ("priorityClassName", "agent.priorityClassName"),23 ("prometheus", "agent.prometheus"),24 ("proxy", "agent.proxy"),25 ("psp", "agent.psp"),26 ("rbac", "agent.rbac"),27 ("resourceProfile", "agent.resourceProfile"),28 ("scc", "agent.scc"),29 ("secure", "agent.secure"),30 ("serviceAccount", "agent.serviceAccount"),31 ("slim", "agent.slim"),32 ("sysdig.disableCaptures", "agent.sysdig.disableCaptures"),33 ("sysdig.settings", "agent.sysdig.settings"),34 ("timezone", "agent.timezone"),35 ("tolerations", "agent.tolerations"),36 # node-analyzer-only37 ("gke", "nodeAnalyzer.gke"),38 ("image.pullPolicy", "nodeAnalyzer.image.pullPolicy"),39 ("natsUrl", "nodeAnalyzer.natsUrl"),40 ("nodeAnalyzer", "nodeAnalyzer.nodeAnalyzer"),41 ("psp", "nodeAnalyzer.psp"),42 ("rbac", "nodeAnalyzer.rbac"),43 ("scc", "nodeAnalyzer.scc"),44 ("secure", "nodeAnalyzer.secure"),45]46## helpers for migrating values47## returns nested key if it exists, or None48def get_nested_key(key, values):49 nested_keys = key.split(".")50 value = values51 for nested_key in nested_keys:52 value = value.get(nested_key, None)53 if value is None:54 break55 return copy.deepcopy(value)56## set nested key, creating nested dicts if required57def set_nested_key(key, value, values):58 nested_keys = key.split(".")59 # descend into the nested keys, where the value at the cuurently traversed60 # path is nested_values61 nested_values = values62 for nested_key in nested_keys[:-1]:63 if nested_key in nested_values:64 nested_values = nested_values.get(nested_key, None)65 else:66 nested_values[nested_key] = {}67 nested_values = nested_values[nested_key]68 nested_values[nested_keys[-1]] = value69# copy keys from old path to new70def populate_values(new_values, old_values):71 for old_path, new_path in VALUES_MAPPINGS:72 value = get_nested_key(old_path, old_values)73 if value:74 set_nested_key(new_path, value, new_values)75def migrate_values(old_values_filename):76 old_values = {}77 with open(old_values_filename, 'r') as f:78 old_values = yaml.safe_load(f)79 new_values = {}80 populate_values(new_values, old_values)81 new_values_yaml = yaml.dump(new_values, sort_keys=False)82 print(new_values_yaml)83if __name__ == "__main__":84 if len(sys.argv) != 2:85 print("Usage: python migrate_values.py <old_values_file>")86 sys.exit(1)87 old_values_filename = sys.argv[1]...
Task 4.py
Source:Task 4.py
1nested_list = [2 'sam', [['Test', [['one', [], []]], [[u'file.txt', ['id', 1, 0]]], ['Test2', [], [u'file2.txt', ['id', 1, 2]]]], []]3]4def nested_values(nested_dict):5 for item in nested_dict:6 if isinstance(item, list):7 for element in nested_values(item):8 yield element9 else:10 yield item11for item in nested_values(nested_list):...
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!!