Win Wongsawatdichart
Win Wongsawatdichart

Reputation: 87

making a function that run after certain condition in python flask

I want to build a Line chatbot that when a POST requests is received and will parse the receive POST requests information to the chatbot users.

import os
import sys
from argparse import ArgumentParser
import json

from flask import Flask, request, abort,Response,jsonify

import requests

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError, LineBotApiError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,SourceUser
)

app = Flask(__name__)

data=''

@app.route('/data', methods=['POST'])
def get_data():
    
    """devicename,exceptionType,temperature,mask,stranger"""
    device_name = request.form.get('device_name')
    exceptionType = request.form.get('exceptionType')
    temperature = request.form.get('temperature')
    mask = request.form.get('mask')
    stranger = request.form.get('stranger')

    global data

    data=f"device_name = {device_name} exceptionType = {exceptionType} temperature = {temperature} mask = {mask} stranger = {stranger}"
    
    return_status = {"success":"true"}
    return jsonify(return_status)

while len(data) > 1:
    try:
        line_bot_api.broadcast(
                messages=TextSendMessage(text=str(data))
                )
        data=''
    except LineBotApiError as e:
        raise e
    


if __name__ == "__main__":
    arg_parser = ArgumentParser(
        usage='Usage: python ' + __file__ + ' [--port <port>] [--help]'
    )
    arg_parser.add_argument('-p', '--port', default=8000, help='port')
    arg_parser.add_argument('-d', '--debug', default=False, help='debug')
    options = arg_parser.parse_args()

    app.run(debug=options.debug, port=options.port)

here I have two parts, first is the POST requests receiver. and second is the part that checks the condition if data is present. But when I send the POST requests, the line_bot_api.broadcast does not send the message to the chatbot user. I only saw examples of flask code that has a @app.route() so I was wondering if something like this works? or is there a better way to implement the condition (instead of checking data value, is it better to check if function get_data() ran or requests has been sent to our /data route)

Upvotes: 0

Views: 226

Answers (1)

soumith
soumith

Reputation: 606

The while loop stops immediately because the condition fails. One way to get around this and do what you want is by using threads.

import os
import sys
from argparse import ArgumentParser
import json
import threading

from flask import Flask, request, abort,Response,jsonify

import requests

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError, LineBotApiError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,SourceUser
)

app = Flask(__name__)

data=''

@app.route('/data', methods=['POST'])
def get_data():

    """devicename,exceptionType,temperature,mask,stranger"""
    device_name = request.form.get('device_name')
    exceptionType = request.form.get('exceptionType')
    temperature = request.form.get('temperature')
    mask = request.form.get('mask')
    stranger = request.form.get('stranger')

    global data

    data=f"device_name = {device_name} exceptionType = {exceptionType} temperature = {temperature} mask = {mask} stranger = {stranger}"

    return_status = {"success":"true"}
    return jsonify(return_status)

def broadcast():
    while True:
        if len(data) < 1 : continue
        try:
            line_bot_api.broadcast(
                    messages=TextSendMessage(text=str(data))
                    )
            data=''
        except LineBotApiError as e:
            raise e



if __name__ == "__main__":
    arg_parser = ArgumentParser(
        usage='Usage: python ' + __file__ + ' [--port <port>] [--help]'
    )
    arg_parser.add_argument('-p', '--port', default=8000, help='port')
    arg_parser.add_argument('-d', '--debug', default=False, help='debug')
    options = arg_parser.parse_args()

    broadcast_thread = threading.Thread(target=broadcast)
    broadcast_thread.start()

    app.run(debug=options.debug, port=options.port)

This is definitely not the best way. But it works.

Upvotes: 1

Related Questions