Python string.ascii_letters() Examples
The following are 30 code examples for showing how to use string.ascii_letters(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
You may check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
string
, or try the search function
.
Example 1
Project: XFLTReaT Author: earthquake File: DNS.py License: MIT License | 8 votes |
def cmh_autotune(self, module, message, additional_data, cm): message = message[len(self.CONTROL_AUTOTUNE)+2:] # get tune type, requested record type, length and encoding for crafting the answer (query_type, RRtype, length, encode_class) = struct.unpack("<BHHH", message[0:7]) if self.DNS_proto.get_RR_type(RRtype)[0] == None: return True # extra parameters added to be able to response in the proper way additional_data = additional_data + (True, self.download_encoding_list[encode_class], self.DNS_proto.get_RR_type(RRtype)[0]) if (query_type == 0) or (query_type == 3): # record && downstream length discovery message = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length)) if query_type == 1: # A record name length discovery message = struct.pack("<i", binascii.crc32(message[7:])) if query_type == 2: # checking download encoding, echoing back request payload message = message[7:] module.send(common.CONTROL_CHANNEL_BYTE, self.CONTROL_AUTOTUNE_CLIENT+message, additional_data) return True # tune control message handler # client sets the record type and encodings by calling this # server side
Example 2
Project: aegea Author: kislyuk File: ssh.py License: Apache License 2.0 | 7 votes |
def scp(args): """ Transfer files to or from EC2 instance. """ scp_opts, host_opts = extract_passthrough_opts(args, "scp"), [] user_or_hostname_chars = string.ascii_letters + string.digits ssm_init_complete = False for i, arg in enumerate(args.scp_args): if arg[0] in user_or_hostname_chars and ":" in arg: hostname, colon, path = arg.partition(":") username, at, hostname = hostname.rpartition("@") if args.use_ssm and not ssm_init_complete: scp_opts += init_ssm(get_instance(hostname).id) ssm_init_complete = True host_opts, hostname = prepare_ssh_host_opts(username=username, hostname=hostname, bless_config_filename=args.bless_config, use_kms_auth=args.use_kms_auth, use_ssm=args.use_ssm) args.scp_args[i] = hostname + colon + path os.execvp("scp", ["scp"] + scp_opts + host_opts + args.scp_args)
Example 3
Project: bottle-yang-extractor-validator Author: YangCatalog File: views.py License: BSD 2-Clause "Simplified" License | 7 votes |
def copy_dependencies(f): config_path = '/etc/yangcatalog/yangcatalog.conf' config = ConfigParser.ConfigParser() config._interpolation = ConfigParser.ExtendedInterpolation() config.read(config_path) yang_models = config.get('Directory-Section', 'save-file-dir') tmp = config.get('Directory-Section', 'temp') out = f.getvalue() letters = string.ascii_letters suffix = ''.join(random.choice(letters) for i in range(8)) dep_dir = '{}/yangvalidator-dependencies-{}'.format(tmp, suffix) os.mkdir(dep_dir) dependencies = out.split(':')[1].strip().split(' ') for dep in dependencies: for file in glob.glob(r'{}/{}*.yang'.format(yang_models, dep)): shutil.copy(file, dep_dir) return dep_dir
Example 4
Project: sanic Author: huge-success File: test_url_building.py License: MIT License | 7 votes |
def test_fails_url_build_if_param_not_passed(app): url = "/" for letter in string.ascii_letters: url += f"<{letter}>/" @app.route(url) def fail(request): return text("this should fail") fail_args = list(string.ascii_letters) fail_args.pop() fail_kwargs = {l: l for l in fail_args} with pytest.raises(URLBuildError) as e: app.url_for("fail", **fail_kwargs) assert "Required parameter `Z` was not passed to url_for" in str(e.value)
Example 5
Project: vault Author: gabfl File: Encryption.py License: MIT License | 7 votes |
def gen_salt(self, set_=True): """ Generate a random salt """ min_char = 8 max_char = 12 allchar = string.ascii_letters + string.punctuation + string.digits salt = "".join(choice(allchar) for x in range(randint(min_char, max_char))).encode() # Set the salt in the same instance if required if set_: self.set_salt(salt) return salt
Example 6
Project: qutebrowser Author: qutebrowser File: test_models.py License: GNU General Public License v3.0 | 7 votes |
def test_tab_completion_not_sorted(qtmodeltester, fake_web_tab, win_registry, tabbed_browser_stubs): """Ensure that the completion row order is the same as tab index order. Would be violated for more than 9 tabs if the completion was being alphabetically sorted on the first column, or the others. """ expected = [] for idx in range(1, 11): url = "".join(random.sample(string.ascii_letters, 12)) title = "".join(random.sample(string.ascii_letters, 12)) expected.append(("0/{}".format(idx), url, title)) tabbed_browser_stubs[0].widget.tabs = [ fake_web_tab(QUrl(tab[1]), tab[2], idx) for idx, tab in enumerate(expected) ] model = miscmodels.buffer() model.set_pattern('') qtmodeltester.check(model) _check_completions(model, { '0': expected, '1': [], })
Example 7
Project: pySmartDL Author: iTaybb File: test_pySmartDL.py License: The Unlicense | 7 votes |
def setUp(self): warnings.filterwarnings("ignore", category=ResourceWarning, message="unclosed.*<ssl.SSLSocket.*>") self.dl_dir = os.path.join(tempfile.gettempdir(), "".join([random.choice(string.ascii_letters+string.digits) for i in range(8)]), '') while os.path.exists(self.dl_dir): self.dl_dir = os.path.join(tempfile.gettempdir(), "".join([random.choice(string.ascii_letters+string.digits) for i in range(8)]), '') self.res_7za920_mirrors = [ "https://github.com/iTaybb/pySmartDL/raw/master/test/7za920.zip", "https://sourceforge.mirrorservice.org/s/se/sevenzip/7-Zip/9.20/7za920.zip", "http://www.bevc.net/dl/7za920.zip", "http://ftp.psu.ru/tools/7-zip/stable/7za920.zip", "http://www.mirrorservice.org/sites/downloads.sourceforge.net/s/se/sevenzip/7-Zip/9.20/7za920.zip" ] self.res_7za920_hash = '2a3afe19c180f8373fa02ff00254d5394fec0349f5804e0ad2f6067854ff28ac' self.res_testfile_1gb = 'http://www.ovh.net/files/1Gio.dat' self.res_testfile_100mb = 'http://www.ovh.net/files/100Mio.dat' self.enable_logging = "-vvv" in sys.argv
Example 8
Project: stream Author: gynvael File: casm.py License: MIT License | 7 votes |
def s_cname(s, t): CNAME0 = string.ascii_letters + "_.!:" CNAME1 = string.ascii_letters + string.digits + "_." token = "" if s.peek() not in CNAME0: return False token = s.get() try: while s.peek() in CNAME1: token += s.get() except StreamException: pass t.append((TokenTypes.IDENTIFIER, token)) # TODO: maybe add more info on type return True
Example 9
Project: stream Author: gynvael File: casm.py License: MIT License | 7 votes |
def s_ctype(s, t): CTYPE0 = string.ascii_letters + "_.!:" CTYPE1 = string.ascii_letters + string.digits + "_." token = "" if s.peek() not in CTYPE0: return False token = s.get() try: while s.peek() in CTYPE1: token += s.get() except StreamException: pass t.append(token) # TODO: maybe add more info on type return True
Example 10
Project: tomlkit Author: sdispater File: items.py License: MIT License | 7 votes |
def __init__( self, k, t=None, sep=None, dotted=False ): # type: (str, Optional[KeyType], Optional[str], bool) -> None if t is None: if any( [c not in string.ascii_letters + string.digits + "-" + "_" for c in k] ): t = KeyType.Basic else: t = KeyType.Bare self.t = t if sep is None: sep = " = " self.sep = sep self.key = k self._dotted = dotted
Example 11
Project: pyeclib Author: openstack File: test_pyeclib_c.py License: BSD 2-Clause "Simplified" License | 6 votes |
def _create_tmp_files(self): """ Create the temporary files needed for testing. Use the tempfile package so that the files will be automatically removed during garbage collection. """ for size_str in self.sizes: # Determine the size of the file to create size_desc = size_str.split("-") size = int(size_desc[0]) if size_desc[1] == 'M': size *= 1000000 elif size_desc[1] == 'K': size *= 1000 # Create the dictionary of files to test with buf = ''.join(random.choice(ascii_letters) for i in range(size)) if sys.version_info >= (3,): buf = buf.encode('ascii') tmp_file = tempfile.NamedTemporaryFile('w+b') tmp_file.write(buf) self.files[size_str] = tmp_file
Example 12
Project: pyeclib Author: openstack File: test_pyeclib_api.py License: BSD 2-Clause "Simplified" License | 6 votes |
def _create_tmp_files(self): """ Create the temporary files needed for testing. Use the tempfile package so that the files will be automatically removed during garbage collection. """ for size_str in self.file_sizes: # Determine the size of the file to create size_desc = size_str.split("-") size = int(size_desc[0]) if size_desc[1] == 'M': size *= 1000000 elif size_desc[1] == 'K': size *= 1000 # Create the dictionary of files to test with buf = ''.join(random.choice(ascii_letters) for i in range(size)) if sys.version_info >= (3,): buf = buf.encode('ascii') tmp_file = tempfile.NamedTemporaryFile() tmp_file.write(buf) self.files[size_str] = tmp_file
Example 13
Project: pyeclib Author: openstack File: test_pyeclib_api.py License: BSD 2-Clause "Simplified" License | 6 votes |
def test_verify_fragment_inline_chksum_succeed(self): pyeclib_drivers = self.get_pyeclib_testspec("inline_crc32") filesize = 1024 * 1024 * 3 file_str = ''.join(random.choice(ascii_letters) for i in range(filesize)) file_bytes = file_str.encode('utf-8') for pyeclib_driver in pyeclib_drivers: fragments = pyeclib_driver.encode(file_bytes) fragment_metadata_list = [] for fragment in fragments: fragment_metadata_list.append( pyeclib_driver.get_metadata(fragment)) expected_ret_value = {"status": 0} self.assertTrue(pyeclib_driver.verify_stripe_metadata( fragment_metadata_list) == expected_ret_value)
Example 14
Project: wanggeService Author: pchaos File: base.py License: MIT License | 6 votes |
def getRandomStr(types='letter', length=8): """ 随机产生length长度的字符串 :param types: 随机字符串的类型 types in ['letter', 'ascii'] 返回包含字母的字符串 types in ['digit', 'num']: 返回包含数字的字符串 其他:返回混合字母和数字的字符串 :param length: 返回字符串的长度 :return: 长度为length,类型为types的字符串 todo string.punctuation """ import random import string if types in ['letter', 'ascii']: return ''.join(random.sample(string.ascii_letters, length)) if types in ['digit', 'num']: return ''.join(random.sample(string.digits, length)) else: return ''.join(random.sample(string.ascii_letters + string.digits, length))
Example 15
Project: recruit Author: Frank-qlu File: test_frame.py License: Apache License 2.0 | 6 votes |
def test_plot_scatter(self): df = DataFrame(randn(6, 4), index=list(string.ascii_letters[:6]), columns=['x', 'y', 'z', 'four']) _check_plot_works(df.plot.scatter, x='x', y='y') _check_plot_works(df.plot.scatter, x=1, y=2) with pytest.raises(TypeError): df.plot.scatter(x='x') with pytest.raises(TypeError): df.plot.scatter(y='y') # GH 6951 axes = df.plot(x='x', y='y', kind='scatter', subplots=True) self._check_axes_shape(axes, axes_num=1, layout=(1, 1))
Example 16
Project: recruit Author: Frank-qlu File: test_frame.py License: Apache License 2.0 | 6 votes |
def test_boxplot_return_type(self): df = DataFrame(randn(6, 4), index=list(string.ascii_letters[:6]), columns=['one', 'two', 'three', 'four']) with pytest.raises(ValueError): df.plot.box(return_type='NOTATYPE') result = df.plot.box(return_type='dict') self._check_box_return_type(result, 'dict') result = df.plot.box(return_type='axes') self._check_box_return_type(result, 'axes') result = df.plot.box() # default axes self._check_box_return_type(result, 'axes') result = df.plot.box(return_type='both') self._check_box_return_type(result, 'both')
Example 17
Project: recruit Author: Frank-qlu File: test_boxplot_method.py License: Apache License 2.0 | 6 votes |
def test_boxplot_legacy1(self): df = DataFrame(np.random.randn(6, 4), index=list(string.ascii_letters[:6]), columns=['one', 'two', 'three', 'four']) df['indic'] = ['foo', 'bar'] * 3 df['indic2'] = ['foo', 'bar', 'foo'] * 2 _check_plot_works(df.boxplot, return_type='dict') _check_plot_works(df.boxplot, column=[ 'one', 'two'], return_type='dict') # _check_plot_works adds an ax so catch warning. see GH #13188 with tm.assert_produces_warning(UserWarning): _check_plot_works(df.boxplot, column=['one', 'two'], by='indic') _check_plot_works(df.boxplot, column='one', by=['indic', 'indic2']) with tm.assert_produces_warning(UserWarning): _check_plot_works(df.boxplot, by='indic') with tm.assert_produces_warning(UserWarning): _check_plot_works(df.boxplot, by=['indic', 'indic2']) _check_plot_works(plotting._core.boxplot, data=df['one'], return_type='dict') _check_plot_works(df.boxplot, notch=1, return_type='dict') with tm.assert_produces_warning(UserWarning): _check_plot_works(df.boxplot, by='indic', notch=1)
Example 18
Project: recruit Author: Frank-qlu File: test_boxplot_method.py License: Apache License 2.0 | 6 votes |
def test_boxplot_return_type_legacy(self): # API change in https://github.com/pandas-dev/pandas/pull/7096 import matplotlib as mpl # noqa df = DataFrame(np.random.randn(6, 4), index=list(string.ascii_letters[:6]), columns=['one', 'two', 'three', 'four']) with pytest.raises(ValueError): df.boxplot(return_type='NOTATYPE') result = df.boxplot() self._check_box_return_type(result, 'axes') with tm.assert_produces_warning(False): result = df.boxplot(return_type='dict') self._check_box_return_type(result, 'dict') with tm.assert_produces_warning(False): result = df.boxplot(return_type='axes') self._check_box_return_type(result, 'axes') with tm.assert_produces_warning(False): result = df.boxplot(return_type='both') self._check_box_return_type(result, 'both')
Example 19
Project: indras_net Author: gcallah File: test_api_endpoints.py License: GNU General Public License v3.0 | 5 votes |
def random_name(): return "".join(random.choices(string.ascii_letters, k=random.randrange(1, 10)))
Example 20
Project: cyberdisc-bot Author: CyberDiscovery File: cyber.py License: MIT License | 5 votes |
def generatebase64(seed: int) -> str: random.seed(seed) letters = string.ascii_letters + string.digits + "+/=" return "".join(random.choices(letters, k=20))
Example 21
Project: backtrader-cn Author: pandalibin File: sina.py License: GNU General Public License v3.0 | 5 votes |
def get_random_string(length=8, digits_only=True): """ 获取随机字符串长度 :param length: :param digits_only: :return: """ random_str = "" random_list = string.digits if digits_only else string.ascii_letters + string.digits for i in range(length): random_str += random.choice(random_list) return random_str
Example 22
Project: aegea Author: kislyuk File: iam.py License: Apache License 2.0 | 5 votes |
def generate_password(length=16): while True: password = [random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length)] password.insert(8, "-") if not any(c in string.ascii_uppercase for c in password): continue if not any(c in string.ascii_lowercase for c in password): continue if not any(c in string.digits for c in password): continue return ''.join(password)
Example 23
Project: aegea Author: kislyuk File: cloudinit.py License: Apache License 2.0 | 5 votes |
def upload_bootstrap_asset(cloud_config_data, rootfs_skel_dirs): key_name = "".join(random.choice(string.ascii_letters) for x in range(32)) enc_key = "".join(random.choice(string.ascii_letters) for x in range(32)) logger.info("Uploading bootstrap asset %s to S3", key_name) bucket = ensure_s3_bucket() cipher = subprocess.Popen(["openssl", "aes-256-cbc", "-e", "-k", enc_key], stdin=subprocess.PIPE, stdout=subprocess.PIPE) encrypted_tarfile = cipher.communicate(get_bootstrap_files(rootfs_skel_dirs, dest="tarfile"))[0] bucket.upload_fileobj(io.BytesIO(encrypted_tarfile), key_name) url = clients.s3.generate_presigned_url(ClientMethod='get_object', Params=dict(Bucket=bucket.name, Key=key_name)) cmd = "curl -s '{url}' | openssl aes-256-cbc -d -k {key} | tar -xz --no-same-owner -C /" cloud_config_data["runcmd"].insert(0, cmd.format(url=url, key=enc_key)) del cloud_config_data["write_files"]
Example 24
Project: wechatpy Author: wechatpy File: utils.py License: MIT License | 5 votes |
def random_string(length=16): rule = string.ascii_letters + string.digits rand_list = random.sample(rule, length) return "".join(rand_list)
Example 25
Project: fishroom Author: tuna File: api_client.py License: GNU General Public License v3.0 | 5 votes |
def token_key_gen(N): return ''.join( random.choice(string.ascii_letters + string.digits) for _ in range(N) )
Example 26
Project: Arya Author: HarmJ0y File: arya.py License: GNU General Public License v3.0 | 5 votes |
def b64sub(s, key): """ "Encryption" method that base64 encodes a given string, then does a randomized alphabetic letter substitution. """ enc_tbl = string.maketrans(string.ascii_letters, key) return string.translate(base64.b64encode(s), enc_tbl)
Example 27
Project: Arya Author: HarmJ0y File: arya.py License: GNU General Public License v3.0 | 5 votes |
def randomString(length=-1): """ Returns a random string of "length" characters. If no length is specified, resulting string is in between 6 and 15 characters. """ if length == -1: length = random.randrange(6,16) random_string = ''.join(random.choice(string.ascii_letters) for x in range(length)) return random_string
Example 28
Project: wuy Author: manatlan File: dlyt.py License: GNU General Public License v2.0 | 5 votes |
def removeDisallowedFilenameChars(filename): VALID = "-_.() %s%s" % (string.ascii_letters, string.digits) cleanedFilename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore') return ''.join(chr(c) for c in cleanedFilename if chr(c) in VALID)
Example 29
Project: torch-toolbox Author: PistonY File: functional.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def text_overlay(img, length, font, text_scale): assert _is_numpy_image(img) and img.dtype == np.uint8 h, w, c = img.shape length = np.random.randint(*length) text_scale = np.random.uniform(*text_scale) text = ''.join(random.choice(ascii_letters) for _ in range(length)) color = np.random.randint(0, 255, c).tolist() pos = (random.randint(0, w), random.randint(0, h)) img = cv2.putText(img, text, pos, font, text_scale, color) return img
Example 30
Project: TaskBot Author: EvilPsyCHo File: WXBizMsgCrypt_py3.py License: GNU General Public License v3.0 | 5 votes |
def get_random_str(self): """ 随机生成16位字符串 @return: 16位字符串 """ rule = string.ascii_letters + string.digits str = random.sample(rule, 16) return "".join(str).encode()