如何在Python 2.7 web.py?

时间:2016-11-08 16:38:00

标签: python-2.7

我在Linux机器上安装了带有web.py(v0.38)的Python 2.7.5。以下是我最基本的代码( webhooks.py

#!/usr/bin/python

import web

urls = ('/.*','WebHooks')
app = web.application(urls, globals())

class WebHooks:
    def POST(self):
        raw_payload = web.data()
        json_encode = json.loads(raw_payload)

if __name__ == '__main__':
    app.run()
  1. 我执行python webhooks.py 9999
  2. 它会打开一个本地端口http://0.0.0.0:9999/
  3. 我的问题:我已阅读位于here的文档,我感到难过。有人能帮我打开一个HTTPS URL吗? https://0.0.0.0:9999/

    我尝试了什么

    将以下内容添加到我的代码中进行测试:

    response = app.request("/.*", https=True)
    

    我会收到错误:AttributeError: 'module' object has no attribute 'request'

    我使用pip install urllib.py解决了这个问题,然后将import urllib添加到我的代码顶部,但最终出现了一堆错误:

    Traceback (most recent call last):
      File "/usr/lib/python2.7/site-packages/web/application.py", line 239, in process
        return self.handle()
      File "/usr/lib/python2.7/site-packages/web/application.py", line 230, in handle
        return self._delegate(fn, self.fvars, args)
      File "/usr/lib/python2.7/site-packages/web/application.py", line 461, in _delegate
        cls = fvars[f]
    KeyError: u'WebHooks'
    
    Traceback (most recent call last):
      File "/usr/lib/python2.7/site-packages/web/application.py", line 239, in process
        return self.handle()
      File "/usr/lib/python2.7/site-packages/web/application.py", line 229, in handle
        fn, args = self._match(self.mapping, web.ctx.path)
    AttributeError: 'ThreadedDict' object has no attribute 'path'
    

1 个答案:

答案 0 :(得分:4)

你走错了路,但不要担心。您尝试的response = app.request("/.*", https=True)位与您的应用制作 https请求有关,而不是处理 https请求。

请参阅http://webpy.org/cookbook/ssl

在内部,web.py使用CherryPyWSGIServer。要处理https,您需要为服务器提供ssl_certificate和ssl_key。很简单,在调用app.run()之前添加几行:

if __name__ == '__main__':
    from web.wsgiserver import CherryPyWSGIServer
    ssl_cert = '/path-to-cert.crt'
    ssl_key = '/path-to-cert.key'
    CherryPyWSGIServer.ssl_certificate = ssl_cert
    CherryPyWSGIServer.ssl_private_key = ssl_key
    app.run()

当然,在完整的解决方案中,您可能需要apache或nginx来处理https部分,但上述内容非常适合小型应用程序和测试。