Search code examples
pythonvariablesrefreshgloballocal

Use a local variable in a request


I try to import proxies in my code.

I tried t oselect a random proxy in my request but I didn't get there

This is my code (python)

import random
import requests

#create global variable to use in proxy_slct
rdmproxy = "1.1.1.1:1"

#get proxies from file + randomize and select
def proxy_slct():
    global rdmproxy
    threading.Timer(5.0, proxytimer).start()
    proxy_file = open('proxies.txt').read().splitlines()
    rdmproxy = random.choice(proxy_file)
    f.close()
proxytimer()

#request
try:
    login = requests.get("https://httpbin.org/ip", proxies=rdmproxy, timeout=5)
    print(login.json())

Solution

  • Why do you define rmdproxy at the top of your code and then overwrite it?

    Try with this:

    import random
    import requests
    
    def proxy_slct():
        global rdmproxy
        threading.Timer(5.0, proxytimer).start()
        with open('proxies.txt') as file:
            proxy_file = file.read().splitlines()
            rdmproxy = random.choice(proxy_file)
    proxytimer()
    
    try:
        login = requests.get("https://httpbin.org/ip", proxies=rdmproxy, timeout=5)
        print(login.json())
    

    As you can see you didin't initialize rmdproxy on the global scope but in the local scope with the keyword global, the you assign a random value to that variable.

    Also try to print that variable so you could see if its value is what you want it to be.