Skip to content
g21589 edited this page Jun 14, 2025 · 18 revisions

MinIO

from minio import Minio
from minio.error import S3Error


def list_objects_with_prefix_and_size(bucket_name, prefix, minio_client):
    try:
        objects = minio_client.list_objects(
            bucket_name, 
            prefix=prefix, 
            recursive=True, 
            extra_headers={'x-minio-extract': 'true'}
        )
        for obj in objects:
            print(f"File: {obj.object_name}, Size: {obj.size} bytes")
    except S3Error as err:
        print(f"Error listing objects: {err}")

def download_stream(bucket_name, object_name, minio_client):
    resp = minio_client.get_object(
        bucket_name, 
        object_name,
        request_headers={'x-minio-extract': 'true'}
    )
    with resp:
        for chunk in resp.stream(32*1024):
            print(chunk)

def download_stream2(bucket_name, object_name, minio_client):
    resp = minio_client.get_object(
        bucket_name, 
        object_name,
        request_headers={'x-minio-extract': 'true'}
    )
    #return pd.read_parquet(resp)
    return pl.read_parquet(resp)

minio_client = Minio(
    endpoint='127.0.0.1:9000',
    access_key='XXX',
    secret_key='XXX',
    secure=False
)
bucket_name = "data"
prefix = "AAA/data2.zip/"

list_objects_with_prefix_and_size(bucket_name, prefix, minio_client)

download_stream(bucket_name, "AAA/data2.zip/XXX.png", minio_client)
#download_stream(bucket_name, "AAA/data2.zip", minio_client)

fs = pa.fs.S3FileSystem(
    access_key="XXX",
    secret_key="XXX",
    endpoint_override="http://127.0.0.1:9000"
)

with fs.open_output_stream('data/AAA/data3.zip', compression='gzip', buffer_size=None) as s:
    s.write(b'data')

Polars + S3

from io import BytesIO
import os
import s3fs
import numpy as np
import pandas as pd
import polars as pl
import pyarrow.dataset as ds
from pyarrow import fs


df = pl.read_parquet('./data/yellow_tripdata_2024-01.parquet')

def read_func(x):
    b_data = None
    with open('./data/yellow_tripdata_2024-02.parquet', 'rb') as f:
        b_data = f.read()
    return pl.DataFrame({'A': [b_data]})

c = df.group_by('VendorID').map_groups(read_func)
c.write_parquet('./data/AA.parquet', use_pyarrow=True)

r_df = pl.read_parquet('./data/AA.parquet')
f_df = pd.read_parquet(BytesIO(r_df[0, 'A']))

#####

storage_options = {
    "key": "",
    "secret": "",
    "client_kwargs": {
        "endpoint_url": "http://127.0.0.1:9000"
    }
}

storage_options2 = {
    "access_key_id": "",
    "secret_access_key": "",
    "endpoint_url": "http://127.0.0.1:9000"
}

source = "s3://data/tripdata/*.parquet"

# fs = fs.S3FileSystem(endpoint_override=storage_options['client_kwargs']['endpoint_url'].replace("http://", "")), 
#                      access_key=storage_options['key'], 
#                      secret_key=storage_options['secret'])
# fs = s3fs.S3FileSystem(endpoint_url=storage_options['client_kwargs']['endpoint_url'], 
#                        key=storage_options['key'], 
#                        secret=storage_options['secret'])

# dset = ds.dataset("s3://data/tripdata/yellow_tripdata_2024-01.parquet", format="parquet", filesystem=fs)
# df = (
#     pl.scan_pyarrow_dataset(dset)
#         .collect()
# )

df = (
    pl.scan_parquet(source, storage_options=storage_options2)
        .select(['VendorID', 'store_and_fwd_flag', 'tip_amount'])
        .filter(pl.col('store_and_fwd_flag') == 'N')
        .group_by(['VendorID'])
        .quantile(0.5)
        .collect()
)

# (
#     pl.scan_parquet('./data/2019-Nov.parquet')  
#         .collect(streaming=True)
#         .write_parquet(
#             './data/pq',
#             partition_by=["brand"]
#             #use_pyarrow=True,
#             #pyarrow_options={"partition_cols": ["brand"]},
#         )
# )

# p_mean = (
#     df.select(['brand', 'price'])
#         .group_by(["brand"])
#         .quantile(0.5)
#         .collect()
# )

# sum_df = p_mean.to_pandas()

Logging

https://docs.python.org/3/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes

Pandas

https://medium.com/bigdatarepublic/advanced-pandas-optimize-speed-and-memory-a654b53be6c2

Async I/O

import asyncio, nest_asyncio
nest_asyncio.apply() # Fix asyncio bug in IPython (RuntimeError: This event loop is already running)

async def example1(): # 定義一個中間會被中斷的協程
    print("Start example1 coroutin.")
    await asyncio.sleep(1) # 中斷協程一秒
    print("Finish example1 coroutin.")

async def example2(): # 定義一個協程
    print("Start example2 coroutin.")
    # do some process...
    print("Finish example2 coroutin.")

tasks = [
    asyncio.ensure_future(example1()),
    asyncio.ensure_future(example2()),
]
    
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))

Plotly

https://pypi.org/project/kaleido/#files

SQLAlchemy

FastAPI-with-SqlAlchemy

Kaleido

void OnHeadlessBrowserStarted(headless::HeadlessBrowser* browser)

Time: 26.1649 sec Time: 31.2114 sec

Time: 3.2116 sec Time: 8.1961 sec

Time: 0.412 sec

Clone this wiki locally