【问题标题】:module 'http.client' has no attribute 'HTTPSConnection' when I run it in VSCode当我在 VSCode 中运行模块“http.client”时,它没有属性“HTTPSConnection”
【发布时间】:2021-09-30 13:01:52
【问题描述】:

我正在尝试在 VSCode 中使用 Python 进行 Microsoft AI-102-AIEngineer 的文本分析的实验室练习。但我得到了错误

模块“http.client”没有属性“HTTPSConnection”

当我从我的 VSCode 编辑器运行代码时。我正确配置了我的密钥和端点。代码在这里:

from dotenv import load_dotenv
import os
import http.client, base64, json, urllib
from urllib import request, parse, error

def main():
    global cog_endpoint
    global cog_key

    try:
        # Get Configuration Settings
        load_dotenv()
        cog_endpoint = os.getenv('COG_SERVICE_ENDPOINT')
        cog_key = os.getenv('COG_SERVICE_KEY')

        # Get user input (until they enter "quit")
        userText =''
        while userText.lower() != 'quit':
            userText = input('Enter some text ("quit" to stop)\n')
            if userText.lower() != 'quit':
                GetLanguage(userText)


    except Exception as ex:
        print(ex)

def GetLanguage(text):
    try:
        # Construct the JSON request body (a collection of documents, each with an ID and text)
        jsonBody = {
            "documents":[
                {"id": 1,
                 "text": text}
            ]
        }

        # Let's take a look at the JSON we'll send to the service
        print(json.dumps(jsonBody, indent=2))

        # Make an HTTP request to the REST interface
        uri = cog_endpoint.rstrip('/').replace('https://', '')
        conn = http.client.HTTPSConnection(uri)

        # Add the authentication key to the request header
        headers = {
            'Content-Type': 'application/json',
            'Ocp-Apim-Subscription-Key': cog_key
        }

        # Use the Text Analytics language API
        conn.request("POST", "/text/analytics/v3.0/languages?", str(jsonBody).encode('utf-8'), headers)

        # Send the request
        response = conn.getresponse()
        data = response.read().decode("UTF-8")

        # If the call was successful, get the response
        if response.status == 200:

            # Display the JSON response in full (just so we can see it)
            results = json.loads(data)
            print(json.dumps(results, indent=2))

            # Extract the detected language name for each document
            for document in results["documents"]:
                print("\nLanguage:", document["detectedLanguage"]["name"])

        else:
            # Something went wrong, write the whole response
            print(data)

        conn.close()


    except Exception as ex:
        print(ex)


if __name__ == "__main__":
    main()

【问题讨论】:

    标签: python-3.x https


    【解决方案1】:

    确保/usr/local/lib/python3.8/http/client.py 存在。

    在交互式 python 控制台中,测试:

    >>> import http.client
    >>> http.client.HTTPConnection('www.python.org')
    <http.client.HTTPConnection object at 0x106a9f5f8>
    
    >>> http.client.HTTPSConnection('www.python.org')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: module 'http.client' has no attribute 'HTTPSConnection'
    

    同时检查 SSL:

    >>> import _ssl
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ImportError: dlopen(/Users/ishandutta2007/.pyenv/versions/3.5.4/lib/python3.5/lib-dynload/_ssl.cpython-35m-darwin.so, 2): Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib
      Referenced from: /Users/ishandutta2007/.pyenv/versions/3.5.4/lib/python3.5/lib-dynload/_ssl.cpython-35m-darwin.so
      Reason: image not found
    

    这取决于您的操作系统。

    例如,在 MacOS 上,来自this issue

    更新 OpenSSL 通常没问题,从 libssl.1.0.0.dylib 跳转到 libssl.1.1.dylib 极为罕见。
    dylib 版本号 1.0.0 多年来一直相同。

    但是,当它确实发生变化并且您删除旧的时,依赖于它的所有内容都会损坏(Homebrew 可以尽最大努力确保其包全部重新编译,但它对您的 pyenv Python 无能为力安装)。

    这也不是 OpenSSL 独有的,只是动态链接的本质。
    如果有一天libsqlite3.0.dylib 变成libsqlite4.0.dylib,你的旧 Python 安装也会中断。

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      • 1970-01-01
      • 2017-08-11
      相关资源
      最近更新 更多