Best Python code snippet using splinter
views.py
Source:views.py
1from django.http.response import HttpResponseRedirect2from django.shortcuts import get_object_or_404, redirect, render # render returns HTML markup to the client3from django.http import HttpResponse4from django.views import generic5from .models import Article, Author, Region6from .forms import ArticleForm, AuthorForm, RegionForm7# Create your views here.8from django.utils.text import slugify9from django.db.models import Count10from pprint import pprint11from pycountry import countries12# a request handler, no template or HTML13# a view function is a function that takes a request and returns a response14slugs_to_country_names = {slugify(c.name):c.name for c in countries}15def home(request):16 return render(request, 'home.html', {'variable': {'a':'b'}})17def filter_articles(request, region_country):18 country_names = {slugify(country.name):country.name for country in countries}19 if region_country not in country_names: 20 print(region_country)21 return redirect('/articles')22 23 filtered_articles = Article.objects.filter(region__country = country_names[region_country] )24 return render(request, 'article/article_list.html', context = {'article_list': filtered_articles} )25def create_entity(request, model_form, redirect_location, html_location):26 form = model_form() 27 context = {'form':form}28 if request.method == 'POST': 29 form = model_form(request.POST)30 31 if form.is_valid():32 form.save() 33 return redirect(redirect_location)34 else:35 print(form.errors)36 37 return render(request, html_location, context)38def update_entity(request, model, model_form, slug, redirect_location, html_location):39 entity = model.objects.get(slug = slug)40 form = model_form(instance= entity)41 context = {'form':form}42 if request.method == 'POST':43 form = model_form(request.POST, instance=entity)44 if form.is_valid():45 form.save()46 return redirect(redirect_location)47 else:48 print(form.errors)49 return render(request, html_location, context)50def delete_entity(request, model, model_str, slug, html_indicator, redirect_location, html_location):51 entity = model.objects.get(slug = slug)52 context = {model_str:entity}53 54 if request.method == 'POST' and request.POST[html_indicator] == 'delete':55 entity.delete()56 return redirect(redirect_location)57 58 return render(request, html_location, context)59class ArticleList(generic.ListView):60 queryset = Article.objects.order_by('-created_on')61 template_name= 'article/article_list.html'62 model = Article63 def get(self, request, *args, **kwargs):64 queryset = self.get_queryset()65 if queryset == False: 66 return redirect('/articles')67 else:68 return super().get(request, *args, **kwargs)69 def get_queryset(self):70 if self.kwargs == {}:71 return Article.objects.all()72 else:73 queried_countries = set(self.kwargs['regions'].split('&'))74 requested_countries = []75 for country in queried_countries: 76 if not country in slugs_to_country_names: 77 return False78 else:79 requested_countries.append(slugs_to_country_names[country])80 81 queried_number = len(requested_countries)82 83 query_set = Article.objects.annotate(num_regions = Count('regions')).filter(num_regions__gte =queried_number)84 85 for country_name in requested_countries:86 query_set = query_set.filter(regions__country = country_name)87 return query_set88class ArticleDetail(generic.DetailView):89 model = Article90 template_name = 'article/article_detail.html'91class AuthorList(generic.ListView):92 queryset = Author.objects.order_by('-joined')93 template_name = 'author/author_list.html'94class AuthorDetail(generic.DetailView):95 model = Author96 template_name = 'author/author_detail.html'97class RegionList(generic.ListView):98 queryset = Region.objects.order_by('-added')99 template_name = 'region/region_list.html'100class RegionDetail(generic.DetailView):101 model = Region 102 template_name = 'region/region_detail.html'103def create_article(request):104 return create_entity(105 request= request, 106 model_form= ArticleForm, 107 redirect_location= '/articles', 108 html_location= 'article/article_create.html'109 )110def update_article(request, slug):111 return update_entity(112 request= request, 113 model = Article,114 model_form= ArticleForm, 115 slug = slug, 116 redirect_location= '/articles', 117 html_location= 'article/article_create.html'118 )119def delete_article(request, slug):120 return delete_entity(121 request= request, 122 model= Article,123 model_str= 'article', 124 slug=slug, 125 html_indicator='delete_article', 126 redirect_location='/articles', 127 html_location='article/article_delete.html'128 )129def create_author(request):130 return create_entity(131 request= request, 132 model_form= AuthorForm, 133 redirect_location='/authors', 134 html_location= 'author/author_create.html'135 )136def update_author(request, slug):137 return update_entity(138 request= request, 139 model = Author, 140 model_form= AuthorForm, 141 slug = slug, 142 redirect_location= '/authors', 143 html_location= 'author/author_create.html'144 )145def delete_author(request, slug):146 return delete_entity(147 request= request, 148 model= Author,149 model_str= 'author', 150 slug=slug, 151 html_indicator='delete_author', 152 redirect_location='/authors', 153 html_location='author/author_delete.html'154 )155def create_region(request):156 return create_entity(157 request= request, 158 model_form= RegionForm, 159 redirect_location='/regions', 160 html_location= 'region/region_create.html'161 )162def update_region(request, slug):163 return update_entity(164 request= request, 165 model = Region, 166 model_form= RegionForm, 167 slug = slug, 168 redirect_location= '/regions', 169 html_location= 'region/region_create.html'170 )171def delete_region(request, slug):172 return delete_entity(173 request= request, 174 model= Region,175 model_str= 'region', 176 slug=slug, 177 html_indicator= 'delete_region', 178 redirect_location= '/regions', 179 html_location='region/region_delete.html'...
test_registration.py
Source:test_registration.py
...70 data = {"email": "client@example.com", "password": "password"}71 response = client.post(url, data)72 assert User.objects.count() == 173 new_user = User.objects.get(email="client@example.com")74 redirect_location = get_redirect_location(response)75 assert redirect_location == reverse("home")76 event = account_events.CustomerEvent.objects.get()77 assert event.type == account_events.CustomerEvents.ACCOUNT_CREATED78 assert event.user == new_user79def test_signup_view_redirect(client, customer_user):80 url = reverse("account:signup")81 data = {82 "email": "client@example.com",83 "password": "password",84 "next": reverse("checkout:start"),85 }86 response = client.post(url, data)87 redirect_location = get_redirect_location(response)88 assert redirect_location == reverse("checkout:start")89def test_signup_view_fail(client, db, customer_user):90 url = reverse("account:signup")91 data = {"email": customer_user.email, "password": "password"}92 client.post(url, data)93 assert User.objects.count() == 194def test_password_reset_view_post(client, db, customer_user):95 url = reverse("account:reset-password")96 data = {"email": customer_user.email}97 response = client.post(url, data)98 redirect_location = get_redirect_location(response)99 assert redirect_location == reverse("account:reset-password-done")100 # Retrieve the event and ensure it was properly generated101 event = account_events.CustomerEvent.objects.get()102 assert event.type == account_events.CustomerEvents.PASSWORD_RESET_LINK_SENT103 assert event.user == customer_user104def test_password_reset_view_get(client, db):105 url = reverse("account:reset-password")106 response = client.get(url)107 assert response.status_code == 200108 assert response.template_name == ["account/password_reset.html"]109def test_base_backend(authorization_key, base_backend):110 assert authorization_key.site_settings.site.domain == "mirumee.com"111 key, secret = base_backend.get_key_and_secret()112 assert key == "Key"...
HeaderAnalysis.py
Source:HeaderAnalysis.py
1#Author: Lavakumar Kuppan2#License: MIT License - http://www.opensource.org/licenses/mit-license3from IronWASP import *4from System import *5import clr6#Inherit from the base PassivePlugin class7class HeaderAnalysis(PassivePlugin):8 #Override the GetInstance method of the base class to return a new instance with details9 def GetInstance(self):10 p = HeaderAnalysis()11 p.Name = "Header Analysis"12 p.Version = "0.4"13 p.Description = "Analyzes the HTTP Request and Response Headers for potential security issues"14 #When should this plugin be called. Possible values - BeforeInterception, AfterInterception, Both, Offline. Offline is the default value, it is also the recommended value if you are not going to perform any changes in the Request/Response15 #p.CallingState = PluginCallingState.BeforeInterception16 #On what should this plugin run. Possible values - Request, Response, Both17 p.WorksOn = PluginWorksOn.Response18 return p19 20 #Override the Check method of the base class with custom functionlity21 def Check(self, Sess, Results, ReportAll):22 23 self.ReportAll = ReportAll24 25 if Sess.Response.Headers.Has("Location") and Sess.Response.Code != 200:26 actual_redirect_location = Sess.Response.Headers.Get("Location")27 redirect_location = actual_redirect_location.lower()28 for part in Sess.Request.UrlPathParts:29 if part.lower() == redirect_location:30 self.ReportRedirect(actual_redirect_location, part, "url", Sess, Results)31 return32 for name in Sess.Request.Query.GetNames():33 for val in Sess.Request.Query.GetAll(name):34 if val.lower() == redirect_location:35 self.ReportRedirect(actual_redirect_location, val, "query:(0)".format(name), Sess, Results)36 return37 for name in Sess.Request.Body.GetNames():38 for val in Sess.Request.Body.GetAll(name):39 if val.lower() == redirect_location:40 self.ReportRedirect(actual_redirect_location, val, "body:{0}".format(name), Sess, Results)41 return42 if Sess.Request.Headers.Has("Referer"):43 if Sess.Request.Headers.Get("Referer").lower() == redirect_location:44 self.ReportRedirect(actual_redirect_location, Sess.Request.Headers.Get("Referer"), "referrer", Sess, Results)45 return46 def ReportRedirect(self, redirect_location, val, section, Sess, Results):47 Signature = '{0}|{1}'.format(Sess.Request.SSL.ToString(), section)48 if self.ReportAll or self.IsSignatureUnique(Sess.Request.BaseUrl, FindingType.TestLead, Signature):49 PR = Finding(Sess.Request.BaseUrl)50 PR.Title = "Possible Open Redirect"51 PR.Summary = "The Location Header of the Response contains the value present in the Request. This could potentially be an Open Redirect. Manual investigation required."52 53 if section == "url":54 PR.Triggers.Add(redirect_location, "The response is redirecting to {0}, this value is found in the url path section of this request".format(redirect_location), Sess.Request, redirect_location, "This response is a redirect to the location {0}".format(redirect_location), Sess.Response)55 elif section.startswith("query:"):56 PR.Triggers.Add(redirect_location, "The response is redirecting to {0}, this value is found in the {1} parameter of query section of this request".format(redirect_location, section[6:]), Sess.Request, redirect_location, "This response is a redirect to the location {0}".format(redirect_location), Sess.Response)57 elif section.startswith("body:"):58 PR.Triggers.Add(redirect_location, "The response is redirecting to {0}, this value is found in the {1} parameter of body section of this request".format(redirect_location, section[5:]), Sess.Request, redirect_location, "This response is a redirect to the location {0}".format(redirect_location), Sess.Response)59 elif section == "referrer":60 PR.Triggers.Add(redirect_location, "The response is redirecting to {0}, this value is found in the referrer header of this request".format(redirect_location), Sess.Request, redirect_location, "This response is a redirect to the location {0}".format(redirect_location), Sess.Response)61 62 PR.Signature = Signature63 PR.Type = FindingType.TestLead64 Results.Add(PR)65 66 67p = HeaderAnalysis()...
old_files.py
Source:old_files.py
1class website_attack():2 def __init__(self):3 print("Please choose the webpage.")4 print("")5 print("1) Ebay")6 print("2) Amazon")7 print("3) gmail")8 print("4) instagram")9 choosen_webside = int(input(""))10 if choosen_webside == 1:11 self.ebay_attack()12 elif choosen_webside == 2:13 self.amazon_attack()14 elif choosen_webside == 3:15 self.gmail_attack()16 elif choosen_webside == 4:17 self.insta_attack()18 def ebay_attack(self):19 phishing_email = input("Please enter your email: ")20 storage_location = input("Please enter the storage location: ")21 redirect_location = input("Please enter the redirect location (for default type: d): ")22 shutil.copytree('phishing/ebay/', storage_location)23 path = storage_location + "/modify.php"24 # Read in the file25 with open(path, 'r') as file:26 filedata = file.read()27 # Replace the target string28 filedata = filedata.replace('someone@example.com', phishing_email)29 if redirect_location != "d":30 filedata = filedata.replace('https://signin.ebay.com/ws/eBayISAPI.dll?SignIn&ru=http%3A%2F%2Fwww.ebay.com%2F', redirect_location)31 # Write the file out again32 with open(path, 'w') as file:33 file.write(filedata)34 print("Complete...")35 def amazon_attack(self):36 phishing_email = input("Please enter your email: ")37 storage_location = input("Please enter the storage location: ")38 redirect_location = input("Please enter the redirect location (for default type: d): ")39 shutil.copytree('phishing/amazon/', storage_location)40 path = storage_location + "/validate.php"41 # Read in the file42 with open(path, 'r') as file:43 filedata = file.read()44 # Replace the target string45 filedata = filedata.replace('someone@example.com', phishing_email)46 if redirect_location != "d":47 filedata = filedata.replace('https://www.amazon.com/dp/B01E6AO69U/ref=ods_gw_ha_d_white?pf_rd_p=4a14e6ce-9ad7-4d30-8874-2e112490a43e&pf_rd_r=E58SKPFF5RA13KW7JQ3M', redirect_location)48 # Write the file out again49 with open(path, 'w') as file:50 file.write(filedata)51 print("Complete...")52 def gmail_attack(self):53 phishing_email = input("Please enter your email: ")54 storage_location = input("Please enter the storage location: ")55 redirect_location = input("Please enter the redirect location (for default type: d): ")56 shutil.copytree('phishing/gmail/', storage_location)57 path = storage_location + "/redirect.php"58 # Read in the file59 with open(path, 'r') as file:60 filedata = file.read()61 # Replace the target string62 filedata = filedata.replace('someone@example.com', phishing_email)63 if redirect_location != "d":64 filedata = filedata.replace('https://drive.google.com/file/d/0B6gbXN_c6lAQWGF1alVfSDNEREE/view', redirect_location)65 # Write the file out again66 with open(path, 'w') as file:67 file.write(filedata)68 print("Complete...")69 def insta_attack(self):70 phishing_email = input("Please enter your email: ")71 storage_location = input("Please enter the storage location: ")72 redirect_location = input("Please enter the redirect location (for default type: d): ")73 shutil.copytree('phishing/instagram/', storage_location)74 path = storage_location + "/login.php"75 # Read in the file76 with open(path, 'r') as file:77 filedata = file.read()78 # Replace the target string79 filedata = filedata.replace('someone@example.com', phishing_email)80 if redirect_location != "d":81 filedata = filedata.replace('https://instagram.com', redirect_location)82 # Write the file out again83 with open(path, 'w') as file:84 file.write(filedata)...
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!!