How to use current_app method in ATX

Best Python code snippet using ATX

views.py

Source:views.py Github

copy

Full Screen

1import urlparse2from django.conf import settings3from django.core.urlresolvers import reverse4from django.http import HttpResponseRedirect, QueryDict5from django.template.response import TemplateResponse6from django.utils.http import base36_to_int7from django.utils.translation import ugettext as _8from django.views.decorators.cache import never_cache9from django.views.decorators.csrf import csrf_protect10# Avoid shadowing the login() and logout() views below.11from django.contrib.auth import REDIRECT_FIELD_NAME, login as auth_login, logout as auth_logout12from django.contrib.auth.decorators import login_required13from django.contrib.auth.forms import AuthenticationForm, PasswordResetForm, SetPasswordForm, PasswordChangeForm14from django.contrib.auth.models import User15from django.contrib.auth.tokens import default_token_generator16from django.contrib.sites.models import get_current_site17@csrf_protect18@never_cache19def login(request, template_name='registration/login.html',20 redirect_field_name=REDIRECT_FIELD_NAME,21 authentication_form=AuthenticationForm,22 current_app=None, extra_context=None):23 """24 Displays the login form and handles the login action.25 """26 redirect_to = request.REQUEST.get(redirect_field_name, '')27 if request.method == "POST":28 form = authentication_form(data=request.POST)29 if form.is_valid():30 netloc = urlparse.urlparse(redirect_to)[1]31 # Use default setting if redirect_to is empty32 if not redirect_to:33 redirect_to = settings.LOGIN_REDIRECT_URL34 # Heavier security check -- don't allow redirection to a different35 # host.36 elif netloc and netloc != request.get_host():37 redirect_to = settings.LOGIN_REDIRECT_URL38 # Okay, security checks complete. Log the user in.39 auth_login(request, form.get_user())40 if request.session.test_cookie_worked():41 request.session.delete_test_cookie()42 return HttpResponseRedirect(redirect_to)43 else:44 form = authentication_form(request)45 request.session.set_test_cookie()46 current_site = get_current_site(request)47 context = {48 'form': form,49 redirect_field_name: redirect_to,50 'site': current_site,51 'site_name': current_site.name,52 }53 if extra_context is not None:54 context.update(extra_context)55 return TemplateResponse(request, template_name, context,56 current_app=current_app)57def logout(request, next_page=None,58 template_name='registration/logged_out.html',59 redirect_field_name=REDIRECT_FIELD_NAME,60 current_app=None, extra_context=None):61 """62 Logs out the user and displays 'You are logged out' message.63 """64 auth_logout(request)65 redirect_to = request.REQUEST.get(redirect_field_name, '')66 if redirect_to:67 netloc = urlparse.urlparse(redirect_to)[1]68 # Security check -- don't allow redirection to a different host.69 if not (netloc and netloc != request.get_host()):70 return HttpResponseRedirect(redirect_to)71 if next_page is None:72 current_site = get_current_site(request)73 context = {74 'site': current_site,75 'site_name': current_site.name,76 'title': _('Logged out')77 }78 if extra_context is not None:79 context.update(extra_context)80 return TemplateResponse(request, template_name, context,81 current_app=current_app)82 else:83 # Redirect to this page until the session has been cleared.84 return HttpResponseRedirect(next_page or request.path)85def logout_then_login(request, login_url=None, current_app=None, extra_context=None):86 """87 Logs out the user if he is logged in. Then redirects to the log-in page.88 """89 if not login_url:90 login_url = settings.LOGIN_URL91 return logout(request, login_url, current_app=current_app, extra_context=extra_context)92def redirect_to_login(next, login_url=None,93 redirect_field_name=REDIRECT_FIELD_NAME):94 """95 Redirects the user to the login page, passing the given 'next' page96 """97 if not login_url:98 login_url = settings.LOGIN_URL99 login_url_parts = list(urlparse.urlparse(login_url))100 if redirect_field_name:101 querystring = QueryDict(login_url_parts[4], mutable=True)102 querystring[redirect_field_name] = next103 login_url_parts[4] = querystring.urlencode(safe='/')104 return HttpResponseRedirect(urlparse.urlunparse(login_url_parts))105# 4 views for password reset:106# - password_reset sends the mail107# - password_reset_done shows a success message for the above108# - password_reset_confirm checks the link the user clicked and109# prompts for a new password110# - password_reset_complete shows a success message for the above111@csrf_protect112def password_reset(request, is_admin_site=False,113 template_name='registration/password_reset_form.html',114 email_template_name='registration/password_reset_email.html',115 password_reset_form=PasswordResetForm,116 token_generator=default_token_generator,117 post_reset_redirect=None,118 from_email=None,119 current_app=None,120 extra_context=None):121 if post_reset_redirect is None:122 post_reset_redirect = reverse('django.contrib.auth.views.password_reset_done')123 if request.method == "POST":124 form = password_reset_form(request.POST)125 if form.is_valid():126 opts = {127 'use_https': request.is_secure(),128 'token_generator': token_generator,129 'from_email': from_email,130 'email_template_name': email_template_name,131 'request': request,132 }133 if is_admin_site:134 opts = dict(opts, domain_override=request.META['HTTP_HOST'])135 form.save(**opts)136 return HttpResponseRedirect(post_reset_redirect)137 else:138 form = password_reset_form()139 context = {140 'form': form,141 }142 if extra_context is not None:143 context.update(extra_context)144 return TemplateResponse(request, template_name, context,145 current_app=current_app)146def password_reset_done(request,147 template_name='registration/password_reset_done.html',148 current_app=None, extra_context=None):149 context = {}150 if extra_context is not None:151 context.update(extra_context)152 return TemplateResponse(request, template_name, context,153 current_app=current_app)154# Doesn't need csrf_protect since no-one can guess the URL155@never_cache156def password_reset_confirm(request, uidb36=None, token=None,157 template_name='registration/password_reset_confirm.html',158 token_generator=default_token_generator,159 set_password_form=SetPasswordForm,160 post_reset_redirect=None,161 current_app=None, extra_context=None):162 """163 View that checks the hash in a password reset link and presents a164 form for entering a new password.165 """166 assert uidb36 is not None and token is not None # checked by URLconf167 if post_reset_redirect is None:168 post_reset_redirect = reverse('django.contrib.auth.views.password_reset_complete')169 try:170 uid_int = base36_to_int(uidb36)171 user = User.objects.get(id=uid_int)172 except (ValueError, User.DoesNotExist):173 user = None174 if user is not None and token_generator.check_token(user, token):175 validlink = True176 if request.method == 'POST':177 form = set_password_form(user, request.POST)178 if form.is_valid():179 form.save()180 return HttpResponseRedirect(post_reset_redirect)181 else:182 form = set_password_form(None)183 else:184 validlink = False185 form = None186 context = {187 'form': form,188 'validlink': validlink,189 }190 if extra_context is not None:191 context.update(extra_context)192 return TemplateResponse(request, template_name, context,193 current_app=current_app)194def password_reset_complete(request,195 template_name='registration/password_reset_complete.html',196 current_app=None, extra_context=None):197 context = {198 'login_url': settings.LOGIN_URL199 }200 if extra_context is not None:201 context.update(extra_context)202 return TemplateResponse(request, template_name, context,203 current_app=current_app)204@csrf_protect205@login_required206def password_change(request,207 template_name='registration/password_change_form.html',208 post_change_redirect=None,209 password_change_form=PasswordChangeForm,210 current_app=None, extra_context=None):211 if post_change_redirect is None:212 post_change_redirect = reverse('django.contrib.auth.views.password_change_done')213 if request.method == "POST":214 form = password_change_form(user=request.user, data=request.POST)215 if form.is_valid():216 form.save()217 return HttpResponseRedirect(post_change_redirect)218 else:219 form = password_change_form(user=request.user)220 context = {221 'form': form,222 }223 if extra_context is not None:224 context.update(extra_context)225 return TemplateResponse(request, template_name, context,226 current_app=current_app)227def password_change_done(request,228 template_name='registration/password_change_done.html',229 current_app=None, extra_context=None):230 context = {}231 if extra_context is not None:232 context.update(extra_context)233 return TemplateResponse(request, template_name, context,...

Full Screen

Full Screen

godaddy.py

Source:godaddy.py Github

copy

Full Screen

1from app.blueprints.api.domain.pynamecheap.namecheap import Api2from app.blueprints.api.api_functions import print_traceback3from app.blueprints.page.date import get_string_from_utc_datetime4from flask import current_app, flash5from app.blueprints.page.date import get_dt_string6import pythonwhois7import datetime8import tldextract9import pytz10import requests11import json12from dynadotpy.client import Dynadot13# Godaddy check domain availability14def check_domain(domain, test=True):15 try:16 # Get the GoDaddy keys17 api_key = current_app.config.get('GODADDY_TEST_API_KEY') if test else current_app.config.get('GODADDY_API_KEY')18 api_secret = current_app.config.get('GODADDY_TEST_SECRET_KEY') if test else current_app.config.get('GODADDY_SECRET_KEY')19 # Get the URL20 url = current_app.config.get('GODADDY_TEST_API_URL') if test else current_app.config.get('GODADDY_API_URL')21 url = url + '/v1/domains/available?domain=' + domain22 headers = {23 "Authorization": "sso-key " + api_key + ":" + api_secret,24 "Accept": "application/json",25 "Content-Type": "application/json"26 }27 r = requests.get(url, headers=headers)28 # print(r.text)29 if r.status_code == 200:30 return json.loads(r.text)31 else:32 return None33 except Exception as e:34 print_traceback(e)35 return None36# Get WhoIs domain availability37def get_domain_availability(domain):38 details = dict()39 try:40 # Check GoDaddy first41 if check_domain(domain, False) is not None:42 ext = tldextract.extract(domain)43 domain = ext.registered_domain44 details = pythonwhois.get_whois(domain)45 if 'expiration_date' in details and len(details['expiration_date']) > 0 and details['expiration_date'][0] is not None:46 expires = get_dt_string(details['expiration_date'][0])47 details.update({'name': domain, 'available': False, 'expires': expires})48 else:49 details.update({'name': domain, 'available': True, 'expires': None})50 else:51 details.update({'name': domain, 'available': None, 'expires': None})52 except Exception as e:53 print_traceback(e)54 details.update({'name': domain, 'available': None, 'expires': None})55 return details56# GoDaddy purchase domain57def purchase_domain(domain, test=True):58 try:59 # Make sure the domain is available before trying to buy it60 availability = check_domain(domain, test)61 # Don't buy any domains that are more than $5962 if availability is not None and availability['available'] and availability['price'] <= 59990000:63 # Get the GoDaddy keys64 api_key = current_app.config.get('GODADDY_TEST_API_KEY') if test else current_app.config.get('GODADDY_API_KEY')65 api_secret = current_app.config.get('GODADDY_TEST_SECRET_KEY') if test else current_app.config.get('GODADDY_SECRET_KEY')66 # Get the URL67 url = current_app.config.get('GODADDY_TEST_API_URL') if test else current_app.config.get('GODADDY_API_URL')68 url = url + '/v1/domains/purchase'69 headers = {70 "Authorization": "sso-key " + api_key + ":" + api_secret,71 "Accept": "application/json",72 "Content-Type": "application/json",73 }74 registration = current_app.config.get('NAMECHEAP_REGISTRATION')75 contact_info = {76 'addressMailing': {77 'address1': registration['Address1'],78 'address2': '',79 'city': registration['City'],80 'state': registration['StateProvince'],81 'postalCode': registration['PostalCode'],82 'country': 'US',83 },84 'email': registration['EmailAddress'],85 'fax': '',86 'jobTitle': 'owner',87 'nameFirst': registration['FirstName'],88 'nameLast': registration['LastName'],89 'nameMiddle': '',90 'organization': 'namecatcher.io',91 'phone': registration['Phone'],92 }93 body = json.dumps({94 'consent': {95 'agreedAt': get_string_from_utc_datetime(datetime.datetime.now(pytz.utc), True),96 'agreedBy': str(current_app.config.get('IP_ADDRESS')),97 'agreementKeys': ['DNRA']98 },99 'contactAdmin': contact_info,100 'contactBilling': contact_info,101 'contactRegistrant': contact_info,102 'contactTech': contact_info,103 'domain': domain,104 'period': 1,105 'privacy': False,106 'renewAuto': True107 })108 r = requests.post(url, headers=headers, data=body)109 print(r.status_code)110 print(r.text)111 # Domain was successfully purchased112 if r.status_code == 200:113 return True114 else:115 return json.loads(r.text)116 elif availability is not None and not availability['available']:117 return False118 else:119 return None120 except Exception as e:121 print_traceback(e)122 return None123# Godaddy check domain124def list_domains(test=True):125 try:126 # Get the GoDaddy keys127 api_key = current_app.config.get('GODADDY_TEST_API_KEY') if test else current_app.config.get('GODADDY_API_KEY')128 api_secret = current_app.config.get('GODADDY_TEST_SECRET_KEY') if test else current_app.config.get('GODADDY_SECRET_KEY')129 # Get the URL130 url = current_app.config.get('GODADDY_TEST_API_URL') if test else current_app.config.get('GODADDY_API_URL')131 url = url + '/v1/domains'132 headers = {133 "Authorization": "sso-key " + api_key + ":" + api_secret,134 "Accept": "application/json",135 "Content-Type": "application/json"136 }137 r = requests.get(url, headers=headers)138 print(r.text)139 if r.status_code == 200:140 return r.text141 except Exception as e:142 print_traceback(e)143 return None144# Godaddy Get Purchase Agreement145def get_purchase_agreement(domain, test=True):146 try:147 # Get the GoDaddy keys148 api_key = current_app.config.get('GODADDY_TEST_API_KEY') if test else current_app.config.get('GODADDY_API_KEY')149 api_secret = current_app.config.get('GODADDY_TEST_SECRET_KEY') if test else current_app.config.get('GODADDY_SECRET_KEY')150 # Get a list of TLDs for the purchase agreement151 ext = tldextract.extract(domain)152 tld = '.' + ext.suffix153 # Get the URL154 url = current_app.config.get('GODADDY_TEST_API_URL') if test else current_app.config.get('GODADDY_API_URL')155 url = url + '/v1/domains/agreements?tlds=' + tld + "&privacy=false"156 headers = {157 "Authorization": "sso-key " + api_key + ":" + api_secret,158 "Accept": "application/json",159 "Content-Type": "application/json"160 }161 r = requests.get(url, headers=headers)162 print(r.status_code)163 print(r.text)164 if r.status_code == 200:165 return r166 except Exception as e:167 print_traceback(e)168 return None169# Godaddy get TLD Schema170def get_tld_schema(domain, test=True):171 try:172 # Get the GoDaddy keys173 api_key = current_app.config.get('GODADDY_TEST_API_KEY') if test else current_app.config.get('GODADDY_API_KEY')174 api_secret = current_app.config.get('GODADDY_TEST_SECRET_KEY') if test else current_app.config.get('GODADDY_SECRET_KEY')175 # Get a list of TLDs for the purchase agreement176 ext = tldextract.extract(domain)177 tld = ext.suffix178 # Get the URL179 url = current_app.config.get('GODADDY_TEST_API_URL') if test else current_app.config.get('GODADDY_API_URL')180 url = url + '/v1/domains/purchase/schema/' + tld181 headers = {182 "Authorization": "sso-key " + api_key + ":" + api_secret,183 "Accept": "application/json",184 "Content-Type": "application/json"185 }186 r = requests.get(url, headers=headers)187 # print(r.status_code)188 # print(r.text)189 parsed = json.loads(r.text)190 print(json.dumps(parsed, indent=4, sort_keys=True))191 if r.status_code == 200:192 return json.loads(r.text)['properties']193 except Exception as e:194 print_traceback(e)...

Full Screen

Full Screen

pg.py

Source:pg.py Github

copy

Full Screen

1"""click interface for postgresql commands.2"""3import logging4import os5import subprocess6import click7from flask import current_app8from flask.cli import AppGroup9DEFAULT_DB_BACKUP_PATH = 'db.pg_dump'10logger = logging.getLogger(__name__)11logger.setLevel(logging.DEBUG)12cli = AppGroup(help=__doc__, name='pg')13@cli.command()14@click.option('-l', '--location', default=DEFAULT_DB_BACKUP_PATH)15@click.option('--format', default='c')16def dump(location, format):17 """Run pg_dump."""18 os.environ['PGPASSWORD'] = current_app.config['PG_PASSWORD']19 pg_dump = current_app.config.get('PG_BIN_DIR', '') + 'pg_dump'20 subprocess.call((21 pg_dump,22 '--host={}'.format(current_app.config['PG_HOST']),23 '--username={}'.format(current_app.config['PG_USERNAME']),24 '--format=%s' % format,25 current_app.config['PG_DB_NAME'],26 '--file=%s' % location,27 ))28@cli.command()29@click.option('-l', '--location', default=DEFAULT_DB_BACKUP_PATH)30def restore(location):31 """Restore pg_dump."""32 os.environ['PGPASSWORD'] = current_app.config['PG_PASSWORD']33 pg_restore = current_app.config.get('PG_BIN_DIR', '') + 'pg_restore'34 subprocess.call((35 pg_restore,36 '--host={}'.format(current_app.config['PG_HOST']),37 '--username={}'.format(current_app.config['PG_USERNAME']),38 '--dbname={}'.format(current_app.config['PG_DB_NAME']),39 '--clean',40 location,41 ))42@cli.command()43@click.option('-c', '--command')44@click.option('-f', '--file')45def psql(command=None, file=None):46 """Call psql."""47 os.environ['PGPASSWORD'] = current_app.config['PG_PASSWORD']48 psql = current_app.config.get('PG_BIN_DIR', '') + 'psql'49 args = [50 psql,51 '--host={}'.format(current_app.config['PG_HOST']),52 '--username={}'.format(current_app.config['PG_USERNAME']),53 '--dbname={}'.format(current_app.config['PG_DB_NAME']),54 ]55 if command:56 args.append('--command=%s' % command)57 if file:58 args.append('--file=%s' % file)...

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