|
| 1 | +# GraphQL WS |
| 2 | + |
| 3 | +.. image:: https://img.shields.io/pypi/v/graphql\_ws.svg :target: https://pypi.python.org/pypi/graphql\_ws |
| 4 | + |
| 5 | +.. image:: https://img.shields.io/travis/graphql-python/graphql\_ws.svg :target: https://travis-ci.org/graphql-python/graphql\_ws |
| 6 | + |
| 7 | +.. image:: https://readthedocs.org/projects/graphql-aiows/badge/?version=latest :target: https://graphql-aiows.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status |
| 8 | + |
| 9 | +.. image:: https://pyup.io/repos/github/graphql-python/graphql\_ws/shield.svg :target: https://pyup.io/repos/github/graphql-python/graphql\_ws/ :alt: Updates |
| 10 | + |
| 11 | +Websocket server for GraphQL subscriptions. |
| 12 | + |
| 13 | +- Free software: MIT license |
| 14 | + |
| 15 | +# Installation instructions |
| 16 | + |
| 17 | +For having a demo with Python 3.6: |
| 18 | + |
| 19 | +```shell |
| 20 | +git clone https://github.com/graphql-python/graphql-ws.git |
| 21 | +cd graphql-ws |
| 22 | + |
| 23 | +# Install the package |
| 24 | +python setup.py develop |
| 25 | +pip install -r requirements.txt |
| 26 | + |
| 27 | +# Demo time! |
| 28 | +cd examples |
| 29 | +python aio.py |
| 30 | +``` |
| 31 | + |
| 32 | +## Setup |
| 33 | + |
| 34 | +For setting up, just plug into your AioHTTP server. |
| 35 | + |
| 36 | +```python |
| 37 | +subscription_server = WebSocketSubscriptionServer(schema) |
| 38 | + |
| 39 | +async def subscriptions(request): |
| 40 | + ws = web.WebSocketResponse(protocols=('graphql-ws',)) |
| 41 | + await ws.prepare(request) |
| 42 | + |
| 43 | + await subscription_server.handle(ws) |
| 44 | + return ws |
| 45 | + |
| 46 | + |
| 47 | +app = web.Application() |
| 48 | +app.router.add_get('/subscriptions', subscriptions) |
| 49 | + |
| 50 | +web.run_app(app, port=8000) |
| 51 | +``` |
| 52 | + |
| 53 | +And then, plug into a subscribable schema: |
| 54 | + |
| 55 | +```python |
| 56 | +import asyncio |
| 57 | +import graphene |
| 58 | + |
| 59 | + |
| 60 | +class Query(graphene.ObjectType): |
| 61 | + base = graphene.String() |
| 62 | + |
| 63 | + |
| 64 | +class Subscription(graphene.ObjectType): |
| 65 | + count_seconds = graphene.Float(up_to=graphene.Int()) |
| 66 | + |
| 67 | + async def resolve_count_seconds(root, info, up_to): |
| 68 | + for i in range(up_to): |
| 69 | + yield i |
| 70 | + await asyncio.sleep(1.) |
| 71 | + yield up_to |
| 72 | + |
| 73 | + |
| 74 | +schema = graphene.Schema(query=Query, subscription=Subscription) |
| 75 | +``` |
0 commit comments