简体   繁体   English

python django,如何禁止从for循环转到下一个代码

[英]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. 此代码检查scheme + some url的响应。

But when I execute the code, my Django terminal prints: 但是,当我执行代码时,我的Django终端会打印:

 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. 我认为这意味着在此行前面return JsonResponse({'res': 1}) ,在此行之后或之后返回print("Tested: " + str(r.status_code))

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. 我了解到Python代码是从上到下逐行执行的,但是似乎并没有这样做。

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() 我试图使用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. 200为成功,并且重定向到成功页面。 Then it runs your last loop. 然后它运行您的最后一个循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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