Here's an example that creates a file using pyiceberg and sets up a simple HTTP server to share it:
python
from pyiceberg.catalog import load_catalog
from pyiceberg.schema import Schema
from pyiceberg.types import (
NestedField,
StringType,
IntegerType
)
import http.server
import socketserver
import os
# First, let's create a sample Iceberg table schema and metadata file
def create_iceberg_file():
# Define a simple schema
schema = Schema(
NestedField(1, "id", IntegerType(), required=True),
NestedField(2, "name", StringType(), required=True)
)
# Write schema to a file
with open("sample_metadata.json", "w") as f:
f.write(schema.json())
return "sample_metadata.json"
# Create a custom HTTP request handler
class FileHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
# Set headers for JSON content
if self.path.endswith('.json'):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
return http.server.SimpleHTTPRequestHandler.do_GET(self)
def start_server(port=8000):
# Create the file first
filename = create_iceberg_file()
# Set up the HTTP server
handler = FileHandler
with socketserver.TCPServer(("", port), handler) as httpd:
print(f"Serving at port {port}")
print(f"Access the file at: http://localhost:{port}/{filename}")
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\nShutting down server...")
httpd.shutdown()
if __name__ == "__main__":
start_server()
This code does the following:
Creates a simple Iceberg schema with two fields: an ID (integer) and a name (string)
Writes the schema to a JSON file
Sets up a basic HTTP server to serve the file
Makes the file accessible via HTTP
To use this code:
Save it to a file (e.g., iceberg_server.py)
Run it:
bash
python iceberg_server.py
The server will start and print the URL where you can access the file. You can access the file by opening a web browser and navigating to http://localhost:8000/sample_metadata.json
Here's a more complex version that includes actual table data:
python
from pyiceberg.catalog import load_catalog
from pyiceberg.schema import Schema
from pyiceberg.types import (
NestedField,
StringType,
IntegerType
)
from pyiceberg.table import Table
import json
import http.server
import socketserver
import os
from datetime import datetime
def create_iceberg_files():
# Define schema
schema = Schema(
NestedField(1, "id", IntegerType(), required=True),
NestedField(2, "name", StringType(), required=True),
NestedField(3, "timestamp", StringType(), required=True)
)
# Create sample data
data = {
"format-version": 2,
"table-uuid": "fb072c92-a02b-11e9-ae9c-1bb7bc9eca94",
"location": "sample_table",
"last-updated-ms": int(datetime.now().timestamp() * 1000),
"last-column-id": 3,
"schema": schema.json_dict(),
"current-schema-id": 0,
"schemas": [schema.json_dict()],
"partition-spec": [],
"default-spec-id": 0,
"partition-specs": [],
"last-partition-id": 1000,
"properties": {},
"current-snapshot-id": -1,
"snapshots": [],
"snapshot-log": [],
"metadata-log": []
}
# Write metadata file
with open("metadata.json", "w") as f:
json.dump(data, f, indent=2)
# Create sample data file
sample_records = [
{"id": 1, "name": "Alice", "timestamp": datetime.now().isoformat()},
{"id": 2, "name": "Bob", "timestamp": datetime.now().isoformat()},
{"id": 3, "name": "Charlie", "timestamp": datetime.now().isoformat()}
]
with open("data.json", "w") as f:
json.dump(sample_records, f, indent=2)
return ["metadata.json", "data.json"]
class CORSRequestHandler(http.server.SimpleHTTPRequestHandler):
def end_headers(self):
# Add CORS headers
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET')
self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate')
return super().end_headers()
def do_GET(self):
# Set content type for JSON files
if self.path.endswith('.json'):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
return http.server.SimpleHTTPRequestHandler.do_GET(self)
def start_server(port=8000):
# Create the files first
files = create_iceberg_files()
# Set up and start the HTTP server
handler = CORSRequestHandler
with socketserver.TCPServer(("", port), handler) as httpd:
print(f"Server started at port {port}")
for file in files:
print(f"Access {file} at: http://localhost:{port}/{file}")
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\nShutting down server...")
httpd.shutdown()
if __name__ == "__main__":
start_server()
This enhanced version:
Creates both metadata and data files in Iceberg format
Includes CORS headers to allow access from web applications
Serves multiple files
Includes proper timestamps and UUIDs
Has a more complete Iceberg table structure
To use it:
Save and run the script:
bash
python iceberg_server.py
Access the files at:
http://localhost:8000/metadata.json
http://localhost:8000/data.json
The server will continue running until you stop it with Ctrl+C.
Note: This is a basic example for demonstration purposes. In a production environment, you'd want to: