CemirUtils Class and Functions Documentation
cemirutils
is a Python utility library designed to provide a range of commonly used functions, methods, libraries, and decorators to streamline development in Linux and Python environments.
Requirements
Installation
pip install -U cemirutils
Authors
- Cem Emir Yüksektepe (@gmail.com) https://cem.pw
- Muslu Yüksektepe (@gmail.com) https://muslu.org
- Hasan Yüksektepe (@gmail.com) https://hayatikodla.net
For more information, visit the cemirutils PyPI page.
Classes and Functions
1. CemirUtilsLoopTimer
- Methods:
loop
: Decorator to measure loop execution time.check_loop
: Context manager for loop timing.
2. CemirUtilsConditions
- Methods:
condition_collector
: Decorator to log the lines and conditions met during function execution.
3. CemirUtilsFunctionNotification
- Methods:
notify
: Sends an email notification after the function execution.
4. CemirUtilsHTTP
- Methods:
get_methods
: Returns available HTTP methods.get
: Executes a GET request.post
: Executes a POST request.put
: Executes a PUT request.delete
: Executes a DELETE request.patch
: Executes a PATCH request.
5. CemirUtilsDecorators
- Methods:
timeit
: Measures execution time.log
: Logs function calls and results.retry
: Retries a function upon failure.cache
: Caches function results.cache_with_expiry
: Caches results with an expiry time.deprecate
: Marks a function as deprecated.debug
: Logs detailed function calls.before_after
: Executes actions before and after function calls.rate_limit
: Limits function calls over a period.webhook_request
: Sends a webhook request on function call.
6. CemirUtilsEmail
- Methods:
send_email
: Sends an email with optional attachments.
7. IPGeolocation
- Methods:
create_sqlite_db
: Creates SQLite DB from CSV.get_ip_location
: Retrieves IP location data.
8. CemirPostgreSQL
- Methods:
psql_create_table
: Creates a PostgreSQL table.psql_insert
: Inserts data into a table.insert
: Inserts data.read
: Reads data from a table.update
: Updates table data.delete
: Deletes data from a table.
9. CemirUtils
This documentation provides an overview of the CemirUtils
classes and their respective functions, offering a range of utilities for file operations, HTTP requests, email handling, PostgreSQL operations, and more.
CemirUtils Class and Functions Documentation
colorize print
from cemirutils import cprint
data = {
"name": "John",
"age": 30,
"is_student": False,
"languages": ["Python", "JavaScript"],
"grades": {
"math": 90,
"science": 85
}
}
cprint(data)
cprint(1)
cprint("@#₺")
cprint(1.12)
cprint([1,2,"asd"])
cRange
Returns a list containing specified individual numbers and ranges.
from cemirutils import crange
for i in crange(1, '99-105', 'c,e,m,i,r'):
print(i)
CemirUtilsLoopTimer
from cemirutils import crange
for i in crange(1, '99-100', 242, '1001-1250', '3401-3430', 3441, '3600-3601', '3611-3616', '3621-3626'):
print(i)
import time
from cemirutils import CemirUtilsLoopTimer
timer = CemirUtilsLoopTimer()
@timer.loop
def example_function():
with timer.check_loop():
for _ in range(10):
time.sleep(0.1)
with timer.check_loop():
count = 0
while count < 3:
count += 1
time.sleep(count)
with timer.check_loop():
for _ in range(5):
time.sleep(0.1)
example_function()
CemirUtilsConditions
from cemirutils import CemirUtilsConditions
cemir_utils = CemirUtilsConditions()
@cemir_utils.condition_collector
def test_function(x, y, z):
if x > 15:
pass
elif x < 15 and y > 10:
pass
else:
pass
if y == 20:
pass
elif y >= 15:
pass
else:
pass
if z == "hello":
pass
elif z == "world":
pass
else:
pass
if x == 10:
pass
elif x >= 10:
pass
else:
pass
if y % 2 == 0:
pass
else:
pass
if z.startswith("hq"):
pass
elif z.startswith("w"):
pass
else:
pass
test_function(10, 20, "hello")
CemirUtilsFunctionNotification
from cemirutils import CemirUtilsFunctionNotification
utils = CemirUtilsFunctionNotification(
smtp_server="mail.makdos.com",
smtp_port=587,
smtp_user="notify@makdos.com",
smtp_password="nope"
)
@utils.notify(to_email="musluyuksektepe@gmail.com", subject="Function Called")
def important_action():
return {"status": "Important action completed."}
important_action()
CemirUtilsHTTP
from cemirutils import CemirUtilsHTTP
http = CemirUtilsHTTP()
print(http.get_methods())
get_response = http.get("https://jsonplaceholder.typicode.com/posts/1", verify_ssl=True)
print("GET Response:", get_response)
post_data = {"title": "foo", "body": "bar", "userId": 1}
post_response = http.post("https://jsonplaceholder.typicode.com/posts", data=post_data, verify_ssl=True)
print("POST Response:", post_response)
put_data = {"title": "foo", "body": "bar", "userId": 1}
put_response = http.put("https://jsonplaceholder.typicode.com/posts/1", data=put_data, verify_ssl=True)
print("PUT Response:", put_response)
delete_response = http.delete("https://jsonplaceholder.typicode.com/posts/1", verify_ssl=True)
print("DELETE Response:", delete_response)
patch_data = {"title": "foo"}
patch_response = http.patch("https://jsonplaceholder.typicode.com/posts/1", data=patch_data, verify_ssl=True)
print("PATCH Response:", patch_response)
CemirUtilsDecorators
import time
from datetime import datetime
from cemirutils import CemirUtilsDecorators
@CemirUtilsDecorators.timeit
@CemirUtilsDecorators.log
def timeit_log(x, y):
time.sleep(1)
return x + y
timeit_log(3, 5)
@CemirUtilsDecorators.retry(retries=5, delay=2)
def may_fail_function():
if time.time() % 2 < 1:
raise ValueError("Random failure!")
return "Success"
may_fail_function()
@CemirUtilsDecorators.cache
def slow_function(x):
time.sleep(2)
return x * x
print(slow_function(4))
print(slow_function(4))
@CemirUtilsDecorators.cache_with_expiry(expiry_time=5)
def cached_function(x):
time.sleep(3)
return x * x
print(datetime.now(), cached_function(4))
time.sleep(1)
print(datetime.now(), cached_function(4))
@CemirUtilsDecorators.deprecate("Please use new_function instead.")
def old_function(x, y):
return x + y
old_function(3, 5)
@CemirUtilsDecorators.debug
def add_numbers(a, b):
return a + b
add_numbers(3, 5)
@CemirUtilsDecorators.before_after
def test_beforeafter(data):
print(f"1 Performing database operation with data: {data}")
return "2 Success"
print(test_beforeafter("Muslu Y."))
@CemirUtilsDecorators.rate_limit(max_calls=5, period=10)
def limited_function():
return {"status": "ok"}
try:
print(datetime.now(), limited_function())
print(datetime.now(), limited_function())
print(datetime.now(), limited_function())
time.sleep(4)
print(datetime.now(), limited_function())
print(datetime.now(), limited_function())
print(datetime.now(), limited_function())
print(datetime.now(), limited_function())
except RuntimeError as e:
print(e)
utils = CemirUtilsDecorators()
@utils.webhook_request(url="https://jsonplaceholder.typicode.com/posts", headers={"x-sent-by": "CemirUtils", "user-agent": "CemirUtils"})
def send_webhook():
return {'message': 'Webhook request'}
print(send_webhook())
@CemirUtilsDecorators.webhook_request(url="https://jsonplaceholder.typicode.com/posts", headers={"x-sent-by": "CemirUtils", "user-agent": "CemirUtils"})
def send_webhook():
return {'message': 'Webhook request'}
print(send_webhook())
CemirUtilsEmail
from cemirutils import CemirUtilsEmail
email_util = CemirUtilsEmail(
smtp_host="smtp.gmail.com",
smtp_port=465,
smtp_user="musluyuksektepe@gmail.com",
smtp_pass="nopass",
smtp_ssl=True
)
email_util.send_email(
to_email="cememir2017@gmail.com",
subject="Test Subject",
body_html="<html><body><h1>This is a test email in HTML.</h1></body></html>",
attachments=["2024.pdf", "not_found.log"],
zip_files=False
)
IPGeolocation
from cemirutils import IPGeolocation
ip_geolocator = IPGeolocation()
ip_address = "121.0.11.0"
location_info = ip_geolocator.get_ip_location(ip_address, force_download=False)
print(location_info)
CemirPostgreSQL
from datetime import datetime
from cemirutils import CemirPostgreSQL
utils = CemirPostgreSQL(dbname='test_db3', dbhost='127.0.0.1', dbuser='postgres', dbpassword='', dbport=5435, dbcreate_db_if_not_exists=True)
print(utils.insert('test_table_json', ('id', 'dates', 'content'), (2, datetime.now(), {"age": 40, "city": "İzmir"}), get_id=True))
print(utils.read('test_table_json'))
print(utils.update('test_table_json', {'dates': datetime.now(), 'content': '{"age": 40, "city": "Sivas"}'}, 'id = 1', get_id=True))
print(utils.read('test_table_json'))
asd = utils.read(table_name='test_table_json', columns="content", condition="content ->> 'age' = '40'")
print(type(asd), asd)
print(utils.delete('test_table_json', 'id = 1'))
print(utils.read('test_table_json'))
File Operations
from cemirutils import CemirUtils
utils = CemirUtils()
files = utils.linux_ls(path=".")
print(files)
utils.linux_touch(file_name="new_file.txt")
utils.linux_gzip(file_name="file.txt")
content = utils.linux_cat(file_name="file.txt")
print(content)
utils.linux_cp(src="file.txt", dest="copy_file.txt")
utils.linux_mv(src="file.txt", dest="moved_file.txt")
utils.linux_rm(file_name="file.txt")
utils.linux_mkdir(dir_name="new_dir")
utils.linux_rmdir(dir_name="new_dir")
utils.linux_cut(file_name="file.txt", delimiter=" ", fields=[1, 2])
utils.linux_find(path=".", name="*.txt")
utils.linux_grep(file_name="file.txt", pattern="search_text")
List Operations
from cemirutils import CemirUtils
data_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
cem = CemirUtils(data_list)
print(data_list)
print(cem.list_head(2))
print(cem.list_tail(4))
print(cem.list_main())
print(cem.list_unique_values())
print(cem.list_sort_asc())
print(cem.list_sort_desc())
print(cem.list_filter_greater_than(5))
print(cem.list_filter_less_than(4))
print(cem.list_sum_values())
print(cem.list_average())
Dictionary Operations
data = [{'a': 1}, {'b': 2}, {'a': 3}, {"name": "sivas", "age": 10}]
cemd = CemirUtils(data)
print(cemd.dict_get_keys())
print(cemd.dict_filter_by_key('name'))
print(cemd.dict_merge({'a': 1}, {'b': 2}))
Time Operations
from cemirutils import CemirUtils
utils = CemirUtils(None)
print(utils.time_days_between_dates("2024-05-01", "2024-05-25"))
print(utils.time_hours_minutes_seconds_between_times("08:30:00", "15:45:30"))
print(utils.time_until_date("2024-05-27 23:59:59"))
print(utils.time_add_days_and_format("2024-05-01", 30))
print(utils.time_is_weekend("2024-05-25"))
print(utils.time_is_leap_year(2024))
print(utils.time_days_in_month(2024, 2))
print(utils.time_next_weekday("2024-05-25", 0))
print(utils.time_since("2022-01-01 00:00:00"))
print(utils.time_business_days_between_dates("2024-05-01", "2024-05-25"))
This markdown provides comprehensive examples of using all functions and decorators in the CemirUtils
library. Each function is shown with a clear, working example to illustrate its usage.