简体   繁体   中英

python django, How to prohibit go to the next code from for loop

def redirectTest(item):
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
        }
        r = None
        try:
            r = requests.head(item, allow_redirects=False, headers=headers)
        except Exception as e:
            print(e)
        if r is not None:
            if r.status_code == 301:
                print("Tested: " + str(r.status_code))
            elif r.status_code == 302:
                print("Tested: " + str(r.status_code))
            else:
                print("Tested: " + str(r.status_code))
    except requests.exceptions.RequestException as e:
        print('error: ' + e)
    return

@ensure_csrf_cookie
def re_check_url(request):
    if request.method == "POST":
        if request.is_ajax():
            resolved_urls = ['twitch.tv/yumyumyu77']
            scheme_list = ['http://www.', 'http://', 'https://www.', 'https://']

            for item in resolved_urls:
                for scheme_item in scheme_list:
                    redirectTest(scheme_item + item)
            return JsonResponse({'res': 1})
        return JsonResponse({'res': 2})

This code checks scheme + some url 's responses.

But when I execute the code, my Django terminal prints:

 r_status_code: 301
 r_status_code: 301
 r_status_code: 200
[22/Oct/2018 23:54:49] "POST /re/check/url/ HTTP/1.1" 200 10
 r_status_code: 301

Problem:

I think it means that return JsonResponse({'res': 1}) this line is ahead, and print("Tested: " + str(r.status_code)) this line is after or later.

Sometimes it prints ordinarily, but sometimes it prints abnormally.

Question:

I learned that Python code is executed line by lines from top to bottom, but It seems like it is not doing so.

Why does this happened? and how can I fix it?

It's executing order is not what I expected.

Edit:

I tried to use Lock()

    for item in resolved_urls:
        for scheme_item in scheme_list:
            from threading import Lock
            _lock = Lock()
            with _lock:
                redirectTest(scheme_item + item)

But It does not seems to be working well.

Everything is actually working correctly. 200 is success, and it redirects to the success page. Then it runs your last loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM