GVKun编程网logo

AttributeError: 'tuple' 对象没有属性 'encode' MYsql(此对象没有属性)

1

对于AttributeError:'tuple'对象没有属性'encode'MYsql感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍此对象没有属性,并为您提供关于(h,w)=image.sha

对于AttributeError: 'tuple' 对象没有属性 'encode' MYsql感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍此对象没有属性,并为您提供关于(h, w) = image.shape[:2] AttributeError: 'tuple' 对象没有属性 'shape'、AsyncElasticsearch 客户端不接受与 AWS Elasticsearch 的连接 - AttributeError: 'AWS4Auth' 对象没有属性 'encode'、AttributeError'tuple'对象没有属性'get'、AttributeError: 'AttributeError' 对象没有属性 'To'的有用信息。

本文目录一览:

AttributeError: 'tuple' 对象没有属性 'encode' MYsql(此对象没有属性)

AttributeError: 'tuple' 对象没有属性 'encode' MYsql(此对象没有属性)

如何解决AttributeError: ''tuple'' 对象没有属性 ''encode'' MYsql

所以这是给我错误的代码

  1. mycursor.execute("CREATE TABLE IF NOT EXISTS",str(share_name),"(nickname VARCHAR(255),date VARCHAR(255),bill VARCHAR(255),quantity VARCHAR(255),rate VARCHAR(255),amount(255))")
  2. insert = f"INSERT INTO","(nickname) VALUES (%s)"
  3. val = str(share_nick)
  4. mycursor.execute(insert,val)

p 这是错误

  1. Exception in Tkinter callback
  2. Traceback (most recent call last):
  3. File "C:\\Program Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\\lib\\tkinter\\__init__.py",line 1892,in __call__
  4. return self.func(*args)
  5. File "C:\\Users\\Shourya Kumar.DESKTOP-M2TQLD2\\Desktop\\papa project\\addshare.py",line 36,in submit
  6. mycursor.execute(insert,val)
  7. File "C:\\Users\\Shourya Kumar.DESKTOP-M2TQLD2\\Desktop\\papa project\\venv\\lib\\site-packages\\MysqL\\connector\\cursor.py",line 545,in execute
  8. stmt = operation.encode(self._connection.python_charset)
  9. AttributeError: ''tuple'' object has no attribute ''encode''

第 36 行是这个 mycursor.execute(insert,val)

我刚刚给出了实际上是错误的代码,如果你们需要其余的代码,请告诉我我会上传链接

解决方法

首先你所有的 insert 变量都是元组你没有正确使用格式或 f 字符串

  1. insert = f"INSERT INTO {share_name} (nickname) VALUES (%s)"
  2. mycursor.execute(insert,val)

我正在添加完整的代码

  1. share_name = ''tableName'' # your table name
  2. cursor.execute(f"CREATE TABLE IF NOT EXISTS {share_name} (nickname VARCHAR(255),date VARCHAR(255),bill VARCHAR(255),quantity VARCHAR(255),rate VARCHAR(255),amount varchar(255))") #you don''t have varchar in amount column
  3. insert = f"INSERT INTO {share_name} (nickname) VALUES (%s)" #
  4. cursor.execute(insert,(1,))
  5. cnx.commit() #commit is necessary to perform real insert
  6. cnx.close()

(h, w) = image.shape[:2] AttributeError: 'tuple' 对象没有属性 'shape'

(h, w) = image.shape[:2] AttributeError: 'tuple' 对象没有属性 'shape'

如何解决(h, w) = image.shape[:2] AttributeError: ''tuple'' 对象没有属性 ''shape''

我一直在尝试实现用于对象跟踪的 OpenCv CSRT 算法。下面是代码。

  1. from imutils.video import VideoStream
  2. from imutils.video import FPS
  3. import argparse
  4. import imutils
  5. import time
  6. import cv2
  7. file1 = ''traffic.mp4''
  8. tracker = cv2.TrackerCSRT_create()
  9. initBB = None
  10. vs = cv2.VideoCapture(file1)
  11. fps = None
  12. while True:
  13. frame = vs.read()
  14. if frame is None:
  15. break
  16. frame = imutils.resize(frame,width=500)
  17. (H,W) = frame.shape[:2]
  18. if initBB is not None:
  19. (success,Box) = tracker.update(frame)
  20. if success:
  21. (x,y,w,h) = [int(v) for v in Box]
  22. cv2.rectangle(frame,(x,y),(x + w,y + h),(0,255,0),2)
  23. fps.update()
  24. fps.stop()
  25. info = [
  26. ("Tracker","CSRT"),("Success","Yes" if success else "No"),("FPS","{:.2f}".format(fps.fps())),]
  27. for (i,(k,v)) in enumerate(info):
  28. text = "{}: {}".format(k,v)
  29. cv2.putText(frame,text,(10,H - ((i * 20) + 20)),cv2.FONT_HERShey_SIMPLEX,0.6,255),2)
  30. cv2.imshow("Frame",frame)
  31. key = cv2.waitKey(1) & 0xFF
  32. if key == ord("s"):
  33. initBB = cv2.selectROI("Frame",frame,fromCenter=False,showCrosshair=True)
  34. tracker.init(frame,initBB)
  35. fps = FPS().start()
  36. elif key == ord("q"):
  37. break
  38. vs.release()
  39. cv2.destroyAllWindows()

我从 https://www.pyimagesearch.com/ 获得了代码。但是除了从命令行运行之外,他们还实现了网络摄像头和视频捕获选项的代码。但我只是想在我的 IDLE 中运行视频捕获选项。所以我修改了一些以在 IDLE 中运行。但是当我运行它时,我收到以下错误

  1. line 20,in <module> frame = imutils.resize(frame,width=500)
  2. File "C:\\python37\\lib\\site-packages\\imutils\\convenience.py",line 69,in resize
  3. (h,w) = image.shape[:2]
  4. AttributeError: ''tuple'' object has no attribute ''shape''

能否请您指出正确的方向。

解决方法

函数 .read() 返回一个布尔值 (True/False) 和一个框架(数组)。如果该帧被正确读取,它将是 True。因此,您应该将 frame = vs.read() 更改为 _,frame = vs.read(),如下所示(如果没有其他错误,我希望它可以正常工作):

  1. ...
  2. while True:
  3. _,frame = vs.read()
  4. frame = imutils.resize(frame,width=500)
  5. (H,W) = frame.shape[:2]
  6. ...

AsyncElasticsearch 客户端不接受与 AWS Elasticsearch 的连接 - AttributeError: 'AWS4Auth' 对象没有属性 'encode'

AsyncElasticsearch 客户端不接受与 AWS Elasticsearch 的连接 - AttributeError: 'AWS4Auth' 对象没有属性 'encode'

如何解决AsyncElasticsearch 客户端不接受与 AWS Elasticsearch 的连接 - AttributeError: ''AWS4Auth'' 对象没有属性 ''encode''

我在我的项目中使用 AWS Elasticsearch 和 async elasticsearch-py 包来连接集群。

AWS Elasticsearch 版本 7.9

Python 包elasticsearch[async]==7.12.0

我无法使用 AWS4Auth 库(在官方 AWS ES 客户端 Python 文档中提到)初始化异步 Elasticsearch 客户端

它应该成功连接到客户端。但是,它给了我这个错误:

  1. AttributeError: ''AWS4Auth'' object has no attribute ''encode''

分享我的代码片段:

  1. from elasticsearch import AsyncElasticsearch,AIOhttpconnection
  2. from requests_aws4auth import AWS4Auth
  3. import asyncio
  4. host = ''my-test-domain.us-east-1.es.amazonaws.com''
  5. region = ''us-east-1''
  6. service = ''es''
  7. credentials = {
  8. ''access_key'': "MY_ACCESS_KEY",''secret_key'': "MY_SECRET_KEY"
  9. }
  10. awsauth = AWS4Auth(credentials[''access_key''],credentials[''secret_key''],region,service)
  11. es = AsyncElasticsearch(
  12. hosts=[{''host'': host,''port'': 443}],http_auth=awsauth,use_ssl=True,verify_certs=True,connection_class=AIOhttpconnection
  13. )
  14. async def test():
  15. print(await es.info())
  16. asyncio.run(test())

解决方法

我认为使用 AWS4Auth,您将绑定到 RequestsHttpConnection。

默认的连接类是基于urllib3的,比较多 比可选的基于请求的类性能和轻量级。 如果您需要任何请求,请仅使用 RequestsHttpConnection 高级功能,如自定义身份验证插件等。

来自https://elasticsearch-py.readthedocs.io/en/master/transports.html

试试:

  1. es = AsyncElasticsearch(
  2. hosts=[{''host'': host,''port'': 443}],http_auth=awsauth,use_ssl=True,verify_certs=True,connection_class=RequestsHttpConnection
  3. )

或非异步版本,如果上面的代码不起作用:

  1. es = Elasticsearch(
  2. hosts=[{''host'': host,connection_class=RequestsHttpConnection
  3. )

AttributeError'tuple'对象没有属性'get'

AttributeError'tuple'对象没有属性'get'

我有一个Django应用程序。但是我不能为自己已经苦苦挣扎了一段时间而犯下的错误。

Exception Value: ''tuple'' object has no attribute ''get''Exception Location: /Library/Python/2.7/site-packages/django/middleware/clickjacking.py in process_response, line 30

这就是Django提供给我的回溯。

Traceback:File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response201.                 response = middleware_method(request, response)File "/Library/Python/2.7/site-packages/django/middleware/clickjacking.py" in process_response30.         if response.get(''X-Frame-Options'', None) is not None:

我很难弄清楚为什么会发生此错误。我如何找出tuple代码中的位置?

风景:

def products(request, category=None, gender=None, retailer_pk=None, brand_pk=None):    # If the request it doesn''t have a referer use the full path of the url instead.    if not request.META.get("HTTP_REFERER", None):        referer = request.get_full_path()    else:        referer = request.META.get("HTTP_REFERER")    if gender:        products = ProductSlave.objects.filter(Q(productmatch__stockitem__stock__gt=0) &                                               Q(productmatch__slave_product__master_product__gender=gender)).distinct()    elif brand_pk:        products = ProductSlave.objects.filter(Q(master_product__brand__pk=brand_pk))        brand = Brand.objects.get(pk=brand_pk)    elif retailer_pk:        retailer = Retailer.objects.get(pk=retailer_pk)        products = retailer.productmatch_set.all()    else:        products = ProductSlave.objects.filter(Q(productmatch__stockitem__stock__gt=0))    if not retailer_pk:        filt = create_filtering(productslaves=products, request=request)    elif retailer_pk:        filt = create_filtering(productmatches=products, request=request)    sorting_selected = request.GET.get("sorter", None)    # q_list is used to store all the Q''s    # Then they are reduced. And then filtered    if "brand" in request.GET:        brand_filtering = request.GET.get("brand", None)        if brand_filtering:            brand_filtering = brand_filtering.split("|")        q_list = []        for filter in brand_filtering:            if retailer_pk:                q_list.append(Q(slave_product__master_product__brand__slug=filter))            else:                q_list.append(Q(master_product__brand__slug=filter))        reduced_q = reduce(operator.or_, q_list)        products = products.filter(reduced_q)    if "kategori" in request.GET:        category_filtering = request.GET.get("kategori", None)        if category_filtering:            category_filtering = category_filtering.split("|")        q_list = []        for filter in category_filtering:            if retailer_pk:                q_list.append(Q(slave_product__master_product__product_category__slug=filter))            else:                q_list.append(Q(master_product__product_category__slug=filter))        reduced_q = reduce(operator.or_, q_list)        products = products.filter(reduced_q)    if "stoerrelse" in request.GET:        size_filtering = request.GET.get("stoerrelse", None)        if size_filtering:            size_filtering = size_filtering.split("|")        q_list = []        for filter in size_filtering:            if retailer_pk:                q_list.append(Q(slave_product__productmatch__stockitem__size__pk=filter))            else:                q_list.append(Q(productmatch__stockitem__size__pk=filter))        reduced_q = reduce(operator.or_, q_list)        products = products.filter(reduced_q)    if "farve" in request.GET:        color_filtering = request.GET.get("farve", None)        if color_filtering:            color_filtering = color_filtering.split("|")        q_list = []        for filter in color_filtering:            if retailer_pk:                q_list.append(Q(slave_product__sorting_color__slug=filter))            else:                q_list.append(Q(sorting_color__slug=filter))        reduced_q = reduce(operator.or_, q_list)        products = products.filter(reduced_q)    if "pris" in request.GET:        price_filtering = request.GET.get("pris", None)        if price_filtering:            price_filtering = price_filtering.split("|")        q_list = []        if retailer_pk:            q_list.append(Q(price__gte=price_filtering[0]))            q_list.append(Q(price__lte=price_filtering[1]))        else:            q_list.append(Q(productmatch__price__gte=price_filtering[0]))            q_list.append(Q(productmatch__price__lte=price_filtering[1]))        reduced_q = reduce(operator.and_, q_list)        products = products.filter(reduced_q)    if sorting_selected:        if sorting_selected == filt["sorting"][0]["name"]:            filt["sorting"][0]["active"] = True            if retailer_pk:                products = products.annotate().order_by("-price")            else:                products = products.annotate().order_by("-productmatch__price")        elif sorting_selected == filt["sorting"][1]["name"]:            if retailer_pk:                products = products.annotate().order_by("price")            else:                products = products.annotate().order_by("productmatch__price")            filt["sorting"][1]["active"] = True        elif sorting_selected == filt["sorting"][2]["name"]:            filt["sorting"][2]["active"] = True            if retailer_pk:                products = products.order_by("pk")            else:                products = products.order_by("pk")        else:            if retailer_pk:                products = products.order_by("pk")            else:                products = products.order_by("pk")    else:        if retailer_pk:            products = products.order_by("pk")        else:            products = products.order_by("pk")    if brand_pk:        return render(request, ''page-brand-single.html'', {            ''products'': products,            "sorting": filt["sorting"],            "filtering": filt["filtering"],            "brand": brand,        })    elif retailer_pk:        return (request, ''page-retailer-single.html'', {            "products": products,            "sorting": filt["sorting"],            "filtering": filt["filtering"],            "retailer": retailer,        })    else:        return render(request, ''page-product-list.html'', {            ''products'': products,            "sorting": filt["sorting"],            "filtering": filt["filtering"]        })

答案1

小编典典

您将在这里返回元组:

elif retailer_pk:    return (request, ''page-retailer-single.html'', {        "products": products,        "sorting": filt["sorting"],        "filtering": filt["filtering"],        "retailer": retailer,    })

您是否忘了在render此处添加:

elif retailer_pk:    return render(request, ''page-retailer-single.html'', {        "products": products,        "sorting": filt["sorting"],        "filtering": filt["filtering"],        "retailer": retailer,    })

AttributeError: 'AttributeError' 对象没有属性 'To'

AttributeError: 'AttributeError' 对象没有属性 'To'

如何解决AttributeError: ''AttributeError'' 对象没有属性 ''To''

我正在尝试使用 python Jupyter notebook 探索 enron 电子邮件数据集。但我收到此属性错误。我正在尝试阅读电子邮件并将它们转换为 csv 格式,以便我可以进一步应用 Ml 进行情感分析。 导入 tarfile 进口重新 从日期时间导入日期时间 从集合导入namedtuple,计数器 将熊猫导入为 pd 将 altair 导入为 alt

tar =tarfile.open(r"C:\\Users\\nikip\\Documents\\2021\\Interview Preparation\\sentiment analysis\\enron_mail_20150507.tar.gz","r")
items = tar.getmembers()
Email = namedtuple(''Email'',''Date,From,To,Subject,Cc,Bcc,Message'')

def get_msg(item_number):
    f = tar.extractfile(items[item_number])
    try:
        date = from_ = to = subject = cc= bcc = message= ''''
        in_to = False
        in_message = False
        to = []
        message = []
        item = f.read().decode()
        item = item.replace(''\\r'','''').replace(''\\t'','''')
        lines = item.split(''\\n'')
        
        for num,line in enumerate(lines):
            if line.startswith(''Date:'') and not date:
                date = datetime.strptime('' ''.join(line.split(''Date: '')[1].split()[:-2]),''%a,%d %b %Y %H:%M:%s'')
            elif line.startswith(''From:'') and not from_:
                from_ = line.replace(''From:'','''').strip()                
            elif line.startswith(''To:'')and not to:
                in_to = True
                to = line.replace(''To:'','''').replace('','','''').split()                
            elif line.startswith(''Subject:'') and not subject:
                in_to = False
                subject = line.replace(''Subject:'','''').strip()                
            elif line.startswith(''Cc:'') and not cc:
                cc = line.replace(''Cc:'','''').split()                
            elif line.startswith(''Bcc:'') and not bcc:
                bcc = line.replace(''Bcc:'','''').split()                
            elif in_to:
                to.extend(line.replace('','''').split())                
            elif line.statswith(''Subject:'') and not subject:
                in_to =False                
            elif line.startswith(''X-FileName''):
                in_message = True                
            elif in_message:
                message.append(line)
        
        to = ''; ''.join(to).strip()
        cc = ''; ''.join(cc).strip()
        bcc = ''; ''.join(bcc).strip()
        message = '' ''.join(message).strip()
        email = Email(date,from_,to,subject,cc,bcc,message)
        return email
    
    except Exception as e:
        return e

msg = get_msg(3002)
msg.date

我收到如下错误消息:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-11-e1439579a8e7> in <module>
----> 1 msg.To

AttributeError: ''AttributeError'' object has no attribute ''To''

有人可以帮忙吗?提前致谢

解决方法

问题是您在 get_msg 函数中返回了一个异常,大致如下所示:

def get_msg(item_number):
  try:
    ...do some stuff...
  except Exception as e:
    return e

看起来您在代码中的某处触发了 AttributeError 异常,并且您返回的是该异常,而不是 Email 对象。

您几乎不希望有一个 except 语句来抑制所有类似的异常,因为它会隐藏您的代码中的错误(正如我们在这里看到的)。捕获特定异常通常是更好的做法,或者如果您的代码尽管出现异常仍会继续,则至少记录错误。

作为第一步,我建议删除整个 try/except 块并让您的代码在没有它的情况下工作。

今天关于AttributeError: 'tuple' 对象没有属性 'encode' MYsql此对象没有属性的分享就到这里,希望大家有所收获,若想了解更多关于(h, w) = image.shape[:2] AttributeError: 'tuple' 对象没有属性 'shape'、AsyncElasticsearch 客户端不接受与 AWS Elasticsearch 的连接 - AttributeError: 'AWS4Auth' 对象没有属性 'encode'、AttributeError'tuple'对象没有属性'get'、AttributeError: 'AttributeError' 对象没有属性 'To'等相关知识,可以在本站进行查询。

本文标签: