Giter Club home page Giter Club logo

webhooks's Introduction

Webhook Listener

Very basic webserver module to listen for webhooks and forward requests to predefined functions.

Author: Todd Roberts

https://pypi.org/project/webhook_listener/

https://github.com/toddrob99/Webhooks

Install

Install from PyPI using pip

pip install webhook_listener

Use

  • Define a function to process requests
    • request parameter will be a cherrypy request object
    • *args parameter will be a tuple of URL path components
    • **kwargs parameter will be a dictionary of URL parameters
    • Get the body of a POST request from request.body.read passing the length of request.headers['Content-Length']: request.body.read(int(request.headers['Content-Length'])) if int(request.headers.get('Content-Length',0)) > 0 else ''
    • Note: The body will be a byte array, and not a string. You may need to decode it to a string. For example:
      import json
      body_raw = request.body.read(int(request.headers['Content-Length'])) if int(request.headers.get('Content-Length',0)) > 0 else '{}'
      body = json.loads(body_raw.decode('utf-8'))
      
  • Include webhook-listener in your project
  • Create an instance of the webhook_listener.Listener class
    • handlers = Dictionary of functions/callables for each supported HTTP method. (Example: {'POST':process_post_request, 'GET':process_get_request})
    • port = Port for the web server to listen on (default: 8090)
    • host = Host for the web server to listen on (default: '0.0.0.0')
    • threadPool = Number of worker threads for the web server (default: 10)
    • logScreen = Setting for cherrypy to log to screen (default: False)
    • autoReload = Setting for cherrypy to auto reload when python files are changed (default: False)
    • sslModule = Select which SSL library to use (default: 'builtin')
    • sslCert = Path to the certificate (SSL is disabled when empty)
    • sslPrivKey = Path to the certificate's private key (SSL is disabled when empty)
    • sslCertChain = Path to the full certificate chain see https://cherrypydocrework.readthedocs.io/deploy.html#ssl-support for more information on SSL support
  • Start the Listener
  • Keep your application running so the Listener can run in a separate thread

Example

import time
import webhook_listener


def process_post_request(request, *args, **kwargs):
    print(
        "Received request:\n"
        + "Method: {}\n".format(request.method)
        + "Headers: {}\n".format(request.headers)
        + "Args (url path): {}\n".format(args)
        + "Keyword Args (url parameters): {}\n".format(kwargs)
        + "Body: {}".format(
            request.body.read(int(request.headers["Content-Length"]))
            if int(request.headers.get("Content-Length", 0)) > 0
            else ""
        )
    )

    # Process the request!
    # ...

    return


webhooks = webhook_listener.Listener(handlers={"POST": process_post_request})
webhooks.start()

while True:
    print("Still alive...")
    time.sleep(300)

webhooks's People

Contributors

buanzo avatar sdemets avatar toddrob99 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

webhooks's Issues

Might not be an issue but possible.

I am not 100% sure this will be an issue, I hope python3 doesn't have such a warning.

When you ctrl+c to stop the webhook listener, you will get the following warning:

/usr/lib/python2.7/site-packages/cherrypy/process/wspbus.py:258: RuntimeWarning: The main thread is exiting, but the Bus is in the states.STOPPED state; shutting it down automatically now. You must either call bus.block() after start(), or call bus.exit() before the main thread exits.

Thanks.

How to get autoreload work

Hi Todd,

Found your package when google searching for a simple webhook server. Its great - simple for a beginner at python like me.

Could I get some help tho - I see there is a 'autoreload' and it suggests that I can edit the source code and have the changes reflect on the server immediately (that's great for developing/debugging).

However, it does not seem to be working. When I set logScreen and autoReload to true; I get the output below. It seems to suggest that the file change notification is received but after the webserver is shutdown; it doesn't come back up again.

Am I missing a step?

[15/Jul/2020:12:37:18] ENGINE Bus STARTING
Still alive...
[15/Jul/2020:12:37:18] ENGINE Started monitor thread 'Autoreloader'.
[15/Jul/2020:12:37:18] ENGINE Serving on http://0.0.0.0:8090
[15/Jul/2020:12:37:18] ENGINE Bus STARTED
Received request:
[[[details of request elided ]]]
192.168.0.100 - - [15/Jul/2020:12:37:19] "POST /webhook-serrer HTTP/1.1" 200 2 "" "curl/7.58.0"
[15/Jul/2020:12:37:26] ENGINE Restarting because /home/kelly/system/testing/webserver.py changed.
[15/Jul/2020:12:37:26] ENGINE Stopped thread 'Autoreloader'.
[15/Jul/2020:12:37:26] ENGINE Bus STOPPING
[15/Jul/2020:12:37:26] ENGINE HTTP Server cherrypy._cpwsgi_server.CPWSGIServer(('0.0.0.0', 8090)) shut down
[15/Jul/2020:12:37:26] ENGINE Bus STOPPED
[15/Jul/2020:12:37:26] ENGINE Bus EXITING
[15/Jul/2020:12:37:26] ENGINE Bus EXITED
Still alive...

It won't work for python v2.7.5 and prior

Traceback (most recent call last):
File "./webhooklisterner.py", line 79, in
webhooks.start()
File "/usr/lib/python2.7/site-packages/webhook_listener/init.py", line 31, in start
self.WEBTHREAD = threading.Thread(target=self._startServer, name='webhooks_websever', daemon=True)
TypeError: init() got an unexpected keyword argument 'daemon'

Please split line 31
self.WEBTHREAD = threading.Thread(target=self._startServer, name='webhooks_websever', daemon=True)
To
self.WEBTHREAD = threading.Thread(target=self._startServer, name='webhooks_websever') self.WEBTHREAD.daemon = True
Will work for all, since last arg daemon=True isn't added to the function until 2.7.6

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.