Best Python code snippet using tavern
whitelist.py
Source:whitelist.py  
1#!/usr/bin/env python2#3# Tool for managing the App Inventor whitelist. The whitelist4# is stored in the App Engine Data Store. However it is only5# consulted if "user.whitelist" is set to true in appengine-web.xml6#78# WhiteListData, an element of the whitelist. This class definition9# *MUST* be congruent to the Java class WhiteListData in StoredData.java10import os11import sys12import getpass13from getopt import getopt, GetoptError1415os.environ['SERVER_SOFTWARE'] = 'MIT Whitelist Generator 1.0' # Googlism1617def auth_func():18  return (raw_input('Email: '), getpass.getpass('Password: '))1920def main():21    getlibdir()22    from google.appengine.ext import db23    from google.appengine.ext.remote_api import remote_api_stub24    from google.appengine.tools import appengine_rpc2526    class WhiteListData(db.Model):27        emailLower = db.StringProperty();2829    whitelistname = 'whitelist'30    host = 'localhost'31    getonly = False32    try:33        opts = getopt(sys.argv[1:], 'n:h:d', ['name=','getonly'])34    except GetoptError:35        sys.stderr.write('Usage: whitelist.py [-n whitelistfile] [-h host] [-d] [--getonly]\n')36        sys.exit(1)37    for opt in opts[0]:38        if opt == []:39            continue40        if len(opt) < 2:41            sys.stderr.write('Usage: whitelist.py [-n whitelistfile] [-h host] [-d] [--getonly]\n')42            sys.exit(1)43        if opt[0] in ('-n', '--name'):44            whitelistname = opt[1]45        elif opt[0] == '-h':46            host = opt[1]47        elif opt[0] == '-d':48            host = 'localhost'49        elif opt[0] == '--getonly':50            getonly = True5152    print 'Using %s for input' % whitelistname53    print 'Connecting to %s' % host54    if host == 'localhost':55        host = host + ':8888'56        secure = False57    else:58        secure = True5960    remote_api_stub.ConfigureRemoteApi(None, '/remote_api', auth_func,61                                       servername=host,62                                       save_cookies=True, secure=secure,63                                       rpc_server_factory=appengine_rpc.HttpRpcServer)64    remote_api_stub.MaybeInvokeAuthentication()6566    input_people = open(whitelistname).readlines()67    input_people = [x.strip() for x in input_people]6869    installed_people = []70    c = None71    while True:72        q = WhiteListData.gql("")73        if c:74            q = q.with_cursor(c)75        z = q.fetch(500)76        c = q.cursor()77        installed_people += z78        if len(z) < 500:79            break8081    if getonly:82        print 'Getonly set, returning existing whitelist with no changes'83        for person in installed_people:84            print person.emailLower85        return8687    WHITE = {}88    for email in input_people:89        WHITE[unicode(email)] = [0, None]90    for person in installed_people:91        email = person.emailLower92        if WHITE.has_key(email):93            WHITE[email] = [2, person]94        else:95            WHITE[email] = [1, person]9697    # Now we go through the dictionary. Remove people in state 198    # and add people in state 099100    for (email, z) in WHITE.items():101        state, person = z102        if state == 0:103            v = WhiteListData()104            v.emailLower = email105            v.put()106            print 'Added %s' % email107        elif state == 1:108            person.delete()109            print 'Removed %s' % email110111112def getlibdir():113    '''Find the googl_appengine library directory'''114    from os.path import expanduser115    import ConfigParser116    doupdate = False117    config = ConfigParser.RawConfigParser()118    configfile = expanduser('~/.appinv_whitelist')119    config.read(configfile)120    libdir = '/usr/local/google_appengine' # Default121    if config.has_section('whitelist'):122        try:123            libdir = config.get('whitelist', 'googlelibdir')124        except ConfigParser.NoOptionError:125            config.set('whitelist', 'googlelibdir', libdir)126            doupdate = True127    else:128        config.add_section('whitelist')129        doupdate = True130    if doupdate:131        f = open(configfile, 'w')132        config.write(f)133        f.close()134    sys.path.insert(0, libdir)135    sys.path.insert(1, libdir + '/lib/fancy_urllib')136    try:137        from google.appengine.ext import db138    except ImportError:139        newpath = raw_input('Google Python App Engine SDK Path [%s]: ' % libdir)140        if newpath == '':141            newpath = libdir142        libdir = newpath143        config.set('whitelist', 'googlelibdir', libdir)144        f = open(configfile, 'w')145        config.write(f)146        f.close()147        print 'Location of Google Library Directory Saved, exiting, try again...'148        sys.exit(0)149150# The stuff below is to permit the prompt for the library dir to151# use filename completion....152153class Completer(object):154155    def _listdir(self, root):156        "List directory 'root' appending the path separator to subdirs."157        res = []158        for name in os.listdir(root):159            path = os.path.join(root, name)160            if os.path.isdir(path):161                name += os.sep162            res.append(name)163        return res164165    def _complete_path(self, path=None):166        "Perform completion of filesystem path."167        if not path:168            return self._listdir('.')169        dirname, rest = os.path.split(path)170        tmp = dirname if dirname else '.'171        res = [os.path.join(dirname, p)172                for p in self._listdir(tmp) if p.startswith(rest)]173        # more than one match, or single match which does not exist (typo)174        if len(res) > 1 or not os.path.exists(path):175            return res176        # resolved to a single directory, so return list of files below it177        if os.path.isdir(path):178            return [os.path.join(path, p) for p in self._listdir(path)]179        # exact file match terminates this completion180        return [path + ' ']181182    def complete_filename(self, args):183        "Completions for the 'extra' command."184        if not args:185            return self._complete_path('.')186        # treat the last arg as a path and complete it187        return self._complete_path(args[-1])188189    def complete(self, text, state):190        "Generic readline completion entry point."191        buffer = readline.get_line_buffer()192        line = buffer.split()193        return (self.complete_filename(line) + [None])[state]194195comp = Completer()196197try:198    import readline199except ImportError:200    print "Module readline not available."201else:202    import rlcompleter203    readline.set_completer_delims(' \t\n;')204    readline.parse_and_bind("tab: complete")205    readline.set_completer(comp.complete)206207if __name__ == '__main__':208    main()
...add-user.py
Source:add-user.py  
1# !/usr/bin/env python2# -*- coding: utf-8 -*-3'''4Script to add a user to 'users' index5v.016'''7from elasticsearch import Elasticsearch8import hashlib9import re10es = Elasticsearch()11username, token, tokenInput, email, getonly, community = "", "","", "ex@ample.com", False, False12newIndex=False13# check if 'users' index exists, otherwise create index14request_body = {15    "settings" : {16        "number_of_shards": 1,17        "number_of_replicas": 118    },19    "mappings": {20        "wsUser": {21            "properties": {22                "peerName": {23                    "type": "text"24                },25                "token": {26                    "type": "text"27                },28                "getOnly": {29                    "type": "boolean"30                },31                "community": {32                    "type": "text"33                ,34                "email": {35                    "type": "text"36                }37            }38        }39    }40}41}42if not es.indices.exists("users"):43    res = es.indices.create(index = 'users', body = request_body, ignore=400)44    newIndex=True45# gather user information46print(chr(27) + "[2J")47print("******************************************")48print("Add new user to ES users index.")49print("******************************************")50# input username51usernameInput = input("Enter new API UserID: ")52username=usernameInput.replace(" ", "_")53# check if user exists54if not newIndex:55    res = es.search(index='users', body={56                  "query": {57                    "term": {58                      "peerName.keyword": username59                    }60                  }61                })62    if res["hits"]["total"] > 0:63        print("User ID '"+ username + "' already exists in index. Choose a different User ID or delete _id : '" + str(res['hits']['hits'][0]['_id'])  + "'. Aborting.")64        exit(1)65# input password66tokenInput = input("Enter new Token: ")67token = hashlib.sha512(tokenInput.encode('utf-8')).hexdigest()68# input email69emailInput = input("Enter Contact Email: ")70if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", emailInput) != None:71    email=emailInput72else:73    print("Invalid email address. Bye.")74    exit(1)75# input getOnly76getonlyInput = input("Is this API user 'read only' who cannot submit data? (y/N): ")77if getonlyInput.lower() == "y":78    getonly = True79# input getOnly80communityInput = input("Can this API user only access 'community data'? (y/N): ")81if communityInput.lower() == "y":82    community = True83print("")84print("You entered:")85print("**************")86print("API User: " + username)87print("API Token: " + tokenInput)88print("Email: " + email)89print("getOnly: " + str(getonly))90print("community: " + str(community))91print("**************")92print("")93correctInput = input("Is the above correct? (y/N)")94if correctInput.lower() != "y":95    print("Ok, rerun script and reenter it.")96    exit(1)97print("OK, adding to ES.")98entry = {99    'peerName': username,100    'token': token,101    'getOnly': getonly,102    'community': community,103    'email': email104}105# add user106res = es.index(index="users", doc_type='wsUser', body=entry)...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!!
