python - 如何在 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 变量?
解决方案
看起来你没有打电话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 != '':
...
推荐阅读
- css - 将gridview标题中的垂直文本与窄列对齐
- python - 求二叉树高度的实用函数 - 寻找解释
- python - 在 VS Code 工作区中修改 python 路径
- android - 存储用户输入的数据有多难?
- python - Python函数重构
- docker - 如何更改 Pgadmin4 Docker 映像中的默认导入/导出目录
- sql - SQL:计算表中所有列的缺失百分比
- c++ - 在 C++20 视图管道中调用了两次生成器
- node.js - nodejs express - mssql - 在同一响应中返回两个记录集
- android - 使用 ContentResolver 查询 DocumentsContract Uri 时,如何检查是否可以读取文档?