Outils pour utilisateurs

Outils du site


blog

Notes Python DB - ORM - DAL

Générique

Voir module :

  • SQLAlchemy Core
  • easy_db

Voir : urllib.parse

TinyDB

Une base de donnée native Python avec enregistrement dans fichier JSON (Ou Yaml en custom-storage)

Voir : https://www.docstring.fr/blog/tinydb-une-base-de-donnees-adaptee-vos-projets/

ORM

  • SQLAlchemy ORM
  • SQLObject
  • Pony
  • Peewee
  • mincePy (data mapper pattern designed specifically for computational and data science)
  • MasoniteORM

Database Abstraction Layer (DAL)

pyDAL
2025/03/24 15:06

Notes Python DB - ORM - DAL - SqlAlchemy

Voir Notes Python DB - ORM - DAL

Core & ORM :

Voir ORM :

Lib :

RestApi pour DB SqlAlchemy :

Notes SQLAlchemy Core

#import urllib.parse
import sqlalchemy
from sqlalchemy import create_engine, text
 
engine = create_engine('sqlite:////home/jean/tmp/test-sqlite.db')
 
# Exemple de SQL
sql = text('SELECT * FROM contacts;')
 
with engine.connect() as con:
	result = con.execute(sql)
 
print(result.all())
result.close()
 
 
# Exemple de code SQL
conn = engine.connect()
result = conn.execute(text("SELECT * FROM contacts"))
for row in result:
	print(row)
 
# Exemple de Select
from sqlalchemy import select
stmt = select(User).where(User.name == "spongebob")
 
 
# Introspection import Table
metadata=MetaData()
with engine.connect() as conn:
    table_contacts_reflected==Table("contacts", metadata, autoload_with=conn)
 
print(table_contacts.c)
print(table_contacts.primary_key)
 
 
# Champs descriptions
conn = engine.connect()
result = conn.execute(text("SELECT * FROM contacts"))
cursor=result.cursor
print(';'.join([ x[0] for x in cursor.description]))

Autres

Dataset

Voir :

Dataset: databases for lazy people

import dataset
 
db = dataset.connect('sqlite:///:memory:')
 
table = db['sometable']
table.insert(dict(name='John Doe', age=37))
table.insert(dict(name='Jane Doe', age=34, gender='female'))
 
john = table.find_one(name='John Doe')
2025/03/24 15:06

Notes Python config

Source : https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/9/html/9.4_release_notes/new-features#new-features-kernel

A new environment variable in Python to control parsing of email addresses

To mitigate CVE-2023-27043, a backward incompatible change to ensure stricter parsing of email addresses was introduced in Python 3.

This update introduces a new PYTHON_EMAIL_DISABLE_STRICT_ADDR_PARSING environment variable. When you set this variable to true, the previous, less strict parsing behavior is the default for the entire system:

export PYTHON_EMAIL_DISABLE_STRICT_ADDR_PARSING=true

However, individual calls to the affected functions can still enable stricter behavior.

You can achieve the same result by creating the /etc/python/email.cfg configuration file with the following content:

/etc/python/email.cfg

[email_addr_parsing]
PYTHON_EMAIL_DISABLE_STRICT_ADDR_PARSING = true

For more information, see the Knowledgebase article Mitigation of CVE-2023-27043 introducing stricter parsing of email addresses in Python.

2025/03/24 15:06

Notes Python - les objects - Class

Exemples

class Geeks: 
     def __init__(self): 
          self._age = 0
 
     # using property decorator 
     # a getter function 
     @property
     def age(self): 
         print("getter method called") 
         return self._age 
 
     # a setter function 
     @age.setter 
     def age(self, a): 
         if(a < 18): 
            raise ValueError("Sorry you age is below eligibility criteria") 
         print("setter method called") 
         self._age = a 
 
mark = Geeks() 
 
mark.age = 19
 
print(mark.age)

Source : https://www.geeksforgeeks.org/getter-and-setter-in-python/

2025/03/24 15:06

Notes Python - date - datetime

AM/PM

AM ante meridiem
PM post meridiem
import datetime
#from datetime import datetime
format_date='%Y-%m-%d %I:%M %p'
 
date1=datetime.datetime(2023, 9, 25, 11, 59, 0, 0)
date2=datetime.datetime(2023, 9, 25, 12, 0, 0, 0)
date3=datetime.datetime(2023, 9, 25, 12, 1, 0, 0)
In [32]: datetime.datetime.strftime(date1, format_date)
Out[32]: '2023-09-25 11:59 AM'

In [33]: datetime.datetime.strftime(date2, format_date)
Out[33]: '2023-09-25 12:00 PM'

In [34]: datetime.datetime.strftime(date3, format_date)
Out[34]: '2023-09-25 12:01 PM'

TimeZone (TZ)

datetime.datetime(2023, 9, 25, 10, 0, 34, 441838, tzinfo=<UTC>)
import datetime
from dateutil import tz
 
TZ_PARIS=tz.gettz('Europe/Paris')
TZ_UTC=tz.gettz('UTC')
 
d_utc=datetime.datetime(2023, 10, 3, 1, 1, 1, 114228, tzinfo=TZ_UTC)
d_paris=datetime.datetime(2023, 10, 3, 1, 1, 1, 114228, tzinfo=TZ_PARIS)
In [4]: d_utc.isoformat(timespec='minutes')
Out[4]: '2023-10-03T01:01+00:00'

In [5]: d_paris.isoformat(timespec='minutes')
Out[5]: '2023-10-03T01:01+02:00'

Epoch time

def get_epoch_ms():
    return int(time.time() * 1000.0)

Temps

Mesure du temps d'exécution

Exemple 1

print(f"started at {time.strftime('%X')}")
plop()
print(f"finished at {time.strftime('%X')}")

Exemple 2

start = time.time()
asyncio.run(main())
end = time.time() - start
print('Total time: %.2f' % end)
2025/03/24 15:06
blog.txt · Dernière modification : de 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki