【问题标题】:How to solve Unable to find the server at www.googleapis.com when not connected to the internet with a Python Application如何解决无法使用 Python 应用程序连接到 Internet 时无法在 www.googleapis.com 上找到服务器
【发布时间】:2019-10-29 09:48:07
【问题描述】:

我有一个桌面应用程序,由 python 制成,可作为独立应用程序运行,无需依赖互联网即可正常运行。仅要连接到 Google Drive,该应用程序才需要互联网连接。

问题在于,在运行应用程序时,当未连接到互联网时,应用程序会崩溃,因为它包含与互联网连接相关的导入语句。

有效的方法: 注释掉与互联网连接相关的导入语句后,应用程序在离线环境中正常执行。

什么不起作用: 当导入语句包含在代码中并且没有互联网连接时,应用程序就会崩溃。下面是一些伪代码。

main.py

from kivy.app import App
'''More import statements'''
....
....
from helper import Hi

class Hello(Hi):
'''Rest of the Code goes here'''
...
...
...

helper.py

'''If the device is not connected to the internet, the following internet import statements throw an error. These imports are needed to connect Google Drive.'''

from __future__ import print_function
import httplib2
import os, io

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient.http import MediaFileUpload, MediaIoBaseDownload
try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None
import auth

class Hi:
pass
'''Rest of the Code goes here'''
...
...
...

预期: 需要一种方法来使应用程序即使在没有互联网连接的情况下也能正常运行。如果没有互联网连接,请警告用户连接到互联网以访问 Google 云端硬盘,而不是简单地崩溃。

错误: httplib2.ServerNotFoundError:无法在 www.googleapis.com 找到服务器

我了解 Python 代码是从上到下读取的,应用程序在导入语句验证它未连接到互联网时崩溃。有没有办法让应用离线工作,并且对于在线活动要求用户连接到互联网?

感谢您在这件事上的帮助。

【问题讨论】:

    标签: python google-drive-api python-import httplib2


    【解决方案1】:

    reference 的帮助下能够解决这个问题。问题不在于引用这些语句的函数是否存在导入语句。

    解决方法如下:

    helper.py

    from __future__ import print_function
    import httplib2
    import os, io
    
    from apiclient import discovery
    from oauth2client import client
    from oauth2client import tools
    from oauth2client.file import Storage
    from apiclient.http import MediaFileUpload, MediaIoBaseDownload
    try:
        import argparse
        flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
    except ImportError:
        flags = None
    import auth
    
    import socket
    
    class Hi:
    
        def is_connected():
            try:
            # connect to the host -- tells us if the host is actually reachable
                socket.create_connection(("www.google.com", 80))
                print("Connected to the internet, execute code.")
                self.fileUpload() #----- function is called, if host is reachable.
            except OSError:
                print("No internet, code not executed.")
            
       def fileUpload():
           # This is the function that requires the import statements
           ...
           ...
        
    

    【讨论】:

      猜你喜欢
      • 2017-03-29
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      • 1970-01-01
      • 2016-02-14
      • 1970-01-01
      • 1970-01-01
      • 2018-11-17
      相关资源
      最近更新 更多