Giter Site home page Giter Site logo

github-webhooks's Introduction

Python GitHub Webhooks Framework

NOTE: Forked from github_webhooks as I needed to access more things:

  • query params from incoming webhooks for identification
  • background_tasks to handle long running webhook actions.

Simple and lightweight micro framework for quick integration with GitHub webhooks.
It's based on FastAPI and pydantic, nothing more!
Async and mypy friendly.

Run CI
PyPI

Installation

Just add github-webhooks-framework2 package.
Example:

  • pip install github-webhooks-framework2
  • poetry add github-webhooks-framework2

Example

Create file example.py and copy next code:

import uvicorn
from pydantic import BaseModel

from github_webhooks import create_app
from github_webhooks.schemas import WebhookCommonPayload


# WebhookCommonPayload is based on pydantic.BaseModel
class PullRequestPayload(WebhookCommonPayload):
    class Pull(BaseModel):
        title: str
        url: str

    action: str
    pull_request: Pull


# Initialize Webhook App
app = create_app()


# Register webhook handler:
#   `pull_request` - name of an event to handle
#   `PullRequestPayload` - webhook payload will be parsed into this model
@app.hooks.register('pull_request', PullRequestPayload)
async def handler(payload: PullRequestPayload) -> None:
    print(f'New pull request {payload.pull_request.title}')
    print(f'  link: {payload.pull_request.url}')
    print(f'  author: {payload.sender.login}')


if __name__ == '__main__':
    # start uvicorn server
    uvicorn.run(app)

Let's have detailed overview.

We start by defining payload Model to parse incoming Pull Request Body.

class PullRequestPayload(WebhookCommonPayload):
    class Pull(BaseModel):
        title: str
        url: str

    action: str
    pull_request: Pull

In this example we only want to get action, pull_request.title and pull_request.url from payload.
By subclassing WebhookCommonPayload model will automatically get sender, repository and organization fields.

Next - we are creating ASGI app (based on FastAPI app)

app = create_app()

Optionally we can provide here secret_token Github Webhook secret

app = create_app(secret_token='super-secret-token')

And time to define our handler

@app.hooks.register('pull_request', PullRequestPayload)
async def handler(payload: PullRequestPayload) -> None:
    print(f'New pull request {payload.pull_request.title}')
    print(f'  link: {payload.pull_request.url}')
    print(f'  author: {payload.sender.login}')

We are using here @app.hooks.register deco, which accepts 2 arguments:

  • event: str - name of webhook event
  • payload_cls: pydantic.BaseModel - pydantic model class to parse request, subclassed from pydantic.BaseModel or WebhookCommonPayload.

And our handler function can include the following params:

async def handler(payload: PullRequestPayload, headers: WebhookHeaders, query_params: QueryParams, background_tasks: BackgroundTasks) -> Optional[str]:
    # `headers` will be WebhookHeaders model with Github Webhook headers parsed.
    ...

When not in need of any of the named params simply take them as **_: Any as not used:

async def handler(payload: PullRequestPayload, **_: Any) -> Optional[str]:
    ...

An example setup can be found in example/server.py.

References:

Development

  1. Install local venv: python -m venv .venv
  2. Activate: . .venv/bin/activate
  3. Install deps with pip install -r requirements.txt -r requirements-test.txt
  4. When done with packages: ./freeze-requirements.sh

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.