Beispiel #1
0
 def __init__(self, my_app):
     self.api = ApiService()
     self.current_worker = ''
     self.workers = {}
     self.station_name = ''
     self.my_app = my_app
     self.init_values()
Beispiel #2
0
 def __init__(self, my_app):
     self.api = ApiService()
     self.my_app = my_app
     self.current_worker = ''
     self.workers = {}
     self.readed_order = {}
     self.current_order = 0
     self.current_boards = []
     self.init_values()
Beispiel #3
0
def test_get_webhooks():

    api_svc = ApiService(ACCESS_TOKEN)
    result = api_svc.get_webhooks("/webhooks?page=1&per_page=1")
    assert result.status_code == 200
    result = result.json()
    total = result["total"]
    print(
        '\ntest_endpoint2::get_webhooks -  {} webhook(s) successfully retrieved...'
        .format(total))
Beispiel #4
0
def test_happy_path_scenario():
    api_svc = ApiService(ACCESS_TOKEN)

    # Check HEAD
    result = api_svc.check_head("/webhooks")
    assert result.status_code == 204

    # Check OPTIONS
    result = api_svc.check_options("/webhooks")
    # No options returned (?)
    assert result.status_code == 204

    survey_id = create_survey(api_svc, SURVEY_TITLE, "/surveys")
    webhook_id = create_webhook(api_svc, survey_id, "webhook_one", "/webhooks")
    modify_webhook(api_svc, "My Modified Webhook", "/webhooks/" + webhook_id)
    replace_webhook(api_svc, survey_id, "/webhooks/" + webhook_id)
    get_webhook(api_svc, "/webhooks/" + webhook_id)
    delete_webhook(api_svc, "/webhooks/" + webhook_id)
Beispiel #5
0
 def __init__(self):
     """
     The main class which loads the App config and interacts with the ApiService to retrieve Food truck data.
     This class is also responsible for how the data is printed on the console.
     """
     self.display_message(
         "===============================| Foodiezz |===============================\n"
     )
     self.display_message("Hello! Welcome to Foodiezz!")
     # load the AppConfig
     config = AppConfig()
     self.socrata_dataset_id = config.socrata_dataset_id
     self.page_limit = config.page_limit
     # initialize the the ApiService object
     self.api_service = ApiService(config.socrata_domain, config.app_token)
     self.foodtruck_dataset = {}
     # initializing PrettyTable object with 'Name' and 'Address' as the header
     # I am using PrettyTable to print the final output in an organized and structured way on the console.
     self.foodtruck_table = PrettyTable(field_names=['Name', 'Address'])
     self.foodtruck_table.min_width = 60
     self.total_foodtrucks_open = 0
Beispiel #6
0
def hello():
    service = ApiService()
    return service.say()
Beispiel #7
0
    def __init__(self, config):
        self.last_url_requested = None

        ApiService.__init__(self, config, self.API_URL, self.USER_AGENT, self.AUTH_URL, self.CLIENT_ID,
                            self.CLIENT_SECRET, self.GRANT_TYPE, self.SCOPE)
    def __init__(self, config):
        self.last_url_requested = None

        ApiService.__init__(self, config, self.API_URL, self.USER_AGENT,
                            self.AUTH_URL, self.CLIENT_ID, self.CLIENT_SECRET,
                            self.GRANT_TYPE, self.SCOPE)
Beispiel #9
0
class AppService:
    def __init__(self, my_app):
        self.api = ApiService()
        self.current_worker = ''
        self.workers = {}
        self.station_name = ''
        self.my_app = my_app
        self.init_values()

    def init_values(self):
        workers_raw_data = self.api.get_endpoint_data('workers')

        self.station_name = self.api.get_endpoint_data('stations/{}'.format(
            settings.STATION_NUMBER)).get('name', '')

        self.my_app.main_app_name_label = '{} ROOM'.format(self.station_name)
        self.workers = {
            worker['barcode']: worker['username']
            for worker in workers_raw_data
        }

    def update_worker(self, _barcode):
        if _barcode in self.workers:
            self.my_app.worker_label = self.workers[
                _barcode] if not self.current_worker else '-'
            self.my_app.status_label = 'welcome' if not self.current_worker else '-'
            if not self.current_worker:
                self.current_worker = self.workers[_barcode]
                self.api.send_endpoint_data(endpoint='add_worker_scan',
                                            data={
                                                "worker_barcode":
                                                self.current_worker,
                                                "started": True
                                            })
            else:
                self.api.send_endpoint_data(endpoint='add_worker_scan',
                                            data={
                                                "worker_barcode":
                                                self.current_worker,
                                                "started": False
                                            })
                self.current_worker = ''
            return True
        return False

    def update_barcode_list(self, _data):
        current_last_barcode_label = self.my_app.last_barcode_label
        self.my_app.last_barcode_label = str(_data)

        for index in range(10, 1, -1):
            up_label = getattr(self.my_app,
                               'barcode_label_{}'.format(index - 1))
            setattr(self.my_app, 'barcode_label_{}'.format(index), up_label)

        first_label = '{} {}'.format(datetime.now().strftime('%H:%M:%S'),
                                     current_last_barcode_label)

        self.my_app.barcode_label_1 = first_label if current_last_barcode_label != '' else ''
        self.my_app.last_time_label = datetime.now().strftime('%H:%M:%S')

    def add_barcode(self, _barcode):
        data_to_send = {
            "barcode": _barcode,
            "worker": self.current_worker,
            "station": self.station_name,
        }

        if self.my_app.comment_box:
            data_to_send['comment'] = self.my_app.comment_box

        if settings.STATION_NUMBER == 1:
            new_barcode = {"barcode": _barcode}
            is_sended, message = self.api.send_endpoint_data(
                endpoint='add_barcode', data=new_barcode)

        is_sended, message = self.api.send_endpoint_data(endpoint='add_scan',
                                                         data=data_to_send)
        self.my_app.status_label = message
        self.my_app.comment_box = ''

    def add_second_category(self, _barcode):
        data_to_send = {"barcode": _barcode, "second_category": True}

        is_sended, message = self.api.send_endpoint_data(
            endpoint='add_second_category', data=data_to_send)
        if is_sended:
            message = 'ADDED 2th'
        else:
            message = 'NOT ADDED 2th'
        self.my_app.status_label = message

    def main_handling(self, _barcode):
        if not self.update_worker(_barcode):
            if not self.current_worker:
                self.my_app.status_label = 'SCAN WORKER CARD'
            else:
                if self.my_app.second_category_flag is True:
                    self.add_second_category(_barcode)
                    self.my_app.second_category_flag = False
                else:
                    self.add_barcode(_barcode)
        self.update_barcode_list(_barcode)
Beispiel #10
0
class AppService:
    def __init__(self, my_app):
        self.api = ApiService()
        self.my_app = my_app
        self.current_worker = ''
        self.workers = {}
        self.readed_order = {}
        self.current_order = 0
        self.current_boards = []
        self.init_values()

    def init_values(self):
        workers_raw_data = self.api.get_endpoint_data(endpoint='workers')

        self.my_app.main_app_name_label = '{} ROOM'.format(
            settings.STATION_NAME)
        self.workers = {
            worker['barcode']: worker['username']
            for worker in workers_raw_data
        }

    def update_worker(self, _barcode):
        if _barcode in self.workers:
            self.my_app.worker_label = self.workers[
                _barcode] if not self.current_worker else '-'
            self.my_app.status_label = 'welcome' if not self.current_worker else '-'
            if not self.current_worker:
                self.current_worker = self.workers[_barcode]
                self.api.send_endpoint_data(endpoint='add_worker_scan',
                                            data={
                                                "worker_barcode":
                                                self.current_worker,
                                                "started": True
                                            })
            else:
                self.api.send_endpoint_data(endpoint='add_worker_scan',
                                            data={
                                                "worker_barcode":
                                                self.current_worker,
                                                "started": False
                                            })
                self.current_worker = ''
            return True
        return False

    def update_barcode_list(self, _data):
        current_last_barcode_label = self.my_app.last_barcode_label
        self.my_app.last_barcode_label = str(_data)

        for index in range(10, 1, -1):
            up_label = getattr(self.my_app,
                               'barcode_label_{}'.format(index - 1))
            setattr(self.my_app, 'barcode_label_{}'.format(index), up_label)

        first_label = '{} {}'.format(datetime.now().strftime('%H:%M:%S'),
                                     current_last_barcode_label)

        self.my_app.barcode_label_1 = first_label if current_last_barcode_label != '' else ''
        self.my_app.last_time_label = datetime.now().strftime('%H:%M:%S')

    def add_barcode(self, _barcode):
        status, message = self.api.send_endpoint_data(
            endpoint='add_sended_board',
            data={
                "board": _barcode,
                "order": self.current_order
            })
        if status == 200:
            self.current_boards.append(_barcode)
            self.my_app.status_label = 'ADDED'
        else:
            self.my_app.status_label = message.get('detail', "")

    def check_new_order_available(self):
        if self.my_app.order_id != self.current_order:
            if self.my_app.order_id is not 0:
                self.load_order(self.my_app.order_id)
            else:
                self.clear_order()
            self.current_order = self.my_app.order_id

    def handle_delete(self, _barcode):
        if self.delete_barcode(_barcode):
            self.my_app.status_label = 'DELETED'
        else:
            self.my_app.status_label = 'CANNOT DELETE'

        self.my_app.delete_board_button = 'DELETE BOARD'

    def clear_order(self):
        self.my_app.order_detail_label = ''
        self.my_app.order_texbox.text = ''
        already_sended = self.api.get_endpoint_data(
            endpoint="orders/{}".format(self.current_order))['sended']

        for board in already_sended:
            if not self.delete_barcode(board):
                self.current_boards = self.api.get_endpoint_data(
                    endpoint="orders/{}".format(self.order_id))['sended']
                self.my_app.status_label = 'REMOVE ERROR'
                return False

        self.current_boards = []
        self.my_app.status_label = 'REMOVED'
        self.readed_order = {}
        self.my_app.delete_board_button = 'DELETE BOARD'

    def delete_barcode(self, _barcode):
        status, message = self.api.delete_endpoint_data(
            endpoint='add_sended_board',
            data={
                "board": _barcode,
                "order": self.current_order
            })

        if message == 'barcode removed from order' and status == 200:
            if _barcode in self.current_boards:
                self.current_boards.remove(_barcode)
            return True
        else:
            return False

    def load_order(self, _id):
        order = self.api.get_endpoint_data(endpoint="orders/{}".format(_id))
        if order['completed']:
            self.my_app.status_label = 'ALREADY SENDED'
            self.my_app.load_order_button = 'LOAD ORDER'
            self.my_app.order_texbox.text = ''
            self.current_order = 0
            return False

        boards = order.get('boards', False)
        self.current_boards = order.get('sended', [])
        self.my_app.status_label = 'ORDER LOADED' if boards else 'NO ORDER'
        self.my_app.order_detail_label = order['client'] if boards else ''
        self.readed_order = boards if boards else {}

        self.create_message_list()

    def return_current_models(self):
        already_sended_boards = copy.deepcopy(self.readed_order)
        for board in self.current_boards:
            board_model = self.api.get_endpoint_data(
                endpoint='boards/{}'.format(board))['model']
            already_sended_boards[board_model] -= 1

        return already_sended_boards

    def check_if_send_order(self):
        if self.my_app.status_label == 'SENDING':
            already_sended_boards = self.return_current_models()
            if all(value == 0 for value in already_sended_boards.values()):
                status, message = self.api.update_endpoint_data(
                    endpoint='orders/{}'.format(self.current_order),
                    data={"completed": "true"})
                self.my_app.status_label = 'SENDED' if status == 200 else 'ERROR'
            else:
                self.my_app.status_label = 'NOT FULL'
                return False
            self.current_boards = []
            self.current_order = 0
            self.my_app.order_id = 0
            self.my_app.order_texbox.text = ''
            self.my_app.load_order_button = 'LOAD ORDER'
            self.my_app.order_detail_label = ''
            self.my_app.message_labels = []

    def create_message_list(self):
        self.my_app.message_labels = []
        already_sended_boards = self.return_current_models()

        for index, board in enumerate(self.readed_order):
            self.my_app.message_labels.append('{}:{}{}{}{}'.format(
                board, ' ' * (20 - len(board)), self.readed_order[board],
                '        ', already_sended_boards[board]))

    def main_handling(self, _barcode):
        if not self.update_worker(_barcode):
            if not self.current_order:
                self.my_app.status_label = 'READ ORDER'
            elif not self.current_worker:
                self.my_app.status_label = 'SCAN WORKER CARD'
            else:
                if self.my_app.delete_board_button == 'CANCEL DELETE':
                    self.handle_delete(_barcode)
                else:
                    self.add_barcode(_barcode)
                self.create_message_list()
        self.update_barcode_list(_barcode)
Beispiel #11
0
from api_service import ApiService
import os
from image_file import ImageFile
from tqdm import tqdm

mApiService = ApiService()
mImageFile = ImageFile()
yolotype = [
    "with_mask", "without_mask", "mask_weared_incorrect", "person", "hand",
    "foot", "head"
]
inSaveYoloType = [4, 5, 6]  # 要更新的資料
yolotypeStr = str(yolotype).replace("'", '"')
dirname = 'yolo_data/'
imgpath = './data/' + dirname + 'images/'
imgpathData = './data/' + dirname + 'image/'
labelpagth = './data/' + dirname + 'label/'
findMinSize = 0.00  #
mImageFile.mkdir(labelpagth)
mImageFile.mkdir(imgpathData)
filelist = mImageFile.getImageFile(imgpath)

count = 0
haveLayout = 0
# 寫入 classes.txt
with open(labelpagth + "classes.txt", "w") as text_file:
    for name in yolotype:
        text_file.write(name + '\n')

for i in tqdm(range(len(filelist))):
    filename = filelist[i]
Beispiel #12
0
class Foodiezz:
    def __init__(self):
        """
        The main class which loads the App config and interacts with the ApiService to retrieve Food truck data.
        This class is also responsible for how the data is printed on the console.
        """
        self.display_message(
            "===============================| Foodiezz |===============================\n"
        )
        self.display_message("Hello! Welcome to Foodiezz!")
        # load the AppConfig
        config = AppConfig()
        self.socrata_dataset_id = config.socrata_dataset_id
        self.page_limit = config.page_limit
        # initialize the the ApiService object
        self.api_service = ApiService(config.socrata_domain, config.app_token)
        self.foodtruck_dataset = {}
        # initializing PrettyTable object with 'Name' and 'Address' as the header
        # I am using PrettyTable to print the final output in an organized and structured way on the console.
        self.foodtruck_table = PrettyTable(field_names=['Name', 'Address'])
        self.foodtruck_table.min_width = 60
        self.total_foodtrucks_open = 0

    def search(self, time_now=datetime.now()):
        """
        This method takes datetime object and searches all the Food trucks that are open at the time that is passed
        as argument. If no value is passed then it takes the current time as default.
        :param time_now: Python datetime object. Default value is current time
        :return: None
        """
        # getting day of the week. this is used to filter the 'dayorder' field in Socrata data
        current_day_order = time_now.isoweekday()
        # formatting time stamp into HH:MM format. this will be used as a filter out food trucks whose start and end
        # time do not contain current timestamp
        time_str = "'{}'".format(time_now.strftime('%H:%M'))
        self.display_message("\nTime is: {}".format(time_now.strftime("%c")))
        try:
            # initialize Halo spinner object to display spinner in console while we fetch data from the SODA API
            spinner = Halo()
            spinner.start("Finding food trucks for you...")
            # here the query is selecting 'applicant', 'location', 'start24', 'end24', 'dayorder', 'dayofweekstr' only
            # it is also filtering the result where 'start24' of the food truck data is less than the current time and
            # 'end24' is greater than equal to current time (start24 <= time_str <= end24). It is also filtering the
            # result by the day of the week by specifying dayorder=current_day_order. And finally it orders the result
            # in ascending order of 'applicant' field which is the name of the Food Truck. I am assuming the 'applicant'
            # field is the name of the Food Truck
            socrata_data = self.api_service.select([
                'applicant', 'location', 'start24', 'end24', 'dayorder',
                'dayofweekstr'
            ]).where(start24__lte=time_str,
                     end24__gte=time_str,
                     dayorder=current_day_order).order_by('applicant').query(
                         self.socrata_dataset_id)
            # stop and clear the spinner from the console to clean it up before printing the final output
            spinner.stop()
            spinner.clear()
            # parse and convert the response JSON into a List of SocrataData model object
            socrata_data_list = parse_obj_as(List[SocrataData], socrata_data)
            # for some Food trucks, there are multiple entries in the result because of different timings in the day
            # I only need any one out of these. As we are getting already filtered result that fit our criteria from the
            # API, I can sure that all these entries are valid. To remove duplicate I am using a python dictionary where
            # the key is a unique combination of 'applicant' and 'location' field. I am using a dictionary instead of
            # hash set because I want maintain the insertion order of the already sorted result. In Python3, sets don't
            # guarantee insertion order but by default a dictionary is ordered in Python 3.
            for data in socrata_data_list:
                self.foodtruck_dataset[(data.applicant, data.location)] = data
            self.total_foodtrucks_open = len(self.foodtruck_dataset)
            # Once I have the dictionary of the dataset, I am updating the PrettyTable rows with the data
            self.__update_ptable()
        except requests.exceptions.HTTPError as ex:
            logging.error(str(ex))
        except:
            traceback.print_exc()
            logging.error(
                "unhandled exception occurred while searching food trucks")

    def __update_ptable(self):
        """
        Internal method to update data in the PTable object
        :return: None
        """
        # initializing two variables here that will be used to define the minimum width of the columns
        # the minimum width will the length of longest name in the data. By setting the minimum width to the length
        # of the longest name, aligns the console output in one line.
        min_name_len = 0
        min_location_len = 0
        for key in self.foodtruck_dataset:
            name = key[0]
            location = key[1]
            # add name and location to the table object one by one
            self.foodtruck_table.add_row([name, location])
            if len(name) > min_name_len:
                min_name_len = len(name)
            if len(location) > min_location_len:
                min_location_len = len(location)

        if min_name_len > 0 and min_location_len > 0:
            self.foodtruck_table._min_width = {
                "Name": min_name_len,
                "Address": min_location_len
            }
        self.foodtruck_table.align[
            'Name'] = 'l'  # Align the 'Name' column to left
        self.foodtruck_table.align[
            'Address'] = 'r'  # Align the 'Address' column to right

    def print_table(self, paginate=True):
        """
        This method will print the response of the query in the required format.

        :param paginate: True if the output needs to be paginated. False if we want to print all at once
        :return: None
        """
        if self.total_foodtrucks_open > 0:
            self.display_message(
                "\nFound these Food Trucks that are open now:\n")
            if not paginate:
                # display all the results if paginate is False
                self.display_message(
                    self.foodtruck_table.get_string(header=False,
                                                    border=False))
            else:
                # Loop from 0 to total number of records, stepping at page_limit and printing the result to the console
                for i in range(0, self.total_foodtrucks_open, self.page_limit):
                    self.display_message(
                        self.foodtruck_table.get_string(start=i,
                                                        end=i +
                                                        self.page_limit,
                                                        header=False,
                                                        border=False))
                    # Call the __show_prompt() to show prompt on the console.
                    self.__show_prompt(i)
            self.display_message(
                "===============================| {} Food Trucks found |==============================="
                .format(self.total_foodtrucks_open))
        else:
            self.display_message(
                "\nUh-oh! Looks like no Food Truck is open right now!")

    def __show_prompt(self, offset):
        """
        This method will display a prompt on the console asking the user if he/she would like to view more results
        :param offset: starting index of the result. Used to display number of results displayed on the console.
        :return: None
        """
        if offset + self.page_limit < self.total_foodtrucks_open:
            print("\n---------------------------")
            print("Showing {} of {} results.".format(
                offset + self.page_limit, self.total_foodtrucks_open))
            # ask the used if he/she would like to see more results
            input("Press enter to view more...")
            # following print statements are read by the console as Up Arrow action
            # the reason for these statements is to move 4 lines up before the program starts printing the next results
            # this way we have clean list of Food trucks in the output.
            print("\033[A                                   \033[A")
            print("\033[A                                   \033[A")
            print("\033[A                                   \033[A")
            print("\033[A                                   \033[A")

    def done(self):
        """
        This method closes the ApiService session. This method is called before exiting the process.
        :return: None
        """
        self.api_service.close()
        self.display_message("\nThank you for using Foodiezz!!")

    @staticmethod
    def display_message(msg=None):
        """
        Helper method to print message on the console. Idea behind this method is that if required in future it can
        call any api to display the output without changing most of the code.
        :param msg:
        :return:
        """
        print(msg)
Beispiel #13
0
def test_webhook_fires_scenario():
    api_svc = ApiService(ACCESS_TOKEN)

    survey_id = create_survey(api_svc, "test webhook fires", "/surveys")
    webhook_id = create_webhook(api_svc, survey_id, "webhook_two", "/webhooks")
Beispiel #14
0
# using flask_restful 
from flask import Flask, jsonify, request 
from flask_restful import Resource, Api 
from api_service import ApiService
from flask_cors import CORS
import json

app = Flask(__name__) 
CORS(app)
api = Api(app) 
apiService = ApiService()

@app.route('/movie-info',methods=['GET'])
def fetchAllMovieInfo():
	return jsonify(apiService.fetchAllMovieinfo(request.args))


@app.route('/movie-info/<string:movieInfoId>',methods=['GET'])
def fetchSingleMovieInfo(movieInfoId):
	return jsonify(apiService.fetchMovieinfo(movieInfoId))


@app.route('/actors',methods=['GET'])
def fetchActors():
	return jsonify(apiService.fetchAllActorinfo())


@app.route('/writers',methods=['GET'])
def fetchWriters():
	return jsonify(apiService.fetchAllWriterinfo())