2016-11-08 31 views
0

我在Linux機器上使用安裝了web.py(v0.38)的Python 2.7.5。下面是我在最基本的形式代碼(webhooks.py如何在Python 2.7 web.py上啓用HTTPS?

#!/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/

我的問題:我已閱讀文檔位於​​,我很難過。有人能幫我打開一個HTTPS網址嗎? 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' 

回答

2

你走向錯誤的道路,但不要擔心。您嘗試使用的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的部分,但上述非常適合小型應用程序和測試。

+0

謝謝!我會在明天早上嘗試第一件事並更新這個狀態。 –

+1

更新:您的解決方案工作正常!對於也在嘗試這種方式的其他讀者,我必須確保在工作之前有兩件事。首先,您需要在您的系統上安裝openssl-devel,然後使用pip安裝pyOpenSSL。 –