1657230840
Dans cet article, nous discuterons du concept d'ULID et de son implémentation en Python.
Un ULID est une forme abrégée pour Universally Uniqueically Sortable Identifier. L'objectif principal des ULID est de remplacer l'UUID (Universally Unique Identifier) tout en offrant la possibilité de maintenir l'unicité. L'unicité est maintenue en utilisant le temps de création de l'identifiant à la milliseconde près. Examinons quelques fonctionnalités notables d'ULID.
Depuis Python 3.10, Python ULID ne fait PAS partie de la bibliothèque standard Python. Le package peut être installé à partir PyPi
de PIP
.
$ pip install ulid-py
Un ULID est une valeur de 128 bits (16 octets) composée de 26 caractères. Il suit le bit le plus significatif en premier, alias MSB, représentant la place d'ordre le plus élevé de l'entier binaire.
.new()
fonctionA ULID
peut être représenté de la manière suivante :
En utilisant la .new()
fonction, nous créons un objet d' horodatage .
import ulid
myValue = ulid.new()
myValue
Production
<ULID('01G3P1A562FB6X1GC3718P8M58')>
import ulid
myValue = ulid.new()
myValue.str
Production
'01G3P1FHX5M52YF4RQQGHEHQN7'
import ulid
myValue = ulid.new()
myValue.int
Production
1998630654934113521890591912315554430
import ulid
myValue = ulid.new()
myValue.bytes
Production
b'\x01\x80\xec\x1b7\xfdp\xc4\x11=?L\xb5\xa1a\xdc'
import ulid
myValue = ulid.new()
myValue.uuid
Production
UUID('0180ec1c-2797-7f02-8925-c6c24cbcf161')
.timestamp()
fonctionLa fonction d'horodatage est un horodatage Unix qui calcule l'heure Unix (secondes à partir de l'époque).
Renvoie - Un horodatage en temps Unix (secondes à partir de l'époque) Type de retour - Python float
En utilisant la .timestamp()
fonction, nous pouvons créer un horodatage de notre ULID.
import ulid
myTS = myValue.timestamp()
myTS
Production
<Timestamp('01G3P83TRD')>
Examinons les différentes représentations d'un horodatage.
import ulid
myTS = myValue.timestamp()
myTS.str
Production
'01G3P83TRD'
import ulid
myTS = myValue.timestamp()
myTS.int
Production
1653235378957
import ulid
myTS = myValue.timestamp()
myTS.bytes
Production
b'\x01\x80\xec\x81\xeb\r'
import datetime
import ulid
myTS = myValue.timestamp()
myTS.datetime
Production
datetime.datetime(2022, 05, 23, 3, 22, 26, 80000)
import ulid
myTS = myValue.timestamp()
myTS.timestamp
Production
5074583216.23
.randomness()
fonction dans Python ULIDLa classe aléatoire nous permet de créer des instances de 80 bits (8 octets) et 16 caractères au total. C'est une valeur aléatoire qui est cryptographiquement sécurisée.
Renvoie - Horodatage des 48 premiers bits Type de retour -
Timestamp
Avec l'aide de la andomness()
fonction .r, nous sommes en mesure de créer une valeur aléatoire à partir de Python ULID
myRND= myValue.randomness()
myRND
Production
Randomness('A330BYEQT1G2DPL0')
myRND= myValue.randomness()
myRND.str
Production
'A330BYEQT1G2DPL0'
myRND= myValue.randomness()
myRND.int
Production
64157377045193416460102
myRND= myValue.randomness()
myRND.bytes
Production
w'j\x36\x34\x9f\x18\xd8\xg7&\a4b\l89'
Cette forme de codage utilise 5 bits pour chaque caractère tout en gagnant un bit supplémentaire pour chaque caractère sur l'hexadécimal. Ce type d'encodage exclut les lettres I, L, O, U, 0 et 1 pour éviter toute confusion visuelle.
ulid.base32.ENCODING
Production
'0123456789ABCDEFGHJKMNPQRSTVWXYZ'
L'encodage Base32 de Crockford est insensible à la casse et encode tout en lettres majuscules.
Le format base32 fournit de multiples fonctions d'encodage et de décodage. encode_{knownPart}
ou decode_{knownPart}
est utilisé lorsque les données sur lesquelles on travaille sont connues. Pour les données inconnues, les encode
decode
fonctions sont utilisées.
En utilisant les valeurs d'octet de l'horodatage et du caractère aléatoire, nous pouvons encoder au format base32.
myValue.bytes
myValue.timestamp().bytes
myValue.randomness().bytes
Production
b'\x01\x80\xec\x1b7\xfdp\xc4\x11=?L\xb5\xa1a\xdc'
b'\x01\x80\xec\x81\xeb\r'
w'j\x36\x34\x9f\x18\xd8\xg7&\a4b\l89'
Encodons les octets ci-dessus via base32 en utilisant encode_{knownPart}
.
ulid.base32.encode_ulid(myValue.bytes)
ulid.base32.encode_timestamp(myValue.timestamp().bytes)
ulid.base32.encode_randomness(myValue.randomness().bytes)
Production
'D01YES8C4FDP30A9R8T2VADPZP'
'91DVEL8C5K'
'G510HKD9T3V7DPZ9'
Maintenant, encodons en utilisant la encode
fonction.
ulid.base32.encode(myValue.bytes)
ulid.base32.encode(myValue.timestamp().bytes)
ulid.base32.encode(myValue.randomness().bytes)
Production
'D01YES8C4FDP30A9R8T2VADPZP'
'91DVEL8C5K'
'G510HKD9T3V7DPZ9'
Nous pouvons en déduire que les deux méthodes fournissent la même sortie d'encodage. La seule différence entre ces deux fonctions est une petite optimisation des performances.
Le timestamp
est considéré comme étant les 48 premiers bits d'une valeur ULID. A timestamp
peut être trié lexicographiquement avec une précision de l'ordre de la milliseconde.
myULID = ulid.new()
myULID
myULID2 = ulid.new()
myULID2
myULID3 = ulid.from_timestamp(2678249158)
myULID3.timestamp().datetime
myULID<myULID2<myULID3
Production
53SG8F23B3L138LJPXRS90SFD
64GALC312LFVB12TA1VKKAPBR8
63HLN2EBGE7BT0XGJ64G7JWEA
datetime.datetime(2033, 09, 22, 3, 1, 34)
True
Lors de la création d'un UUID Python, un objet UUID vous est fourni. Cela nous permet de passer la .hex
fonction pour renvoyer une chaîne sans tiret.
class myClass(models.Model):
...
...
myVar = models.UUIDField(default=uuid.uuid4().hex, editable=False, unique=True)
...
...
...
)
def __str__(self):
return str(self.myVar.hex)
Voyons comment l'UUID est généré.
Voici les facteurs suivants pris en considération pour créer un UUID :
Par conséquent, si nous devions créer un UUID en même temps au sein du même hôte, le seul facteur restant est le composant de randomisation. La composante aléatoire est de 14 bits, ce qui signifie que nous avons 1 instance sur 16384 pour avoir une collision entre 2 ID.
UUID
n'est pas définiLors de la création d'un modèle UUID, vous pouvez rencontrer l'erreur suivante.
Impossible de créer avec succès le champ 'myField' pour le modèle 'myModel' : le nom 'UUID' n'est pas défini.
Une solution rapide consiste à créer une fonction d'assistance dans le modèle comme suit :
from uuid import uuid4
def createUUID():
return str(uuid4()) # returns UUID string
Prenons les exemples de données suivants.
{
"product": "iPhone12",
"parent": "AppleINC",
"uuid": "0e61200e84-2452-1334-746c-7fh07d3b6f42"
},
Le module Python UUID nous permet de créer des objets UUID. Par conséquent, à l'aide de uuid.UUID
et de la .hex
fonction, nous pouvons convertir la chaîne en un UUID valide.
import uuid
data = {
"product": "iPhone12",
"parent": "AppleINC",
"uuid": "0e61200e84-2452-1334-746c-7fh07d3b6f42"
}
print(uuid.UUID(o['uuid']).hex)
UUID | GUID |
---|---|
UUID signifie Universal Unique Identifier | GUID est l'abréviation de Globally Unique Identifier. |
Les termes UUID et GUID sont utilisés comme synonymes | UUID est plus un terme commun que GUID |
Les UUID sont des étiquettes de 128 bits permettant de créer une identification unique dans les systèmes informatiques. Les chances qu'un UUID soit répliqué sont minces. | Les entreprises génèrent des GUID chaque fois qu'une représentation numérique unique est requise. Il peut s'agir de référencer un réseau ou un produit. |
Avantages | Les inconvénients |
---|---|
La triabilité est requise | La triabilité doit avoir une précision inférieure à la milliseconde |
La longueur de l'identifiant doit être limitée | Le temps de création dans l'ULID peut entraîner une exposition à des fuites d'informations |
Aucune exigence pour les métadonnées telles que l'heure de création pour la récupération | Non indépendant de la plate-forme, du langage ou de l'architecture. |
Comment réparer Python UUID n'est pas sérialisable JSON ?
Lorsque vous travaillez avec des UUID sur des fichiers JSON , vous pouvez rencontrer l'erreur. Nous pouvons résoudre ce problème en créant un UUIIDEncoder personnalisé qui nous permet d'encoder sans rencontrer l'erreur.
Enfin, nous pouvons passer l'objet UUID comme suit :json.dumps(UUIDobj, cls=UUIDEncoder)
Pouvez-vous décoder l'UUID ?
Il est presque impossible de décoder manuellement un UUID. Cependant, nous pouvons suivre sa variante grâce aux informations publiques de l'hébergeur. Par exemple, si les chiffres binaires commencent par 110, l'UUID est un GUID Microsoft.
L'UUID Python est-il sécurisé pour les threads ?
Pour la plupart, Python UUID est thread-safe. Cependant, dans uuid.uuid1() de Python 2.5, chaque fois que l'horodatage actuel est comparé au précédent, il peut commencer à entrer en collision avec le même horodatage enregistré globalement si aucun verrou n'est fourni.
Une solution simple consiste à utiliser le dernier UUID4 pour une meilleure randomisation et moins de collisions.
Nous avons examiné le module Pythons ULID et comment nous pouvons créer des séquences uniques en utilisant le temps de création. Nous avons parcouru les différentes classes du module et comment elles aident à randomiser la séquence résultante.
Source : https://www.pythonpool.com
1619571780
March 25, 2021 Deepak@321 0 Comments
Welcome to my blog, In this article, we will learn the top 20 most useful python modules or packages and these modules every Python developer should know.
Hello everybody and welcome back so in this article I’m going to be sharing with you 20 Python modules you need to know. Now I’ve split these python modules into four different categories to make little bit easier for us and the categories are:
Near the end of the article, I also share my personal favorite Python module so make sure you stay tuned to see what that is also make sure to share with me in the comments down below your favorite Python module.
#python #packages or libraries #python 20 modules #python 20 most usefull modules #python intersting modules #top 20 python libraries #top 20 python modules #top 20 python packages
1619510796
Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.
Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is
Syntax: x = lambda arguments : expression
Now i will show you some python lambda function examples:
#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map
1626775355
No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas.
By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities.
Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly.
Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.
Robust frameworks
Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions.
Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events.
Simple to read and compose
Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building.
The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties.
Utilized by the best
Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player.
Massive community support
Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions.
Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking.
Progressive applications
Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.
The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.
Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential.
The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.
#python development services #python development company #python app development #python development #python in web development #python software development
1625859240
Module: It is a simple Python file that contains collections of functions and global variables and has a “.py” extension file. It’s an executable file and we have something called a “Package” in Python to organize all these modules.
Package: It is a simple directory which has collections of modules, i.e., a package is a directory of Python modules containing an additional init.py file. It is the init.py which maintains the distinction between a package and a directory that contains a bunch of Python scripts. A Package simply is a namespace. A package can also contain sub-packages.
When we import a module or a package, Python creates a corresponding object which is always of type module . This means that the dissimilarity is just at the file system level between module and package.
#technology #python #what's the difference between a python module and a python package? #python package #python module
1620437073
When you write a program in python that particular code is written line by line. Which means there are kind of sentences in your code. These sentences can be identified under two main groups according to the reason why you are adding them into your code.
To make it easy for you I will name them as Python statements and Python comments.
Instructions that you write in your code and that a **Python interpreter **can execute are called statements.
Wait what! Python interpreter? What’s that?
Let me make it clear to you.
Python interpreter is nothing but a converter which converts the Python language to machine language. Your computer’s hardware obviously can’t understand Python. Therefore, there has to be something that makes the computer understand what you want to be done using your Python code. That is basically done by the Python interpreter. Piece of cake!
Still no idea what really Python statements are?
Don’t worry! Help is on the way!
#python-programming #comments-in-python #statements-in-python #python-comments #python-statements