Ruby
Un script de Ruby que usa la API con net/http y json de la biblioteca estándar: no hay que instalar gemas. Enumera las variables etiquetadas de una plantilla, mide el dibujo que genera con los valores dados y lo exporta como PDF.
Descárguelo: box.rb.
# box.rb: list a template's inputs, measure it and export it as a PDF with the PiQ SaaS API.
# Ruby 3.0 or later; net/http and json from the standard library.
require "json"
require "net/http"
KEY = ENV["PIQ_API_KEY"]
BASE = (ENV["PIQ_URL"] || "https://saas.parametriq.co.uk").chomp("/")
storage = ENV["PIQ_STORAGE"] # optional: a registered storage's name
abort "Set PIQ_API_KEY to your API key." if KEY.to_s.empty?
TEMPLATE = "L=400,\"Length\"\nW=300,\"Width\"\nP1=[L,0]\nP2=[L,W]\nP3=[0,W]\nPOLYLINE @1,[P0,P1,P2,P3],TRUE,0"
# the template itself, or (optional) where it is kept in your storage
template = storage ? { source: { storage: storage, key: "templates/box.piq" } } : { template: TEMPLATE }
values = { L: 500, W: 250 }
def post(path, body)
uri = URI(BASE + path)
response = Net::HTTP.post(uri, JSON.generate(body), "X-API-KEY" => KEY, "Content-Type" => "application/json")
return response if response.is_a?(Net::HTTPSuccess)
warn "Error #{response.code} #{response.message}"
unless response.body.to_s.empty? # a 401 has no body
problem = JSON.parse(response.body) rescue { "detail" => response.body }
warn problem["title"] if problem["title"]
warn problem["detail"] if problem["detail"]
(problem["errors"] || {}).each { |field, messages| warn " #{field}: #{messages.join(" ")}" }
end
exit 1
end
# 1. The template's labelled variables
JSON.parse(post("/inputs", template).body)["inputs"].each do |i|
puts "#{i["name"]}: #{i["label"]} (#{i["kind"]}, #{i["value"]})"
end
# 2. The drawing measured, with the values given
m = JSON.parse(post("/measure", template.merge(values: values)).body)
cut = m["layers"].find { |layer| layer["layer"] == "Cut" }&.fetch("length") || 0
puts "Size: #{m["width"]} x #{m["height"]}, cut length: #{cut}"
# 3. The drawing as a PDF
pdf = post("/export/pdf", template.merge(values: values))
File.binwrite("box.pdf", pdf.body)
puts "Saved box.pdf (#{pdf["X-PiQ-Warnings"]} warnings)"
# 4. Optional: the PDF saved to your storage instead of downloaded
if storage
destination = { storage: storage, key: "drawings/box.pdf" }
saved = JSON.parse(post("/save/pdf", template.merge(values: values, destination: destination, overwrite: true)).body)
puts "Saved #{saved["key"]} to #{saved["storage"]} (#{saved["size"]} bytes)"
end
Cómo funciona
- Configuración. La clave se toma de
PIQ_API_KEY, la dirección dePIQ_URL(el propio servicio si no está definida) y, opcionalmente, el nombre de un almacenamiento dePIQ_STORAGE. Sin clave, el script se detiene de inmediato. - La plantilla.
templatees el cuerpo del que parte cada solicitud: el texto de la plantilla comotemplateo, cuandoPIQ_STORAGEestá definida, dónde está guardada en su almacenamiento comosource.valuesdaLyWpor nombre. Cada solicitud le añade lo suyo conmerge. postenvía un cuerpo a una operación como JSON, con la clave en el encabezadoX-API-KEY(Net::HTTP.postusa HTTPS para una direcciónhttps). Una respuesta correcta se devuelve para leerla.- Errores. De cualquier otra respuesta se imprime el estado y después la descripción del problema: su
title, sudetaily cada entrada deerrors, el campo y qué está mal en él. Un401no tiene cuerpo, así que no hay nada más que imprimir; un cuerpo que no es JSON se imprime tal cual. Después, el script termina con1. - Inputs.
POST /inputssolo necesita la plantilla. Cada uno de susinputstiene unname,label,kindyvalue. - Measure.
POST /measurecon los valores da elwidthy elheightdel dibujo, y las longitudes de sus líneas por capa enlayers; la longitud de corte es la longitud en la capaCut. - Export.
POST /export/pdfresponde con el propio PDF, no con JSON: su cuerpo se escribe enbox.pdfconFile.binwrite. El encabezadoX-PiQ-Warningsindica cuántas cosas no pudieron exportarse tal cual. - Save (opcional). Con un almacenamiento,
POST /save/pdfexporta el mismo dibujo y lo guarda en su almacenamiento endestination;overwrite: truereemplaza un archivo que ya exista. Responde con dónde lo ha guardado y su tamaño.
Cómo ejecutarlo
Guarde el script como box.rb y, a continuación:
export PIQ_API_KEY=XXXX-XXXX-XXXX-XXXXX
ruby box.rb
Imprime las variables etiquetadas de la plantilla, el tamaño del dibujo y su longitud de corte, y guarda box.pdf:
L: Length (Number, 400)
W: Width (Number, 300)
D: Depth (Number, 300)
Size: 500 x 250, cut length: 1500
Saved box.pdf (0 warnings)
Con un valor que la plantilla no puede usar (por ejemplo, "L": "long"), imprime el problema y se detiene:
Error 400 Bad Request
One or more validation errors occurred.
Some of the values given can't be used.
L: L is a number.
Con una clave incorrecta, solo imprime Error 401 Unauthorized: un 401 no tiene
descripción del problema.
Para probar la parte del almacenamiento, registre un almacenamiento (consulte
Registrar un almacenamiento), coloque en él una plantilla como templates/box.piq y
establezca PIQ_STORAGE con el nombre del almacenamiento. La plantilla se lee entonces desde su almacenamiento, y el
PDF también se guarda en él como drawings/box.pdf, reemplazando cualquier archivo que ya exista.
Consulte también: API, Inputs, Measure, Exportar un dibujo, Guardar en su almacenamiento, Registrar un almacenamiento, Clientes.