Best Python code snippet using autotest_python
parser.py
Source:parser.py
1#! /usr/bin/python -tt2import re3import urlparse4import urlgrabber5import os.path6import Errors7_KEYCRE = re.compile(r"\$(\w+)")8def varReplace(raw, vars):9 '''Perform variable replacement10 @param raw: String to perform substitution on. 11 @param vars: Dictionary of variables to replace. Key is variable name12 (without $ prefix). Value is replacement string.13 @return: Input raw string with substituted values.14 '''15 done = [] # Completed chunks to return16 while raw:17 m = _KEYCRE.search(raw)18 if not m:19 done.append(raw)20 break21 # Determine replacement value (if unknown variable then preserve22 # original)23 varname = m.group(1).lower()24 replacement = vars.get(varname, m.group())25 start, end = m.span()26 done.append(raw[:start]) # Keep stuff leading up to token27 done.append(replacement) # Append replacement value28 raw = raw[end:] # Continue with remainder of string29 return ''.join(done)30class ConfigPreProcessor:31 """32 ConfigParser Include Pre-Processor33 File-like Object capable of pre-processing include= lines for34 a ConfigParser. 35 The readline function expands lines matching include=(url)36 into lines from the url specified. Includes may occur in37 included files as well. 38 Suggested Usage::39 cfg = ConfigParser.ConfigParser()40 fileobj = confpp( fileorurl )41 cfg.readfp(fileobj)42 """43 44 45 def __init__(self, configfile, vars=None):46 # put the vars away in a helpful place47 self._vars = vars48 # used to track the current ini-section49 self._section = None50 51 # set some file-like object attributes for ConfigParser52 # these just make confpp look more like a real file object.53 self.mode = 'r' 54 55 # first make configfile a url even if it points to 56 # a local file57 scheme = urlparse.urlparse(configfile)[0]58 if scheme == '':59 # check it to make sure it's not a relative file url60 if configfile[0] != '/':61 configfile = os.getcwd() + '/' + configfile62 url = 'file://' + configfile63 else:64 url = configfile65 66 # these are used to maintain the include stack and check67 # for recursive/duplicate includes68 self._incstack = []69 self._alreadyincluded = []70 71 # _pushfile will return None if he couldn't open the file72 fo = self._pushfile( url )73 if fo is None: 74 raise Errors.ConfigError, 'Error accessing file: %s' % url75 76 def readline( self, size=0 ):77 """78 Implementation of File-Like Object readline function. This should be79 the only function called by ConfigParser according to the python docs.80 We maintain a stack of real FLOs and delegate readline calls to the 81 FLO on top of the stack. When EOF occurs on the topmost FLO, it is 82 popped off the stack and the next FLO takes over. include= lines 83 found anywhere cause a new FLO to be opened and pushed onto the top 84 of the stack. Finally, we return EOF when the bottom-most (configfile85 arg to __init__) FLO returns EOF.86 87 Very Technical Pseudo Code::88 89 def confpp.readline() [this is called by ConfigParser]90 open configfile, push on stack91 while stack has some stuff on it92 line = readline from file on top of stack93 pop and continue if line is EOF94 if line starts with 'include=' then95 error if file is recursive or duplicate96 otherwise open file, push on stack97 continue98 else99 return line100 101 return EOF102 """103 104 # set line to EOF initially. 105 line=''106 while len(self._incstack) > 0:107 # peek at the file like object on top of the stack108 fo = self._incstack[-1]109 line = fo.readline()110 if len(line) > 0:111 m = re.match( r'\s*include\s*=\s*(?P<url>.*)', line )112 if m:113 url = m.group('url')114 if len(url) == 0:115 raise Errors.ConfigError, \116 'Error parsing config %s: include must specify file to include.' % (self.name)117 else:118 # whooohoo a valid include line.. push it on the stack119 fo = self._pushfile( url )120 else:121 # check if the current line starts a new section122 secmatch = re.match( r'\s*\[(?P<section>.*)\]', line )123 if secmatch:124 self._section = secmatch.group('section')125 # line didn't match include=, just return it as is126 # for the ConfigParser127 break128 else:129 # the current file returned EOF, pop it off the stack.130 self._popfile()131 132 # at this point we have a line from the topmost file on the stack133 # or EOF if the stack is empty134 if self._vars:135 return varReplace(line, self._vars)136 return line137 138 139 def _absurl( self, url ):140 """141 Returns an absolute url for the (possibly) relative142 url specified. The base url used to resolve the143 missing bits of url is the url of the file currently144 being included (i.e. the top of the stack).145 """146 147 if len(self._incstack) == 0:148 # it's the initial config file. No base url to resolve against.149 return url150 else:151 return urlparse.urljoin( self.geturl(), url )152 def _pushfile( self, url ):153 """154 Opens the url specified, pushes it on the stack, and 155 returns a file like object. Returns None if the url 156 has previously been included.157 If the file can not be opened this function exits.158 """159 160 # absolutize this url using the including files url161 # as a base url.162 absurl = self._absurl(url)163 # get the current section to add it to the included164 # url's name.165 includetuple = (absurl, self._section)166 # check if this has previously been included.167 if self._isalreadyincluded(includetuple):168 return None169 try:170 fo = urlgrabber.grabber.urlopen(absurl)171 except urlgrabber.grabber.URLGrabError, e:172 fo = None173 if fo is not None:174 self.name = absurl175 self._incstack.append( fo )176 self._alreadyincluded.append(includetuple)177 else:178 raise Errors.ConfigError, \179 'Error accessing file for config %s' % (absurl)180 return fo181 182 183 def _popfile( self ):184 """185 Pop a file off the stack signaling completion of including that file.186 """187 fo = self._incstack.pop()188 fo.close()189 if len(self._incstack) > 0:190 self.name = self._incstack[-1].geturl()191 else:192 self.name = None193 194 195 def _isalreadyincluded( self, tuple ):196 """197 Checks if the tuple describes an include that was already done.198 This does not necessarily have to be recursive199 """200 for etuple in self._alreadyincluded:201 if etuple == tuple: return 1202 return 0203 204 ...
absurl.py
Source:absurl.py
1from urlparse import urljoin2from django.template import Library3from django.template.defaulttags import URLNode, url4from django.core.exceptions import ImproperlyConfigured5from django.utils.encoding import iri_to_uri6from django.contrib.sites.models import Site7from django.db.models import get_app8register = Library()9class AbsoluteURLNode(URLNode):10 def _get_baseurl(self, context):11 baseurl = None12 if '_ABSURL' in context:13 baseurl = context['_ABSURL']14 elif get_app('sites', emptyOK=True):15 baseurl = u'http://' + Site.objects.get_current().domain16 else:17 raise ImproperlyConfigured('ABSURL demands a Context Processor OR the django.contrib.sites app. Pick one!')18 return baseurl19 def _get_path(self, context):20 path = super(AbsoluteURLNode, self).render(context)21 if self.asvar:22 path = context[self.asvar]23 return path24 def render(self, context):25 baseurl = self._get_baseurl(context)26 path = self._get_path(context)27 url = iri_to_uri(urljoin(baseurl, path))28 if self.asvar:29 context[self.asvar] = url30 return ''31 else:32 return url33def absurl(parser, token):34 """Just like {% url %} but ads the domain of the current site."""35 # invoke url setup just to parse the arguments.36 node = url(parser, token)37 # then pass the parsed args to the actual node instance38 return AbsoluteURLNode(view_name=node.view_name,39 args=node.args,40 kwargs=node.kwargs,41 asvar=node.asvar)...
context_processors.py
Source:context_processors.py
1from django.conf import settings2from django.db.models import Count3def absurl(request):4 scheme = request.is_secure() and 'https' or 'http'5 hostname = request.get_host()...
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!!