Python Twisted / Cyclone, 'Hello, World!' application, on Openshift

September 10, 2015

Share

Tags

python openshift

I am working on Mac OS X, some of the commands in this tutorial may not be identical on your OS

Prerequisites

Be sure to complete the openshift setup as described [here](https://developers.openshift.com/en/getting-started-overview.html)

Create Application (Gear) on OpenShift Cloud

๐บ rhc create-app cyclonetest python-2.7
There may be a few prompts about ssh keys, don't be alarmed

Install Application Dependencies

๐บ cd /path/to/application
๐บ echo "cyclone==1.1" > requirements.txt
๐บ pip install -r ./requirements.txt

Create โ€œHello, World!โ€ Application

๐บ cyclone app -n > app.py

Verify Application Works

Start Application

๐บ cyclone run --app=app.py

Test the app

Using cURL

๐บ curl http://localhost
Hello, world

Using HTTPie

๐บ http --print=HBhb http://localhost:8888
GET / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: localhost:8888
User-Agent: HTTPie/0.9.2



HTTP/1.1 200 OK
Content-Length: 12
Content-Type: text/html; charset=UTF-8
Date: Thu, 10 Sep 2015 02:54:23 GMT
Etag: "e02aa1b106d5c7c6a98def2b13005d5b84fd8dc8"
Server: cyclone/1.1

Hello, world

Modify App to Incorporate Openshift Environment

Add Import Statements

import os, sys
from twisted.python import log
from twisted.internet import reactor

Add main

if __name__ == "__main__":
    log.startLogging(sys.stdout)
    port = int(os.getenv('OPENSHIFT_PYTHON_PORT', 8888))
    host = os.getenv('OPENSHIFT_PYTHON_IP', "0.0.0.0")
    reactor.listenTCP(port, Application(), interface=host)
    reactor.run()

Full Application

import os, sys
from twisted.python import log
from twisted.internet import reactor

import cyclone.web

class MainHandler(cyclone.web.RequestHandler):
    def get(self):
        self.write("Hello, world")


class Application(cyclone.web.Application):
    def __init__(self):
        handlers = [
            (r"/", MainHandler),
        ]

        settings = dict(
            xheaders=False,
            static_path="./static",
            templates_path="./templates",
        )

        cyclone.web.Application.__init__(self, handlers, **settings)

if __name__ == "__main__":
    log.startLogging(sys.stdout)
    port = int(os.getenv('OPENSHIFT_PYTHON_PORT', 8888))
    host = os.getenv('OPENSHIFT_PYTHON_IP', "0.0.0.0")
    reactor.listenTCP(port, Application(), interface=host)
    reactor.run()

Github Repo

Download .gitignore for python projects

curl https://raw.githubusercontent.com/github/gitignore/master/Python.gitignore > .gitignore

Commit and Push

๐บ git add -A
๐บ git commit -am "Adding cyclone hello world"
๐บ git push

Enjoy!

๐บ rhc show-app cyclonetest
testcyclone @ http://cyclonetest-alexboyd.rhcloud.com/
๐บ curl http://cyclonetest-alexboyd.rhcloud.com/
Hello, world