改善 Python 脚本中的条件

问题描述 投票:0回答:1

我正在使用 PySimpleGUI 用 Python 编写脚本,但是我面临着如何在单击按钮时实现条件的问题。

当点击“生成代理”按钮时,首先需要验证是否有有效的令牌,如果令牌无效或没有令牌,则应该完成迭代。但是,我不能在其中使用 return,因为它不是一个函数,我尝试在 check_token() 和 check_country() 中定义来条件,但是,而不是如何正确实现它。

考虑到在检查国家/地区和其他元素(作为计数器)之前执行按钮需要有效令牌的逻辑,是否有任何方法可以停止按钮迭代,以允许用户获取令牌,或者更正国家/地区或其他元素的字段其他人,在工作流程中检查所有“如果”之前?怎样才是最好的方法呢?

(尝试检查ChatGPT,建议在按钮的工作流程中使用return或break。没有什么帮助,因为[1]return仅在函数中使用,[2]break将在运行时关闭整个应用程序。 )

我尝试直接在按钮中实现条件,但是,为了尝试返回按钮,我编写了两个函数来帮助我获取信息。恐怕我没有正确从函数中检索布尔值以将其用作条件中的参考。

[PySimpleGUI 按钮]

elif event == "Generate Proxy": 
output_element = window['output'] 
proxy_list_element = window['proxy_list']

timestamp = app.log_time_stamp()
output_element.update(f"[{timestamp}] 'Generate Proxy' clicked\n", append=True)

country = values['country'].upper()
region = values['region']
city = values['city']
count = values['count']

# CONDITIONS
    if not check_token(token):
        print("Output inválido. Culpa do token que não existe. TEstando break.")
        break
    
    if check_country(country):
        pass
    
    if not region or not city:
        sleep(2)
        output_element.update(f"[{timestamp}] City and region are both optional fields. You don't need to define it.\n", append=True)
        pass
    
    if not count or not count.isdigit():
        sleep(2)
        output_element.update(f"[{timestamp}] The 'Count' field is empty. Please, provide the number of proxy that you want in your list.\n", append=True)
        sleep(2)
        # break
    
    else:
        sleep(2)
        output_element.update(f"[{timestamp}] The Count is: {count}.\n", append=True)
    
    try:
        if values['sticky_session'] == 'Keep IP as long as possible':
            session_type = 'sticky'
    
        else:
            session_type = 'custom'
    
        protocol = 'socks5' if values['SOCKS5'] else 'HTTP'
        sleep(2)
    
        output_element.update(f"[{timestamp}] The request is: Country: {country}, Region: {region}, City: {city}, Sticky Session: {session_type}, Protocol: {protocol}, Count: {count}.\n", append=True)
        sleep(2)
        output_element.update(f"[{timestamp}] Sending the request... Please wait.\n", append=True)
        sleep(2)
    
        proxy_list = mlx.get_proxy(
            country, region, city, session_type, protocol, count)
    
        for proxy in proxy_list:
            proxy_list_element.update(f"{proxy}\n")
    
    except Exception as e:
        sg.Print("Log window initialized...", do_not_reroute_stdout=False)
        sg.Print(f"An error ocurred: {e}.\n")
        sg.Print(traceback.format_exc())`

[检查令牌]

def check_token(token):output_element = window['output']timestamp = mlx.log_time_stamp()

    if not token:
        output_element.update(f"[{timestamp}] You must use your username and password in order to GET TOKEN first.\n", append=True)
        sleep(1)
        output_element.update(f"[{timestamp}] It's not possible to proceed without a token. Cancelling the request.\n", append=True)
        sleep(1)
        output_element.update(f"[{timestamp}] Try again.\n", append=True)
        return False
    
output_element.update(f"[{timestamp}] There is a valid token. Starting the request.\n", append=True)
return True

[check_country() 函数)]

def check_country(country): 
output_element = window['output'] 
timestamp = mlx.log_time_stamp()

    if not country: 
        sleep(2) 
        output_element.update(f"[{timestamp}] [ERROR] Please, insert a country in Country Field. It's a required field. You need to use ISO 3166-1 alpha-2 format (e.g. US, FR, BR).\n", append=True)
        sleep(1)
        return
    
    if len(country) != 2 or country not in iso_country_codes: 
        sleep(2) 
        sg.Print("[ERRORRROROROR] The country inserted in the field isn't a valid country.\n", append=True) sg.Print(traceback.format_exc())
        output_element.update(f"[{timestamp}] The {country} is not a valid value for country. You need to use ISO 3166-1 alpha-2 format (e.g. US, FR, BR).\n", append=True)
        sleep(1)
        return

sleep(2)
output_element.update(f"[{timestamp}] {country} is valid. Proceeding with the request\n", append=True) sleep(1)
return True

我在期待什么?

当点击“生成代理”按钮时,它会验证是否有有效的令牌。如果没有,它会停止按钮以允许用户生成令牌。如果有有效的令牌,它将检查国家、地区、城市、会话、协议和计数。 Session 和 Protocol 已经有默认值,而 Region 和 City 不是强制性的。令牌、国家/地区和计数是强制性的(用户提供),以在 API 请求中发送以获得响应(它将显示在多行元素“proxy_list”中。

python conditional-statements pysimplegui
1个回答
0
投票

不确定问题到底是什么,所以在这里简单回答一下。

def valid_token(token):
    return True

def valid_args(*args):
    return True, args

while True:

    event, values = window.read()

    if event == sg.WIN_CLOSE():
        break
    elif event == "Generate Proxy":
        token = values["token"]
        args = (values[key] for key in ("country", "region", "city", "session", "protocol", "count"))
        if not valid_token(token):
            continue                        # "conitnue" here, not "break"
        valid, args = valid_args(*args)
        if valid:
            response = request(*args)

window.close()
© www.soinside.com 2019 - 2024. All rights reserved.