Пример #1
0
    def log(self, exception):
        import time
        from utils.cut_string import cut_string

        if isinstance(exception, BaseException):

            error_message = str(repr(exception))

            type_text = error_message[0:error_message.find("(\"")]
            prompt_text = cut_string(error_message, "(", ")")

            inner_prompts = []

            have_inner_prompts = False

            try:
                inner = prompt_text.split(",")
                for prompt in inner:
                    if len(prompt) > 0:
                        inner_prompts.append(cut_string(prompt, "\"", "\""))
                        have_inner_prompts = True
            except AttributeError:
                inner_prompts.append("[No more data]")

            file_name = "[" + self.logger_name + "] " + time.strftime(
                "%y%m%d[%H]", time.localtime())
            content_to_write = time.strftime(
                "%Y-%m-%d %H:%M:%S",
                time.localtime()) + ": [ " + type_text + " ] "

            if have_inner_prompts:
                for prompt in inner_prompts:
                    content_to_write += prompt + " | "
                content_to_write = content_to_write[0:len(content_to_write) -
                                                    3]

            with open(self._save_location + file_name + ".txt",
                      mode="a") as file:
                print("[Log-Written] " + content_to_write)
                file.writelines(content_to_write)

        else:
            raise AttributeError(
                "Error Type Not Correct! String and Exception are allowed.",
                exception)
Пример #2
0
def analyze_overview(json_data):
    modify_time = int(str(json_data['modifyTime'])[:-3])
    if not last_time == modify_time:
        region = str(json_data['id'])
        image_url = json_data['imgUrl']
        count_describe_text = json_data['countRemark']

        infected = cut_string(count_describe_text, '确诊', '例').strip('\' ')
        sceptical = cut_string(count_describe_text, '疑似', '例').strip('\' ')
        cured = cut_string(count_describe_text, '治愈', '例').strip('\' ')
        death = cut_string(count_describe_text, '死亡', '例').strip('\' ')

        data = (modify_time, infected, death, sceptical, cured, image_url)
        data_str = str(data)

        if not data_equal(data[1:], last_overview_data[1:]):
            db.insert_item_data('data_record', data_str)
        else:
            print('Unchanged')

        return data, modify_time
    return last_overview_data, modify_time
Пример #3
0
def add_url():
    """
    - Add an URL by alias and target
    @param: alias, target
    :return: [0](str)Status code, "OK" -> Ok, "ALIAS_EXIST" -> Error:The alias is exist in the pool,
                                "EMPTY_ALIAS" -> Alias is empty, "EMPTY_TARGET_URL" -> The target url is empty
    """
    alias, target = request.args.get("alias"), request.args.get("target")

    if is_alias_exist(alias):
        return "ALIAS_EXIST"
    else:
        if len(alias) == 0:
            return "EMPTY_ALIAS"
        if len(target) == 0:
            return "EMPTY_TARGET_URL"
        target = str(target)
        if "http://" not in target and "https://" not in target and "ftp://" not in target:
            target = "http://" + target

        params = {"ttl": 7200}

        if alias[0] == "$" and "$RPLNK-" in alias:

            commands = cut_string.cut_string(alias, "$RPLNK-", "$")
            alias = str(alias).replace("$RPLNK-" + commands + "$", "")
            commands = commands.split(",")

            for command in commands:
                command_name, command_data = command.split(":")

                if command_name == "TTL":
                    params["ttl"] = int(command_data)

        # Inner exception values:
        # [0](str)Status code, "OK" -> Ok, "ALIAS_EXIST" -> Error:The alias is exist in the pool

        result = all_urls.add(ShortLink(alias, target, params["ttl"]))
        print("[add_url]" + str(all_urls.get_by_alias(alias)[0]) + " -> " +
              target)
        return result
Пример #4
0
def upload():
    if request.method == 'POST':
        print("[FileUpload]Handling POST")
        try:
            file = request.files['file']
            batch_id = request.values.get("batch_id")
            alias = request.values.get("alias")
        except:
            file = None
            alias = None
            batch_id = None

        if not batch_id or not alias or not file:
            resp = make_response("400")
            resp.headers['Access-Control-Allow-Origin'] = '*'
            return resp

        if len(alias) > 1000:
            resp = json.dumps({"error": "ALIAS_TOO_LONG"})
            return resp

        if file:

            params = {"ttl": 7200}

            if alias[0] == "$" and "$RPLNK-" in alias:

                commands = cut_string.cut_string(alias, "$RPLNK-", "$")
                alias = str(alias).replace("$RPLNK-" + commands + "$", "")
                commands = commands.split(",")

                for command in commands:
                    command_name, command_data = command.split(":")

                    if command_name == "TTL":
                        params["ttl"] = int(command_data)

            print("    [FileUpload]Get BatchID:" + batch_id)
            print("    [FileUpload]Get File:" + file.filename)
            print("    [FileUpload]Alias:" + alias)
            print("    [FileUpload]Params:" + str(params))

            if is_alias_exist(alias):
                print("    ##[FileUpload]AliasExist!")
                resp = json.dumps({"ok": "false", "error": "ALIAS_EXIST"})
            else:

                file.save(get_save_location(file.filename, batch_id))
                f_link_obj = FileLink(alias, batch_id, ttl=params["ttl"])
                all_files.add(f_link_obj)
                print("    [FileUpload]File saved to " +
                      get_save_location(file.filename, batch_id))
                resp = json.dumps({"ok": "true"})

        else:
            resp = json.dumps({"ok": "false", "error": "BAD"})

        resp = make_response(resp)
        resp.headers['Access-Control-Allow-Origin'] = '*'
        return resp

    elif request.method == 'OPTIONS':
        print("[FileUpload]Handling OPTIONS")
        resp = make_response()
        resp.headers['Access-Control-Allow-Origin'] = '*'
        # print("    [FileUpload]" + str(resp))
        return resp

    else:
        resp = make_response(
            json.dumps({
                "ok": "false",
                "error": "503 Server Down"
            }))
        resp.headers['Access-Control-Allow-Origin'] = '*'
        return resp
Пример #5
0
            city_data_fetch = val[0][0]
            if not str(city_data) == str(city_data_fetch):
                # print(str(city_data) + '\n' + str(city_data_fetch))
                db.replace_item_data('data_record_province', data_str)
                print('Province: ', prov, ' modified.')
        elif modify_map[prov]:
            db.insert_item_data('data_record_province', data_str)
            print('Province: ', prov, ' modified.')

        db.commit()


while True:
    skip_flag = False
    content = retry(api_fetch, 2, DXY_URL)
    overview = '{' + cut_string(content, 'window.getStatisticsService = {',
                                '</script>').replace('}catch(e){}', '')
    overview_json = None

    region_stat_json = None
    region_stat = cut_string(content, '<script id="getAreaStat">', '</script>')
    region_stat = '[' + cut_string(region_stat, 'getAreaStat = [', '}catch(e)')

    try:

        overview_json = json.loads(overview)
        last_overview_data, last_time = analyze_overview_updated(overview_json)

    except json.decoder.JSONDecodeError as e:
        print('Overview data fetch error.', e.args)
    except pymysql.err.OperationalError as e:
        print('Overview data saving error. Reconnecting...', e.args)