Reputation: 43
I'm working on an API function that takes an input from one web service (Knack), runs a number of functions to create a payload to send to another (PandaDoc), and then eventually closes by executing a POST back to Knack with the URL to the newly created PandaDoc.
Here's the start of my code:
from flask import Flask, request, Response
from flask_restful import Resource, Api, reqparse
import price_calculator
import requests
from pandadoc import build_payload, create, send, get_event_details, send_document_to_knack
app = Flask(__name__)
api = Api(app)
class Pricing(Resource):
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('eventId', required=True, type=str)
args = parser.parse_args()
price_list = price_calculator.price_calc(event_id=args['eventId'])
pandadoc_payload = build_payload(price_list=price_list, event_id=args['eventId'])
create_meta = create(payload=pandadoc_payload)
# Code should pause here to listen for response from respond()
# I'll add some code here to compare webhook data to args['eventId'] to make sure it's the same document
recipient_email = get_event_details(event_id=args['eventId'])['client_email']
send_meta = send(doc_id=create_meta['id'], recipient_email=recipient_email)
knack = send_document_to_knack(event_id=args['eventId'], doc_id=create_meta['id'])
return {
'Price List': price_list,
'PandaDoc Meta': create_meta
}, 200
@app.route('/webhook', methods=['POST'])
def respond():
data = request.json[0]['data']
args = {
'doc_id': data['id'],
'doc_status': data['status']
}
return Response(status=200)
However, PandaDoc publishes documents asynchronously, which means it takes anywhere from 3-5 seconds for the doc to be published once I execute create_meta
. PandaDoc offers a webhook for when a document status is updated (published), and I have figured out how to listen for that webhook. However, I somehow need the function post()
to pause until it receives the webhook, so I can compare the payload from the webhook to the existing data (to make sure it's the same document) and then retreive the document ID to send back to Knack.
How can I get my post()
function to pause and wait for the results of the webhook? I'd love for it to move on as soon as the webhook posts, rather than setting a fixed time...
I welcome any other feedback on the code, too, as I'm still relatively new to creating APIs in Python! Thanks.
Upvotes: 1
Views: 630
Reputation: 21
You can use PandaDoc python SDK (ensure_document_created method to poll until the document is created)
Let me know if you have any other questions.
Upvotes: 2
Reputation: 120
I don't program with Python too much, so I'm not 100% sure about this answer but I think that Python has an await
system.
I think something like this could be done:
async def myFunction():
await myFunctionThatTakesSomeTimeToRun()
Upvotes: -1