Skip to content

Python Request

The Werk24 Python client enables seamless extraction of structured data from technical drawings. This section demonstrates different implementation approaches: synchronous processing, asynchronous processing, and callback-based integration.

Choose the Right Approach

Use the table below to determine which implementation best suits your use case. All implementations are always possible, but some might suit your use-case more than others.

Use Case Synchronous Asynchronous Callback
Quick, one-time extraction ✅ Recommended ~ ~
Processing multiple drawings concurrently from local machine ~ ✅ Recommended ~
Integration with web applciations or APIs ~ ~ ✅ Recommended

Synchronous Implementation

If you need a quick way to extract metadata from a technical drawing, the synchronous approach is the easiest method:

from werk24 import read_drawing_sync, get_test_drawing, AskMetaData

# Load a sample drawing for testing
test_drawing = get_test_drawing()

# Extract metadata from the drawing
results = read_drawing_sync(test_drawing, [AskMetaData()])

# Print extracted metadata
print(results)

Explanation

  • get_test_drawing() provides a sample drawing to test the function.
  • read_drawing_sync() sends the drawing to Werk24 and retrieves structured metadata.
  • The response is printed as a list of TechreadMessages, ready for further processing.

Limitation

This method blocks execution until the request is complete. It is not suitable for processing multiple drawings concurrently or integrating with asynchronous systems.

Asynchronous Implementation

For more complex applications, you can use an asynchronous approach to handle requests efficiently, allowing the system to process multiple drawings simultaneously.

import asyncio
from werk24 import (
    Werk24Client, AskMetaData, TechreadMessage, Hook, get_test_drawing
)


def recv(message:TechreadMessage):
    """
    Handles the response from Werk24 when a drawing is processed.

    Args:
    ----
    - message (TechreadMessage): The response message from the Werk24 server. 
      This message corresponds to the specific `Ask` request in the Hook.
    """
    if message.is_successful:
        print(f"Successfully processed the drawing:")
        print(message.payload_dict)
    else:
        print(f"Failed to process the drawing:")
        print(message.exceptions)

async def read_drawing(path: str):
    """
    Sends a technical drawing to Werk24 for analysis.

    Args:
    ----
    - path (str): Path of the file to process.
    """

    # Specify which information you want to obtain, and
    # which function shall be called when the information
    # is available.
    hooks = [Hook(ask=AskMetaData(), function=recv)]

    # Open the file and send it for processing
    with open(path, "rb") as fid:
        async with Werk24Client() as client:
            await client.read_drawing_with_hooks(fid, hooks)

# Run the asynchronous function
asyncio.run(read_drawing("<path>"))

Explanation

  • Asynchronous processing: asyncio.run() allows non-blocking execution, making it suitable for batch processing or integration into web applications.
  • Callback function (recv): Handles responses from the Werk24 server and processes the returned data.
  • Hooks: Define the extraction request (AskMetaData()) and the function to execute when the response is received.
  • Werk24Client(): Manages the connection and request submission.

This approach is ideal for large-scale applications where multiple drawings need to be processed efficiently.

Callback

For seamless integration with web applications or APIs, you can use Werk24's callback-based approach. This allows the server to notify your application when results are ready.

Producer (Sending Requests)

async def read_drawing(path: str):
    """
    Sends a technical drawing to Werk24 for analysis.

    Args:
    ----
    - path (str): Path of the file to process.
    """
    callback_url = "https://<your-own-callback-url>"
    callback_headers = {
        "Authoriziation": "Bearer XYZ"
    }

    # Specify which information you want to obtain, and
    # which function shall be called when the information
    # is available.
    hooks = [Hook(ask=AskMetaData(), function=recv)]

    # Open the file and send it for processing
    with open(path, "rb") as fid:
        async with Werk24Client() as client:
            request_id = await client.read_drawing_with_callback(fid, asks, callback_url callback_headers=headers)
            print(f"Sent request with id: {request_id}")

# Run the asynchronous function
asyncio.run(read_drawing("<path>"))

Explanation

  • Callback URL: Defines where Werk24 should send results when processing is complete.
  • Authorization Headers: Secure the API with a token.
  • Non-blocking processing: The client submits the request and moves on, instead of waiting.

Consumer

import fastapi
from werk24 import TechreadMessage

app = fastapi.App()

@app.post("/werk24-callback")
def werk24_callback(message:TechreadMessage):
    request_id = message.request_id

    if message.is_successful:
        print(f"Request with request_id={request_id} triggered callback")
        print(message)
    else:
        print(f"Request with request_id={request_id} failed. Exceptions: {message.exceptions}")

Explanation

  • FastAPI Endpoint (/werk24-callback): Handles incoming responses from Werk24.
  • TechreadMessage: The structured response containing extracted data.
  • Logs and error handling: Prints success or failure details for each request.