【问题标题】:Why does my script that uses twilio run perfectly locally, but throw an error on Python Anywhere?为什么我使用 twilio 的脚本在本地完美运行,但在 Python Anywhere 上抛出错误?
【发布时间】:2016-08-05 09:20:06
【问题描述】:

我的脚本在本地运行时完美执行,但是当我在 Python Anywhere 上执行时,它会引发以下错误:

Traceback (most recent call last):
  File "/home/ectobiologist7/desiderius.py", line 68, in <module>
    asendoff()
  File "/home/ectobiologist7/desiderius.py", line 64, in asendoff
    body=billiam,
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/messages.py", line 122, in create
    return self.create_instance(kwargs)
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/base.py", line 365, in create_instance
    data=transform_params(body))
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/base.py", line 200, in request
    resp = make_twilio_request(method, uri, auth=self.auth, **kwargs)
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/base.py", line 152, in make_twilio_request
    resp = make_request(method, uri, **kwargs)
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/base.py", line 117, in make_request
    resp, content = http.request(url, method, headers=headers, body=data)
  File "/usr/local/lib/python3.4/dist-packages/httplib2/__init__.py", line 1314, in request
    (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
  File "/usr/local/lib/python3.4/dist-packages/httplib2/__init__.py", line 1064, in _request
    (response, content) = self._conn_request(conn, request_uri, method, body, headers)
  File "/usr/local/lib/python3.4/dist-packages/httplib2/__init__.py", line 987, in _conn_request
    conn.connect()
  File "/usr/lib/python3.4/http/client.py", line 1223, in connect
    super().connect()
  File "/usr/lib/python3.4/http/client.py", line 834, in connect
    self.timeout, self.source_address)
  File "/usr/lib/python3.4/socket.py", line 512, in create_connection
    raise err
  File "/usr/lib/python3.4/socket.py", line 503, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

现在,我在 Stack Overflow 和 Python 本身的任何地方都浏览了论坛,但我找到的解决方案都没有成功。一个建议是该脚本无法正常工作,因为我试图访问的网站不在白名单上,而事实并非如此。我尝试使用一些我发现的代码来强制 PA 使用不同的代理,正如网站开发人员所建议的那样,但这不起作用。我还看到开发人员建议有这个问题的人改用 Python 2.7。我这样做了,但仍然没有任何改变。还有其他可能的解决方案吗?提前致谢!我的代码如下。

from twilio.rest import TwilioRestClient
from datetime import *
import urllib.request
from bs4 import BeautifulSoup
from random import randint
import ast
#use julian date to calculate days left till summer

# put your own credentials here
def dateelle():
    #use datetime to state date in Month Day, Year format.
    todaylist = date.today().timetuple()
    monthdict = {1:"January ", 2:"February ", 3:"March ", 4:"April ", 5:"May ", 6:"June ", 7:"July ", 8:"August ", 9:"September ", 10:"October ", 11:"November ", 12:"December "}
    month = monthdict[todaylist[1]]
    day = todaylist[2]
    year = todaylist[0]
    ultidate = str(month) + str(day) + ", " + str(year) + " "
    return ultidate
def temple():
    url = 'http://api.openweathermap.org/data/2.5/weather?id=5429522&APPID=0f25c0515e643bc2427f665f88a4d3eb'
    headers = {}
    headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36'
    tri1 = urllib.request.Request(url, headers=headers)
    tri2 = urllib.request.urlopen(tri1)
    quell = BeautifulSoup(tri2)
    tagwithtemp = int(ast.literal_eval(quell.text)['main']['temp'] * (9/5) - 459.67)
    return tagwithtemp

def daysleft():
    todayy = date.today().timetuple()[7]
    allthatremains = 147 - todayy
    return allthatremains


comp = {0:" You look nice today.",
        1:" Have a good day.",
        2:" Today will be a great day.",
        3:" You are an important person who means much to the world.",
        4: " Someone's day today will be brightened by your presence.",
        5: " Despite the amount of people in the world, your existence matters. :)",
        6: " There may be billions of people on this planet, but you still make a difference."}
billiam = "Good morning! Today is " + dateelle() + "and it is " + str(temple()) + " degrees." + comp[randint(0,6)] + " " + str(daysleft()) + " days left until summer!"

def asendoff():
    global billiam
    ACCOUNT_SID = "***" #the SID, AUTH token, and my phone number are censored
    AUTH_TOKEN = "***"
    nummer = ["***"]
    client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)

    for lexis in nummer:
        client.messages.create(
            to=lexis,
            from_="+15026255861",
            body=billiam,
        )

if date.today().timetuple()[6] != 6 and date.today().timetuple()[6] != 7:
    asendoff()
else:
    pass

【问题讨论】:

  • 我怀疑某处有防火墙阻止了 PythonAnywhere。
  • @Barmar 在 Twilio 的最后?这将如何解决?
  • 从这里无法判断是哪一端。

标签: python python-3.x twilio pythonanywhere


【解决方案1】:

所有来自 PythonAnywhere 免费帐户的外部连接都经过代理,以防止滥用。

您需要像这样为连接设置代理:

from twilio.rest.resources import Connection
from twilio.rest.resources.connection import PROXY_TYPE_HTTP

Connection.set_proxy_info(
    "proxy.server",
    3128,
    proxy_type=PROXY_TYPE_HTTP
)

但是,在 Python 3 中,httplib2(因此 twilio-python)会忽略代理设置(参见 this page 的底部),因此会尝试直接连接到被阻止的 Twilio。

【讨论】:

  • 我确实已经尝试过代理,但这个看起来不同,所以我会尝试一下!我应该把它放在脚本的哪个位置?
  • 在连接到 twilio 之前
  • 知道了!对于未来的读者,为了澄清,您必须添加代理代码并使用 Python 2.7。感谢您的帮助!
  • 我无法导入这些模块
【解决方案2】:

这里是 Twilio 开发者宣传员。

previous reports 暗示 PA 有旧版本的库。几个月前,我们在库和 API 中创建了一个pretty significant change 来强制实施 SSL。

如果您使用的是最新版本的库,则应该没有任何变化。从您发布的错误中,我无法准确判断 PA 使用的是哪个版本的库,但进一步挖掘,用户似乎是 suggest you need a proxy

我的建议是稍微改变你的方法,也许将它部署到Heroku(它是免费的,你将能够使用你想要的确切的库版本)。这样,如果您发现它在那里工作,您可以联系 PA 并检查他们拥有哪个库版本,您将能够告诉他们是否需要更新。

希望对你有帮助

【讨论】:

  • PythonAnywhere dev here -- 您也可以在我们的平台上运行您想要的任何版本的 Twilio 库,使用 pip2.7 install --user --upgrade 或 virtualenv。问题是 httplib2 中的错误,这意味着它忽略了代理设置(免费 PythonAnywhere 帐户需要)——请参阅 Glenn 对这个问题的回答。
  • 实际上,我应该说一件事——requests 显然是一个比httplib2 更好的构建API 的库。我们在基于requests 的库中的代理设置从未遇到任何问题,尤其是当它从标准环境变量中获取它们而不是要求用户在代码中配置它们时。它也做了巧妙的连接池工作,所以理论上如果你的服务器支持它,事情可以运行得更快。
  • 对不起,我忘了说 PA 上的控制台和我的本地脚本都使用 5.4.0 并且仍然出现此错误。
  • 在主帖中,指向解决方案代理的链接正是我在问题中提到的那个不起作用。对不起!
猜你喜欢
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-07
  • 2011-10-04
  • 2018-02-05
相关资源
最近更新 更多