Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable HTTPS on Python 2.7 web.py?

Tags:

python-2.7

I am using Python 2.7.5 with web.py (v0.38) installed on a Linux machine. Below is my code in the most basic form (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. I execute python webhooks.py 9999
  2. It opens up a local port http://0.0.0.0:9999/

My issue: I have read the documentation located here and I am stumped. Would somebody be able to help me open an HTTPS URL? https://0.0.0.0:9999/

What I have tried

Add the following into my code for testing:

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

I would get an error: AttributeError: 'module' object has no attribute 'request'

I solved that issue with pip install urllib.py and then adding import urllib to the top of my code but I ended up with a bunch of errors:

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'
like image 561
Jeffrey Wen Avatar asked Jun 21 '26 10:06

Jeffrey Wen


1 Answers

You're headed down the wrong path, but not to worry. The response = app.request("/.*", https=True) bit you're trying has to do with your application making an https request, rather then handling an https request.

See http://webpy.org/cookbook/ssl

Internally, web.py uses a CherryPyWSGIServer. To handle https, you need to provide the server with an ssl_certificate and ssl_key. Very simply, add a few lines before you invoke 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()

Of course, in a full solution, you'll probably want apache or nginx to handle the https portion, but the above is perfect for small applications and testing.

like image 52
pbuck Avatar answered Jun 25 '26 21:06

pbuck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!