Best Python code snippet using SeleniumBase
views.py
Source:views.py
1from django.shortcuts import render,redirect,get_object_or_4042from django.contrib.auth.models import User,auth3from django.contrib import messages4from .models import Comments, Destination,All,Contactus, Silverbazar, Querries5from .forms import AllForm, DestinationForm6from django.http import HttpResponseRedirect7from django.urls import reverse8from django.contrib.auth.decorators import login_required9'''10def followers(request):11 follow=get_object_or_404(All,username=request.POST.get('post_id'))12 if follow.followers.filter(id=request.user.id).exists():13 follow.followers.remove(request.user)14 else:15 follow.followers.add(request.user)16 return redirect("index")17'''18def querries(request):19 if(request.method=="POST"):20 tmp=Querries()21 tmp.name=request.POST['name']22 tmp.email=request.POST['email']23 tmp.querry=request.POST['querry']24 tmp.save()25 return render(request,'landingpage.html')26def comment(request):27 if(request.method=="POST"):28 temp=Comments()29 temp.username=request.user.username30 temp.user_id=request.user.id31 temp.comment=request.POST['text']32 temp.post_id=request.POST.get('destid')33 temp.save()34 '''comment=get_object_or_404(Destination,userid=request.POST.get('destid'))35 comment.comments.add(request.user)'''36 return redirect('index')37 return render(request,'index.html')38def silverbazar(request):39 tmp=Silverbazar.objects.all()[::-1]40 return render(request,'silverbazar.html',{'tmp':tmp})41def paisamoney(request,pk):42 pass43def pay(request,pk):44 all=All.objects.get(username=pk)45 all.moneybalance=all.moneybalance + int(request.POST['amount'])46 all.silverbalance=all.silverbalance + int(request.POST['silver'])*1047 all.save()48 return redirect('advdashboard')49def sell(request,pk):50 if request.method=='POST':51 all=All.objects.get(username=pk)52 tmp=Silverbazar()53 if all.mysilvers >= int(request.POST['totalsilvers']):54 tmp.username=request.user.username55 tmp.user_id=request.user.id56 tmp.silver=request.POST['totalsilvers']57 tmp.costpersilver=request.POST['amount']58 tmp.total_cost=(int(request.POST['amount']))*(int(request.POST['totalsilvers']))59 all.mysilvers= all.mysilvers - int(request.POST['totalsilvers'])60 all.save()61 tmp.save()62 else:63 return redirect('dashboard')64 return redirect('index')65 else:66 return render(request,'paisadashboard.html')67 68def withdrawmoney(request,pk):69 if request.method=='POST':70 all=All.objects.get(username=pk)71 if all.mymoney >= int(request.POST['totalamount']):72 all.mymoney= all.mymoney - int(request.POST['totalamount'])73 all.save()74 return redirect(index)75 else:76 return redirect(dashboard)77 else:78 return render(request,'paisadashboard.html')79def visit(request,pk):80 visiter=get_object_or_404(Destination,id=pk)81 all=All.objects.get(username=request.user.username)82 if visiter.clicks.filter(id=request.user.id).exists():83 print("User already exist in clicks")84 else:85 print("User not exist")86 visiter.total_clicks=visiter.total_clicks+187 if visiter.money >= visiter.moneyclick:88 all.mymoney = all.mymoney + visiter.moneyclick89 visiter.money = visiter.money - visiter.moneyclick 90 elif visiter.money > 0 and visiter.money < visiter.moneyclick:91 all.mymoney = all.mymoney + visiter.money92 visiter.money = visiter.money-visiter.money93 else:94 all.mymoney = all.mymoney95 visiter.money = visiter.money96 if visiter.silver >= visiter.silverclick :97 all.mysilvers = all.mysilvers + visiter.silverclick98 visiter.silver = visiter.silver - visiter.silverclick99 elif visiter.silver > 0 and visiter.silver < visiter.silverclick :100 all.mysilvers = all.mysilvers + visiter.silver101 visiter.silver = visiter.silver - visiter.silver102 else:103 all.mysilvers = all.mysilvers104 visiter.silver = visiter.silver105 all.save()106 visiter.clicks.add(request.user)107 visiter.total_visiters=visiter.total_visiters+1108 visiter.save()109 return redirect(request.POST.get('post_url'))110 111def followers(request):112 follow=get_object_or_404(All,username=request.POST.get('post_id'))113 if follow.followers.filter(id=request.user.id).exists():114 follow.followers.remove(request.user)115 else:116 follow.followers.add(request.user)117 return redirect("index")118def search(request):119 if request.method == 'POST':120 searchedtext=request.POST['search']121 searchresult=Destination.objects.filter(header__contains=searchedtext)122 return render(request,'searchpage.html',{'searchedtext':searchedtext,'searchresult':searchresult})123def like(request): 124 post=get_object_or_404(Destination,id=request.POST.get('post_id'))125 if post.likes.filter(id=request.user.id).exists():126 post.likes.remove(request.user)127 else:128 post.likes.add(request.user)129 #return HttpResponseRedirect(reverse('like',args=[str(pk)]))130 return redirect('index')131 #return HttpResponseRedirect(post.get_absolute_url())132# Create your views here.133def landingpage(request):134 return render(request,'landingpage.html')135# creating account page136def createaccount(request):137 if request.method=='POST':138 username= request.POST['username']139 first_name= request.POST['first_name']140 last_name= request.POST['last_name']141 email= request.POST['email1']142 email2=request.POST['email2']143 #email2= request.POST['email2']144 #countrycode= request.POST['countrycode']145 #number= request.POST['number']146 #number2= request.POST['number2']147 password1= request.POST['password1']148 password2= request.POST['password2']149 #address= request.POST['address']150 #country= request.POST['country']151 #language= request.POST['language']152 #type=request.POST['type']153 #user=User.objects.create_user(username='username',password=password1,email=email,first_name=first_name,number=number,number2=number2,address=address,country=country,countrycode=countrycode,language=language,type=type)154 if password1==password2:155 if(User.objects.filter(username=username).exists()):156 messages.info(request,'Username already exist')157 return render(request,'createaccount.html')158 elif(User.objects.filter(email=email).exists()):159 messages.info(request,'email already exist')160 return render(request,'createaccount.html')161 else:162 user=User.objects.create_user(username=username,password=password1,email=email,first_name=first_name,last_name=last_name)163 user.save()164 myname=email165 #stroing to other table166 postto=All()167 postto.user_id=request.user.id168 postto.username= request.POST['username']169 postto.email=request.POST['email1']170 postto.email2=request.POST['email2']171 postto.password=request.POST['password1']172 postto.first_name= request.POST['first_name']173 postto.last_name= request.POST['last_name']174 postto.save()175 return render(request,'sign-in.html')176 print('user created')177 else:178 messages.info(request,'password did not matched')179 return render(request,'createaccount.html')180 return redirect('/')181 182 else:183 return render(request,'createaccount.html')184# creating signin page185def login(request):186 if request.method=='POST':187 username=request.POST['username']188 password=request.POST['password']189 print(username)190 user=auth.authenticate(username=username,password=password)191 if user is not None:192 auth.login(request,user)193 return redirect('index')194 #return redirect("/")195 else:196 messages.info(request,'invalid email and password')197 return redirect('login')198 else:199 return render(request,'sign-in.html')200#logout201def logout(request):202 auth.logout(request)203 return redirect('/')204#creating index page205#def index(request):206# dest=Destination.objects.all()[::-1]207# return render(request, 'index.html',{'dest':dest})208def index(request):209 dest=Destination.objects.all()[::-1]210 all=All.objects.all()211 comment=Comments.objects.all()[::-1]212# for like in dest.likes.all():213# if like is request.user:214# is_like=True215# break216 context={217 'dest':dest,218 'all':all,219 'comments':comment220 }221 return render(request, 'index.html',context)222# creating advertise page223@login_required224def advertise(request,pk):225 initial_values={226 'username':request.user.username,227 }228 form=DestinationForm()229 all=All.objects.get(username=pk)230 if request.method=='POST':231 all=All.objects.get(username=pk)232 form=DestinationForm(request.POST)233 if form.is_valid():234 instance = form.save(commit=False)235 instance.user = request.user236 if all.moneybalance >= int(instance.money) and all.silverbalance >= int(instance.silver):237 all.ads=all.ads+1238 all.moneybalance=all.moneybalance-int(instance.money)239 #Todo here is add validation that check instance.moeny is exist or not240 all.silverbalance=all.silverbalance-int(instance.silver)241 all.save()242 instance.save()243 return redirect('index')244 else:245 return redirect('advdashboard')246 247 else:248 form=DestinationForm(initial=initial_values)249 context={'form':form}250 return render(request,'advertise.html',context)251 252 '''if request.method=='POST':253 all=All.objects.get(username=pk)254 postad=Destination()255 postad.user_id=request.user.id256 postad.username=request.user.username257 postad.header= request.POST['header']258 postad.url=request.POST['url']259 postad.description=request.POST['description']260 postad.type=request.POST['type']261 postad.silver=request.POST['silver']262 postad.silverclick=request.POST['silverclick']263 postad.silverimpression=request.POST['silverimpression']264 postad.money=request.POST['money']265 postad.moneyclick=request.POST['moneyclick']266 postad.moneyimpression=request.POST['moneyimpression']267 if all.moneybalance >= int(postad.money) and all.silverbalance >= int(postad.silver):268 all.ads=all.ads+1269 all.moneybalance=all.moneybalance-int(postad.money)270 all.silverbalance=all.silverbalance-int(postad.silver)271 postad.save()272 all.save()273 return redirect('index')274 else:275 return redirect('advdashboard')276 else:277 print("not coming")278 return render(request,'advertise.html')279'''280#contactus281def contactus(request):282 if request.method=='POST':283 con=Contactus()284 con.user=request.user285 con.user_id=request.user.id286 con.name=request.POST['contactusname']287 con.email=request.POST['contactusemail']288 con.issue=request.POST['contactusissue']289 con.save()290 return redirect('index')291 else:292 return render(request,'contactus.html')293 '''form=ContactusForm()294 if request.method=='POST':295 contact=Contactus.objects.get(pk=id)296 form=ContactusForm(request.POST or None,instance=contact)297 if form.is_valid():298 form.save()299 return redirect('index')300 print("true")301 else:302 print("not working")303 else:304 contact = Contactus.objects.get(pk=id)305 return render(request, 'contactus.html', contact)'''306def advdashboard(request):307 balance=All.objects.all()308 return render(request, 'advertisedashboard.html',{'balance':balance})309#terms and conditions310def termsandcondition(request):311 return render(request,'termsandcondition.html')312#privacy Policy313def privacypolicy(request):314 return render(request,'privacypolicy.html')315# Update profile316def update(request):317 return render(request,'update.html')318def update(request,pk):319 all = All.objects.get(username=pk)320 form=AllForm(instance=all)321 if request.method=='POST':322 form=AllForm(request.POST,instance=all)323 if form.is_valid():324 form.save()325 return redirect('profile')326 context={'form':form}327 return render(request,'update.html',context)328# advertiser history 329def advhistory(request):330 hist=Destination.objects.all()[::-1]331 return render(request, 'advhistory.html',{'hist':hist})332# about us of settings333def aboutus(request):334 return render(request,'aboutus.html')335def dashboard(request):336 balance=All.objects.all()337 return render(request,'paisadashboard.html',{'balance':balance})338def report(request):339 return render(request,'paisareport.html')340def referearn(request):341 return render(request,'referearn.html')342def advreport(request):343 post=Destination.objects.all()344 return render(request,'advreport.html',{'post':post})345def profile(request):346 all=All.objects.all()...
controllers.py
Source:controllers.py
...50 if not isinstance(data["minor"], int):51 return False52 53 return True54def validate_visiter(data):55 if "id" not in data or "user" not in data or "place" not in data or "pass_phrase" not in data or "snap" not in data or "date" not in data:56 return False57 58 if not isinstance(data["id"], int):59 return False60 61 if not isinstance(data["user"], str) or len(data["user"]) > 255:62 return False63 64 if not isinstance(data["place"], int):65 return False66 67 if not isinstance(data["pass_phrase"], str) or len(data["pass_phrase"]) != 32:68 return False69 70 if not isinstance(data["snap"], int):71 return False72 73 if not isinstance(data["date"], str):74 return False75 76 return True77def get_valid_visiter(data):78 visiter_query = Visiter.query.filter_by(\79 id=data["id"],\80 user=data["user"],\81 place=data["place"],\82 pass_phrase=data["pass_phrase"],\83 snap=data["snap"],\84 date=datetime.datetime.strptime(data["date"], "%Y-%m-%dT%H:%M:%S")\85 )86 87 if visiter_query.count() == 1:88 return visiter_query.one()89 else:90 return None91def get_snap_from_visiter_json(data):92 visiter = get_valid_visiter(data)93 94 if visiter is None:95 return None96 else:97 return Snap.query.filter_by(id=visiter.snap).one()98def set_snap(snap):99 snap = db.session.query(Snap).filter_by(id=snap).one()100 101 if len(snap.visiters) != 0:102 camera = db.session.query(Place).filter_by(id=snap.visiters[0].place).one().camera[0]103 print("requesting snap...")104 payload = {"snap": snap.id, "interval": app.config["SNAP_TIME_LAG"]}105 print(requests.get(camera.endpoint, params=payload).text)106@app.route("/")107def show_all():108 if(not app.debug):109 return abort(404)110 111 return render_template("index.html")112@app.route("/get_place", methods=["POST"])113def get_place():114 params = get_json_params()115 if not validate_beacon(params):116 return abort(400)117 place = Beacon.query.filter_by(\118 uuid=params["uuid"],\119 major=params["major"],\120 minor=params["minor"]\121 ).one().place122 return Response(json.dumps(parse_serializable_obj(place), ensure_ascii=False), mimetype="application/json")123@app.route("/get_visiter", methods=["POST"])124def get_visiter():125 params = get_json_params()126 127 if not validate_user(params) or not validate_beacon(params["beacon"]):128 return abort(400)129 130 place = Beacon.query.filter_by(\131 uuid=params["beacon"]["uuid"],\132 major=params["beacon"]["major"],\133 minor=params["beacon"]["minor"]\134 ).one().place135 136 active_snaps = Snap.query.filter("date > :now").params(now=datetime.datetime.now()).all();137 138 for snap in active_snaps:139 if len(snap.visiters) != 0 and snap.visiters[0].place == place.id:140 for visiter in snap.visiters:141 if visiter.user == params["user"]:142 return abort(409)143 144 new_visiter = Visiter(params["user"], place.id, snap.id)145 146 db.session.add(new_visiter)147 db.session.flush()148 serializable_new_visiter = copy.deepcopy(parse_serializable_obj(new_visiter))149 150 db.session.commit()151 152 return Response(json.dumps(serializable_new_visiter), mimetype="application/json")153 154 new_snap = Snap(datetime.datetime.now() + datetime.timedelta(seconds=app.config["SNAP_TIME_LAG"]))155 db.session.add(new_snap)156 db.session.flush()157 158 new_visiter = Visiter(params["user"], place.id, new_snap.id)159 160 db.session.add(new_visiter)161 db.session.flush()162 163 serializable_new_visiter = copy.deepcopy(parse_serializable_obj(new_visiter))164 165 db.session.commit()166 167 set_snap(serializable_new_visiter["snap"])168 169 return Response(json.dumps(serializable_new_visiter), mimetype="application/json")170@app.route("/delete_visiter", methods=["POST"])171def delete_visiter():172 params = get_json_params()173 174 if not validate_visiter(params):175 return abort(400)176 177 visiter = get_valid_visiter(params)178 179 if visiter is None:180 return Response(status=204)181 182 db.session.delete(visiter)183 db.session.commit()184 return Response(json.dumps({"state": "done"}), mimetype="application/json")185@app.route("/get_image", methods=["GET", "POST"])186def get_image():187 if(request.method == "GET"):188 params = json.loads(request.args.get("visiter"));189 else:190 params = get_json_params()191 if not validate_visiter(params):192 return abort(400)193 194 snap = get_snap_from_visiter_json(params)195 196 if snap is None or snap.src is None:197 return Response(status=204)198 199 os.path.exists(app.config["SNAPS_DIRECTORY"] + snap.src)200 201 return send_from_directory(app.config["SNAPS_DIRECTORY"], snap.src)202@app.route("/get_thum", methods=["POST"])203def get_thum_image():204 params = get_json_params()205 206 if not validate_visiter(params):207 return abort(400)208 209 snap = get_snap_from_visiter_json(params)210 211 if snap is None or snap.thum_src is None:212 return Response(status=204)213 214 return send_from_directory(app.config["SNAPS_DIRECTORY"], snap.thum_src)215@app.route("/get_snap_state", methods=["POST"])216def get_snap_state():217 params = get_json_params()218 219 if not validate_visiter(params):220 return abort(400)221 222 snap = get_snap_from_visiter_json(params)223 224 if snap is None:225 return Response(status=204)226 227 response_data = {228 "visiter_length": len(snap.visiters),229 "snap_time": snap.date,230 "done": snap.src is not None231 }232 233 return Response(json.dumps(parse_serializable_obj(response_data)), mimetype="application/json")234@app.route("/add_camera", methods=["POST"])235def add_camera():236 params = get_json_params()237 238 cameras = db.session.query(Camera).filter_by(place=params["place"]).all()239 if len(cameras) != 0:240 cameras[0].endpoint = params["endpoint"]241 db.session.commit()242 return "update ok"243 244 new_camera = Camera(params["place"], params["endpoint"])245 db.session.add(new_camera)246 db.session.commit()247 248 return "ok"249@app.route("/post_image", methods=["POST"])250def post_image():251 if "image" not in request.files or "thum" not in request.files:252 return "No file"253 254 image = request.files["image"]255 thum = request.files["thum"]256 257 if image.filename == "" or thum.filename == "":258 return "No filename"259 260 image_filename = secure_filename(image.filename)261 thum_filename = secure_filename(thum.filename)262 263 image.save(os.path.join(app.config["SNAPS_DIRECTORY"], image_filename))264 thum.save(os.path.join(app.config["SNAPS_DIRECTORY"], thum_filename))265 266 snap = db.session.query(Snap).filter_by(id=request.form["snap"]).one()267 snap.src = image_filename268 snap.thum_src = thum_filename269 db.session.commit()270 271 return "ok"272@app.route("/post_live_view", methods=["POST"])273def post_live_view():274 if "place" not in request.form:275 abort(400)276 live_views[request.form["place"]] = BytesIO(request.files["live_view"].stream.read())277 return "ok"278@app.route("/get_live_view", methods=["POST"])279def get_live_view():280 params = get_json_params()281 if not validate_visiter(params):282 return abort(400)283 if live_views[str(params["place"])].closed:284 abort(404)285 return send_file(live_views[str(params["place"])], mimetype="image/jpeg");286# debugging methods287@app.route("/models/<model>/<id>", methods=["GET"])288def get_model(model, id):289 if(not app.debug):290 return abort(404)291 292 model_class = eval("%s" % model)293 data = parse_serializable_obj(model_class.query.filter_by(id=id).first())294 295 return Response(json.dumps(data), mimetype="application/json")...
bot.py
Source:bot.py
1from functools import total_ordering2import logging3import os4from aiogram import Bot, Dispatcher, executor, types5from db import Visit, Visiter6from sqlalchemy.sql import func7from text import RussianStrings8from db import Session9from datetime import datetime10def configure_logging():11 log_level = logging.INFO12 if os.environ.get("LOG_LEVEL", "") == "DEBUG":13 log_level = logging.DEBUG14 log_config = {15 "level": log_level,16 "format": "%(asctime)s\t%(levelname)s\t%(message)s",17 "datefmt": "%Y-%m-%d %H:%M:%S",18 }19 logging.basicConfig(**log_config)20configure_logging()21TG_BOT_ENVIRON_VARIABLE_NAME = "TG_TILIS_BOT"22TG_BOT_API_TOKEN = os.environ.get(TG_BOT_ENVIRON_VARIABLE_NAME, None)23logger = logging.getLogger()24strings = RussianStrings()25if TG_BOT_API_TOKEN is None:26 logger.error(27 f"{TG_BOT_ENVIRON_VARIABLE_NAME} is not found in enviroment. Please set it and try again"28 )29 exit(0)30bot = Bot(token=TG_BOT_API_TOKEN)31dp = Dispatcher(bot)32def find_user_by_id(db_session, tg_id):33 visiter_query = db_session.query(Visiter).filter_by(tg_id=tg_id).first()34 return visiter_query35@dp.message_handler(commands="start")36async def start_start_handler(message: types.Message):37 logger.info(f"{message.from_user.full_name} has started the bot.")38 db_session = Session()39 visiter = find_user_by_id(db_session, message.from_user.id)40 if visiter is None:41 visiter = Visiter(42 tg_id=message.from_user.id, name=message.from_user.full_name, donate_sum=043 )44 db_session.add(visiter)45 visiter_balance = visiter.donate_sum46 for visit in visiter.visits:47 visiter_balance -= visit.total_payment48 db_session.commit()49 await message.reply(50 strings.get_start_text(message, visiter_balance),51 parse_mode=types.ParseMode.MARKDOWN,52 )53@dp.message_handler(commands="visit")54async def start_visit_handler(message: types.Message):55 logger.info(f"{message.from_user.full_name} added new visit")56 db_session = Session()57 visit = Visit(date=datetime.now(), total_payment=0)58 visiter = find_user_by_id(db_session, message.from_user.id)59 if visiter is None:60 return await message.reply("ÐожалÑйÑÑа ÑнаÑала заÑегеÑÑÑиÑÑйÑеÑÑ Ð² боÑе")61 visit.visiters.append(visiter)62 logger.info(f"Created new visit with id {visit.visit_id}")63 keyboard_markup = types.InlineKeyboardMarkup(row_width=3)64 btns_and_data = (("Я ÑÑÑÑ", f"visit|1"), ("Я не ÑÑÑÑ", f"visit|0"))65 keyboard_markup.row(*(types.InlineKeyboardButton(text, callback_data=data) for text, data in btns_and_data))66 67 visit_message = await message.reply(strings.get_visit_text(visit), reply_markup=keyboard_markup)68 visit.tg_message_id = visit_message.message_id69 70 db_session.add(visit)71 db_session.commit()72 return 73@dp.callback_query_handler(lambda query: query.data.startswith('visit|'))74async def inline_kb_visit_handler(query: types.CallbackQuery):75 status = query.data.split('|')[1]76 db_session = Session()77 visit = db_session.query(Visit).filter_by(tg_message_id=query.message.message_id).first()78 if visit is None:79 logger.error("Unexpected code")80 return81 visiter = find_user_by_id(db_session, query.from_user.id)82 if visiter is None:83 return84 85 smth_changed = False86 if status == '1':87 if visiter not in visit.visiters:88 visit.visiters.append(visiter)89 smth_changed = True90 else:91 await query.answer('СлÑÑÑ, ÑÑ Ñже ÑÑÑÑ!')92 93 elif status == '0':94 if visiter in visit.visiters:95 visit.visiters.remove(visiter)96 smth_changed = True97 else:98 await query.answer('Ðй! Ð¢Ñ Ñже не ÑÑÑÑ!')99 100 print(list(visit.visiters))101 db_session.commit()102 if smth_changed:103 await query.message.edit_text(strings.get_visit_text(visit), reply_markup=query.message.reply_markup)104 return 105if __name__ == "__main__":...
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!!