0

Currently I need to receive an ID and towards this ID I need to create a new account making a post to a platform, after create the account I need to create some users related to this account in my database. Currently I'm doing this in a way that my request are running in 50seconds, and this is not worth, I would to like a better wat to do it. My code seems like it:

@app.route("/create_account", methods=["POST"])
def create_account():
    company_id = request.args.get("company_id")

    if not company_id:
        return make_response("Company id is empty.", 404)

    account_data = get_account_data(company_id)

    post_account_data = format_account_data(
        account_data
    )

    r = requests.post(
        api_url,
        headers={
            "Authorization": token,
            "Content-Type": "application/json",
        },
        data=json.dumps(post_account_data),
    )

    if r.status_code == 200:
        account_id = json.loads(r.content).get("id")
        run_profile_creation(str(company_id))
        return make_response("Account has been created.", 200)
    else:
        return make_response(r.content, r.status_code)


def run_profile_creation(company_id: str):
    profiles = get_profiles(company_id)
    if profiles is None:
        return make_response(
            f"Cannot be able to retrieves profiles from company id{company_id}.",
            404,
        )
    for profile_id in profiles:
        user = get_user(str(profile_id))
        if user.get("status_code") == 200:
            user_data = {
                "name": user.get("name"),
                "email": user.get("email"),
            }
            r = requests.post(
                    api_url,
                    headers={
                        "Authorization": token,
                        "Content-Type": "application/json",
                    },
                    data=json.dumps(user_data),
                )
            if r.status_code == 200:
                return make_response("A new vitally account has been created.", 200)
            else:
                return make_response(
                    "Failed",
                    r.status_code,
                )

probably there is a better way to do this, If you can share any content that can help me with it, I will be grateful

  • Requests that rely on the output of a prior request have to be run sequentially. You can’t get around that. But making what appears to be 3 sequential requests should not take 50 seconds. What might be causing the problem is if that profiles array contains many items, you’re making 1 + 2n requests, and if n is at all high, that could be a problem. You should execute the iterated requests in parallel, see here for methods: https://stackoverflow.com/questions/57126286/fastest-parallel-requests-in-python – bryan60 Apr 22 '22 at 23:58

0 Answers0