cardinal_pythonlib.randomness¶
Original code copyright (C) 2009-2022 Rudolf Cardinal (rudolf@pobox.com).
This file is part of cardinal_pythonlib.
Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Random number generation.
-
cardinal_pythonlib.randomness.
coin
(p: float) → bool[source]¶ Flips a biased coin; returns
True
orFalse
, with the specified probability being that ofTrue
.
-
cardinal_pythonlib.randomness.
create_base64encoded_randomness
(num_bytes: int) → str[source]¶ Create and return
num_bytes
of random data.The result is encoded in a string with URL-safe
base64
encoding.Used (for example) to generate session tokens.
Which generator to use? See https://cryptography.io/en/latest/random-numbers/.
Do NOT use these methods:
randbytes = M2Crypto.m2.rand_bytes(num_bytes) # NO! randbytes = Crypto.Random.get_random_bytes(num_bytes) # NO!
Instead, do this:
randbytes = os.urandom(num_bytes) # YES
-
cardinal_pythonlib.randomness.
generate_random_string
(length: int, characters: str = None) → str[source]¶ Generates a random string of the specified length.
-
cardinal_pythonlib.randomness.
random_random
()¶ random() -> x in the interval [0, 1).