简体   繁体   中英

How do i call two functions in a single route in python flask?

I am currently trying to convert this code:

https://github.com/marionacaros/elisabot

which is a telegram bot code to python flask

I am using this code:

https://github.com/huzaifsayed/coronabot-chatterbot

as the skeleton code.

My app.py looks like this:

from flask import Flask, render_template, request, session


from PIL import Image
from caption import get_question
import requests
from functools import partial
import logging
import random
from evaluate_chatbot import load_chatbot_model, give_feedback
import string
import os
import json

questions = ''
num_images = 7

model_dir = ''
img_directory = 'data/my_test_images/'
test_data_file = 'data/filenames_list/my_test_filenames.txt'


idx = 0
img_path = ''
shown_img_paths = []


def get_random_pic():

    count = 0

    global shown_img_paths

    with open(test_data_file) as f:
        lines = f.readlines()

    img_path = random.choice(lines)

    while img_path in shown_img_paths:
        img_path = random.choice(lines)
        count += 1
        if count == 30:
            return ''

    if img_path not in shown_img_paths:
        shown_img_paths.append(img_path)

    print('image path ', img_path)

    return img_directory + img_path.rstrip()

def feedback_and_question_2(reply):
    out = give_feedback(encoder, decoder, searcher, voc, reply)
    out = "".join([" " + i if not i.startswith("'") and i not in string.punctuation else i for i in out]).strip()
    out = out.split('.', 1)[0]
    if '?' in out:
        out = out.split('?', 1)[0] + '?'

    if out == 'what?':
        out = 'Nice'

    if out == 'no':
        out = 'ok'

    return(out)

def VQG(response):
    img_path = get_random_pic()
    image = Image.open(img_path)
    image.show()
    questions = get_question(img_path)
    return questions

# Load Model
checkpoint_iter = 13000
load_model = os.path.join('checkpoints_dialog_model/cornell_model/cornell-movie-dialogs/fine_tunned_cornell', '{}_checkpoint.tar'.format(checkpoint_iter))
encoder, decoder, searcher, voc = load_chatbot_model(load_model)
print("Bot started")


                                                                 ### Routes here ###
app = Flask(__name__)
app.static_folder = 'static'

# Config logging
log_format = '%(levelname)-8s %(message)s'
logfile = os.path.join(model_dir, 'eval.log')
logging.basicConfig(filename= logfile, level=logging.INFO, format=log_format)
logging.getLogger().addHandler(logging.StreamHandler())


@app.route("/")
def home():
    return render_template("index.html")



@app.route("/get")
def get_bot_response():
    response = request.args.get('msg')
    logging.info(response)
    return str(VQG(response))




# @app.route("/get")
# def chatbot():
#     response = request.args.get('msg')
#     logging.info(response)
#     out = feedback_and_question_2(response)
#     return out

So basically i can only call one function is the app.route("/get"), and i need to call 2 functions concurrently without exiting the function

You can use the concurrent API to launch two threads in parallel and gather their results syncronously.

import concurrent.futures
from flask import jsonify

@app.route("/get")
def get_bot_response():
    response = request.args.get('msg')
    
    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as ex:
      f1 = ex.submit(VQG, response)
      f2 = ex.submit(feedback_and_question_2, response)
      # Wait for results
      r1 = f1.result()
      r2 = f2.result()
    return jsonify(ans1=str(r1), ans2=r2)
    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM