Norme relative a PythonScript

Stai visualizzando la documentazione di Apigee Edge.
Vai alla sezione Documentazione di Apigee X.
Informazioni

Cosa

Il criterio dello script Python ti consente di aggiungere funzionalità Python personalizzate al flusso del proxy API, soprattutto quando le funzionalità di cui hai bisogno vanno oltre i criteri predefiniti di Edge che forniscono.

Il supporto del linguaggio Python è fornito tramite Jython versione 2.5.2. Le librerie di terze parti che aggiungi devono essere "Python puro" (implementato solo in Python). Per ulteriori informazioni sull'aggiunta di librerie, consulta File di risorse.

Un criterio Python non contiene codice effettivo. Un criterio Python fa riferimento invece a un file Python risorsa e definisce il passaggio nel flusso dell'API in cui viene eseguito lo script Python. Puoi caricare lo script tramite l'editor proxy dell'interfaccia utente di gestione oppure puoi includerlo nella Directory /resources/py nei proxy API che sviluppi localmente.

Esempi

Criteri Python e copione

Criterio dello script Python

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

In questo esempio, l'elemento ResourceURL specifica lo script Python pertinente risorsa.

Script Python

Questo mostra cosa potresti includere nello script Python stesso.

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)

Riferimento elemento

<?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

&lt;ResourceURL&gt; elemento

Questo elemento specifica il file Python principale che verrà eseguito nel flusso dell'API. Puoi archiviare questo file nell'ambito del proxy API (in /apiproxy/resources/py nel proxy API o nella sezione Script del riquadro di navigazione dell'editor del proxy API) o nella a livello di organizzazione o di ambiente per il riutilizzo in più proxy API, come descritto in File di risorse: Il tuo codice può utilizzare oggetti, metodi e proprietà del modello a oggetti JavaScript.

<ResourceURL>py://myscript.py</ResourceURL>
Predefinita: Nessuno
Presenza: Obbligatorio
Tipo: Stringa

&lt;IncludeURL&gt; elemento

Specifica un file Python da caricare come dipendenza dal file Python principale specificato con Elemento <ResourceURL>. Gli script verranno valutati nell'ordine in cui sono elencate nelle norme.

Includi più di una risorsa di dipendenza Python con <IncludeURL> elementi.

<IncludeURL>py://myscript_dependency.py</IncludeURL>
Predefinita: Nessuno
Presenza: Facoltativo
Tipo: Stringa

Codici di errore

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>

Argomenti correlati