首页 > 解决方案 > 如何在 Django Views 中的另一个函数中使用一个函数中的变量

问题描述

我有 2 个功能:

1 函数检查方案的 URL:

def checkurl(self):
    if request.method == 'POST' and 'url' in request.POST:
        url = request.POST.get('url', '')
        if not url.startswith('http://') and not url.startswith('https://'):
            url = "https://" + url
    return url

2 函数应该使用 url 变量。但它说“名称'url'未定义”。这是第二个功能:

def tests(request):

    ##################################################
    # URL Parse: netloc, scheme
    ##################################################

    x = datetime.datetime.now()
    time = x.strftime("%Y-%m-%d-%H-%M-%S")

    if request.method == 'POST' and 'url' in request.POST:
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}#headers

        # Set Width and Height

        width_get = request.POST.get('width', '')
        height_get = request.POST.get('height', '')
        if width_get is not None and width_get != '':
            width = width_get
        else:
            width = 1600
        if height_get is not None and height_get != '':
            height = height_get
        else:
            height = 1000

        if url is not None and url != '':

            url_parsed = urlparse(url)
            scheme = url_parsed.scheme
            netloc = url_parsed.netloc
            if netloc.startswith('www.'):
                netloc = netloc.replace('www.', '')
            image_path = "media/" + netloc + "-" + time + ".png"
            shot_path = "/media/" + netloc + "-" + time + ".png"
            path = "C:/WebDrivers/chromedriver.exe"
            driver = webdriver.Chrome(path)
            driver.get(url)
            driver.set_window_size(width, height)
            driver.save_screenshot(image_path)
            screenshot = image_path
            driver.quit()
            var_dict = {
                'screenshot': screenshot,
                'shot_path':shot_path,
                'netloc':netloc,
                }
            return render(request, 'apptests/shots.html', var_dict)
    else:
        return render(request, 'apptests/shots.html')

如何在第二个函数中使用第一个函数中的 URL 变量?

标签: pythondjango

解决方案


看起来你没有打电话checkurl,所以当你打电话时if url is not None and url != '':,变量url还没有定义。

你只需要url = checkurl()在我认为的那一行之前添加。

但是,您将需要传递request给该函数,而不是self据我所知,从您发布的代码中可以看出,这checkurl似乎不是类上的方法,并且您正在使用基于函数的视图作为tests视图.

所以,checkurl将是:

def checkurl(request):
    if request.method == 'POST' and 'url' in request.POST:
        url = request.POST.get('url', '')
        if not url.startswith('http://') and not url.startswith('https://'):
            url = "https://" + url
        return url

注意我已经缩进了return url. url只有当我们有一个时才会返回。在您当前的checkurl函数中,如果if request.method == 'POST' and 'url' in request.POST:为 false,您将尝试返回一个不存在的变量(它仅在该 if 语句的范围内定义)。None因此,如果不满足该条件,现在该函数将返回。

然后你只需要将该函数导入到你的文件中(如果它在一个单独的文件中),并在该语句views.py上方调用它:if

url = checkurl(request)

if url is not None and url != '':
    ...

推荐阅读