Django使用dnspython查询域名IP报AttributeError错误求助
错误原因排查
- 首先是请求逻辑缺失:首次访问根路径是GET请求,此时POST参数为空,
request.POST.get('search')会返回None,把None传入dns解析方法就会触发空属性报错。 - 其次是dnspython API调用错误:
resolve是Resolver类的实例方法,初始代码直接调用类的静态方法属于误用;更新后的代码虽然实例化了Resolver,但没有处理search为None的场景,同样会触发报错。 - 另外存在冗余无效导入:
import dnspython as dns是多余导入,dnspython库标准导入仅需import dns.resolver即可,多余导入可能导致命名冲突。 - 最后是解析结果处理错误:dns.resolver返回的Answer实例不能直接在模板渲染,需要提取其中的IP地址字符串。
修正后的代码
views.py
from django.shortcuts import render import dns.resolver from dns.exception import DNSException def index(request): ip_address = "" # 仅当POST请求且有合法search参数时执行解析 if request.method == "POST": search = request.POST.get('search', '').strip() if search: try: # 调用默认解析器的resolve方法即可 answers = dns.resolver.resolve(search, "A") # 提取所有解析到的IP,用逗号拼接 ip_address = ','.join([rdata.address for rdata in answers]) except DNSException as e: ip_address = f"解析失败:{str(e)}" context = {"ip_address": ip_address} return render(request, 'index.html', context)
index.html优化说明
当前HTML存在嵌套form的不规范问题,外层的查询form里嵌套了上传文件的form,不符合HTML规范,需要把上传文件的form移到外层查询form的外面:
{% extends 'base.html' %} {% block title %} IP Finder {% endblock %} {% block body %} <div class="container"> <br> <br> <center> <h1 style="font-family:'Courier New'">Django NSLookup</h1> <br> <br> <!-- 域名查询form --> <form action="{% url 'index' %}" method="post"> {% csrf_token %} <div class="form-group"> <label> <input type="text" class="form-control" name="search" placeholder="Enter website"> </label> </div> <input type="submit" class="btn btn-primary" value="Search"> </form> <br> <p>Click on the "Choose File" button to upload a file:</p> <!-- 上传文件form移到外层 --> <form action="/action_page.php"> <input type="file" id="myFile" name="filename"> <input type="submit"> </form> </center> <br> <br> {% if ip_address %} <p>IP Address is : {{ip_address}}</p> {% endif %} </div> {% endblock %}
内容的提问来源于stack exchange,提问作者user13121564
相关产品推荐
相关产品推荐

