Política PythonScript

Estás viendo la documentación de Apigee Edge.
Ve a la Documentación de Apigee X.
información

Qué

La política de Python Script permite agregar funciones personalizadas de Python a tu flujo del proxy de API, especialmente cuando la funcionalidad que necesitas está más allá de las políticas listas para usar de Edge proporcionan.

La compatibilidad con el lenguaje Python se proporciona a través de la versión 2.5.2 de Jython. Las bibliotecas de terceros que agregues deben ser “Python puro” (solo implementado en Python). Para obtener más información sobre cómo agregar bibliotecas, consulta Archivos de recursos.

Una política de Python no contiene código real. En su lugar, una política de Python hace referencia a un recurso de Python y define el paso en el flujo de API en el que se ejecuta la secuencia de comandos de Python. Puedes subir a través del editor de proxy de la IU de administración, o puedes incluirla El directorio /resources/py en los proxies de API que desarrollas de manera local

Ejemplos

Política y secuencia de comandos de Python

Política de secuencia de comandos de Python

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Script name="Python-1">
        <DisplayName>Python-1</DisplayName>
        <ResourceURL>py://myscript.py</ResourceURL>
</Script>

En este ejemplo, el elemento, ResourceURL especifica el recurso de secuencia de comandos de Python correspondiente.

Secuencia de comandos de Python

Aquí se muestra lo que podrías incluir en la secuencia de comandos de Python.

import base64

username = flow.getVariable("request.formparam.client_id")
password = flow.getVariable("request.formparam.client_secret")

base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
authorization = "Basic "+base64string

flow.setVariable("authorizationParam",authorization)

Referencia de elementos

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Script name="Python-1">
    <DisplayName>Python-1</DisplayName>
    <ResourceURL>py://myscript.py</ResourceURL>
    <IncludeURL>py://myscript_dependency.py</IncludeURL>
</Script>

The following table describes attributes that are common to all policy parent elements:

Attribute Description Default Presence
name

The internal name of the policy. The value of the name attribute can contain letters, numbers, spaces, hyphens, underscores, and periods. This value cannot exceed 255 characters.

Optionally, use the <DisplayName> element to label the policy in the management UI proxy editor with a different, natural-language name.

N/A Required
continueOnError

Set to false to return an error when a policy fails. This is expected behavior for most policies.

Set to true to have flow execution continue even after a policy fails.

false Optional
enabled

Set to true to enforce the policy.

Set to false to turn off the policy. The policy will not be enforced even if it remains attached to a flow.

true Optional
async

This attribute is deprecated.

false Deprecated

<DisplayName> element

Use in addition to the name attribute to label the policy in the management UI proxy editor with a different, natural-language name.

<DisplayName>Policy Display Name</DisplayName>
Default

N/A

If you omit this element, the value of the policy's name attribute is used.

Presence Optional
Type String

Elemento <ResourceURL>

Este elemento especifica el archivo principal de Python que se ejecutará en el flujo de la API. Puedes almacenar este archivo en el permiso del proxy de API (en /apiproxy/resources/py en el paquete del proxy de API o en la sección de secuencias de comandos del panel de navegación del editor de proxy de API), o en los permisos de la organización o del entorno para volver a utilizarse en múltiples proxies de API, como se describe en Archivos de recursos. Tu código puede usar los objetos, los métodos y las propiedades del modelo de objetos de JavaScript.

<ResourceURL>py://myscript.py</ResourceURL>
Predeterminado: None
Presencia: Obligatorio
Tipo: String

Elemento <IncludeURL>

Especifica un archivo de Python que se cargará como dependencia al archivo principal de Python especificado con el elemento <ResourceURL>. Las secuencias de comandos se evaluarán en el orden en que se incluyan en la política.

Incluye más de un recurso de dependencia de Python con elementos <IncludeURL> adicionales.

<IncludeURL>py://myscript_dependency.py</IncludeURL>
Predeterminado: None
Presencia: Opcional
Tipo: String

Códigos de error

This section describes the fault codes and error messages that are returned and fault variables that are set by Edge when this policy triggers an error. This information is important to know if you are developing fault rules to handle faults. To learn more, see What you need to know about policy errors and Handling faults.

Runtime errors

These errors can occur when the policy executes.

Fault code HTTP status Cause Fix
steps.script.ScriptEvaluationFailed 500 The PythonScript policy can throw several different types of ScriptExecutionFailed errors. Commonly seen types of errors include NameError and ZeroDivisionError.

Deployment errors

These errors can occur when you deploy a proxy containing this policy.

Error name Cause Fix
InvalidResourceUrlFormat If the format of the resource URL specified within the <ResourceURL> or the <IncludeURL> element of the PythonScript policy is invalid, then the deployment of the API proxy fails.
InvalidResourceUrlReference If the <ResourceURL> or the <IncludeURL> elements refer to a PythonScript file that does not exist, then the deployment of the API proxy fails. The referenced source file must exist either the API proxy, environment, or organization level.

Fault variables

These variables are set when this policy triggers an error at runtime. For more information, see What you need to know about policy errors.

Variables Where Example
fault.name="fault_name" fault_name is the name of the fault, as listed in the Runtime errors table above. The fault name is the last part of the fault code. fault.name Matches "ScriptExecutionFailed"
pythonscript.policy_name.failed policy_name is the user-specified name of the policy that threw the fault. pythonscript.PythonScript-1.failed = true

Example error response

{
  "fault": {
    "faultstring": "Execution of SetResponse failed with error: Pythonscript runtime error: "ReferenceError: "status" is not defined.\"",
    "detail": {
      "errorcode": "steps.script.ScriptExecutionFailed"
    }
  }
}

Example fault rule

<FaultRule name="PythonScript Policy Faults">
    <Step>
        <Name>AM-CustomErrorResponse</Name>
        <Condition>(fault.name Matches "ScriptExecutionFailed") </Condition>
    </Step>
    <Condition>(pythonscript.PythonScript-1.failed = true) </Condition>
</FaultRule>

Temas relacionados