-1
  • I am posting a request in the form, which takes a pdf as an input defined in OmniDocsReceiver.py. running on host 127.0.0.1 , port 8000.
  • Callback url CallbackUrl = "http://0.0.0.0:8030/OmniDocsSender/"
async def omnidocs_receiver(uploaded_file: UploadFile = File(...)):
    try:
        # pass the document

        if not uploaded_file:
            logger.error("File not uploaded", exc_info=True)
            return {"message": "No upload file sent"}
        else:
            logger.info("Received file", exc_info=True)
            # specify the location
            file_location = f"{gstr_uploaded_file}/{uploaded_file.filename}"

            # copy the file at the specific location
            with open(file_location, "wb+") as file_object:
                logger.info("File copied to local input folder", exc_info=True)
                shutil.copyfileobj(uploaded_file.file, file_object)

            # read the file and encode it
            with open(file_location, "rb") as pdf_file:
                logger.info("File encoded to base64", exc_info=True)
                encoded_string = base64.b64encode(pdf_file.read())

            # post the file

            payload = {
                "InputDocument": str(encoded_string.decode('utf-8')),
                "ContextKey": ''.join(random.choices(string.ascii_uppercase + string.digits, k=5)) + "_" + str(
                    uploaded_file.filename),
                "CallbackUrl": CallbackUrl,
                "UseCaseCode": use_case,
                "FileFormat": "pdf",
            }

            response = requests.post(url=processs_document_url, data=json.dumps(payload))
            logger.info("Document sent to document for masking", exc_info=True)
            print("Response text while sending=", response.text.encode('utf8'))

        return response.text.encode('utf8')
    except Exception as e:
        logger.error(str(e), exc_info=True)
  • I am putting a postman post request on http://127.0.0.1:8000/OmniDocsReceiver/ and passing a pdf in uploaded_file param.

  • Which in turn sends a response in the below form when the execution is completed at the mentioned callback url

Json Response on successful completion
{
"TransactionRefNo": “<t_id>”,
"Results": {
"ContextKey": "<context_key>",
"MaskedDocument": "base_64 string",
"QualitativeAnalysis": "PossibleMissingNumber"
},
"ResponseCode": "2001",
"HttpResponseCode": 200,
"ProcessingStatus": 2
}


  • I have the callback running on host 0.0.0.0 port 8030, but while testing it through postman the data is not recevied.
from fastapi import FastAPI, File, UploadFile, Request
from configuration import *

import base64
import shutil
import string
import random
import uvicorn
import datetime


app = FastAPI()

# Folder path
gstr_save_masked_file_path = CAL_SAVE_MASKED_DOCUMENT_PATH
print(gstr_save_masked_file_path)


@app.post("/OmniDocsSender/")
async def omnidocs_sender():
    try:
        logger.info("Document received in callback", exc_info=True)
        # print(request)
        # await request.json()

        current_time = datetime.datetime.now()
        recevied_file = "something" + str(current_time)

        res = ''.join(random.choices(string.ascii_uppercase +
                                     string.digits, k=4))

        # save the file by copying the file at the specific location
        file_location = f"{gstr_save_masked_file_path}/{res}"
        print("location and unique key generated")

        with open(file_location, "w") as file_object:
            logger.info("File successfully saved in the local storage after masking", exc_info=True)
            print("writing file")
            file_object.write(recevied_file)
        return "Done"

    except Exception as e:
        print(str(e))

if __name__ == "__main__":
    uvicorn.run(app)
  • On the callback, the steps I have defined is not getting executed but the file is getting stored on the server side.
Lav Sharma
  • 327
  • 1
  • 5
  • 23

2 Answers2

0

You get a 404 on endpoint http://0.0.0.0:8030/OmniDocsReceiver because you have defined a different endpoint. Try http://0.0.0.0:8030/OmniDocsSender because that is where your FastAPI endpoint is listening on.

Also, a GET request should not have a body, so I would recommend you make it a POST endpoint.

JarroVGIT
  • 4,291
  • 1
  • 17
  • 29
  • I have made the said changes, but the code in my callback is not getting executed after successful execution of the process document. – Lav Sharma Jul 28 '22 at 06:06
  • 1
    I don’t think you are using the term “callback” appropriately, and that causes that I don’t understand exactly what you mean. Do you mean your python code in your endpoint definition? – JarroVGIT Jul 28 '22 at 08:05
  • I have updated my answer, i was missing the request body in my code on callback – Lav Sharma Jul 28 '22 at 09:58
  • @Chris I can't as it says ```You cannot delete this question as others have invested time and effort into answering it. For more information, visit the help center.``` – Lav Sharma Jul 28 '22 at 11:15
0
  • CallBack was missing the request body, due to which the response was not getting displayed
@app.post("/OmniDocsSender")
async def omnidocs_sender_post(request: Request):
    try:
        body = await request.json()
        return body
    except Exception as ex:
        logger.error(ex, exc_info=True)
Lav Sharma
  • 327
  • 1
  • 5
  • 23