Last active
August 29, 2015 14:07
-
-
Save jprystowsky/0906692adf93b9b0b57e to your computer and use it in GitHub Desktop.
Hello Shawn, a basic Python Twisted example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1. Install python3 E.g., apt-get install python3, brew install python3, etc. | |
2. pip3 install twisted | |
3. python3 app.py | |
4. GET localhost:8880 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from twisted.web.resource import Resource | |
from twisted.web.server import Site | |
from twisted.internet import reactor | |
import json | |
class Hello: | |
def __init__(self, name='Shawn'): | |
self.greeting = 'Hello' | |
self.name = name | |
class Index(Resource): | |
isLeaf = True | |
def render_GET(self, request): | |
request.setHeader(b'content-type', b'text/plain;charset=utf-8') | |
return b""" | |
Hello, Shawn! Why don\'t you try GETting /hello, /hello?name=Twisted, /api/hello, and /api/hello?name=Twisted | |
Protip: `curl -iv localhost:8880/api/hello` | |
""" | |
class HelloText(Resource): | |
isLeaf = True | |
def render_GET(self, request): | |
request.setHeader(b'content-type', b'text/html;charset=utf-8') | |
name = "Shawn" | |
if b'name' in request.args.keys(): | |
name = request.args[b'name'][0].decode('utf-8') | |
return """<html><body> | |
Nice to see you, <strong>{0}</strong> | |
</body></html>""".format(name).encode('utf-8') | |
class HelloApi(Resource): | |
isLeaf = True | |
def render_GET(self, request): | |
request.setHeader(b'content-type', b'application/json;charset=utf-8') | |
hello = None | |
if b'name' in request.args.keys(): | |
hello = Hello(request.args[b'name'][0].decode('utf-8')) | |
else: | |
hello = Hello() | |
return json.dumps(hello.__dict__).encode('utf-8') | |
apiRoot = Resource() | |
apiRoot.putChild(b'hello', HelloApi()) | |
root = Resource() | |
root.putChild(b'', Index()) | |
root.putChild(b'hello', HelloText()) | |
root.putChild(b'api', apiRoot) | |
reactor.listenTCP(8880, Site(root)) | |
reactor.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment