Source

qtwsgi / step2.py

#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys

from wsgiref.util import setup_testing_defaults
from wsgiref import simple_server

from PySide import QtCore, QtNetwork, QtGui

ENCODING = 'utf-8'

class QWSGILabel(QtGui.QLabel):
    def __init__(self, text, parent=None):
        super(QWSGILabel, self).__init__(text, parent=parent)

    def __call__(self, environ, start_response):
        """WSGI handle"""

        setup_testing_defaults(environ)
        start_response('200 OK', [('Content-type', 'text/html'), ])
        return self.text().encode(ENCODING)

class QHttpThread(QtCore.QThread):
    u"""Http threads"""

    def __init__(self, wsgi_server, parent=None):
        super(QHttpThread, self).__init__(parent=parent)
        self.wsgi_server = wsgi_server
        self.__is_run = False

    def run(self):
        self.__is_run = True
        while (self.__is_run):
            self.wsgi_server.handle_request()

    def stop(self):
        self.__is_run = False

class QHttpWidget(QtGui.QWidget):
    def __init__(self, host='localhost', port=8000, parent=None):
        super(QHttpWidget, self).__init__(parent=parent)
        self.setLayout(QtGui.QVBoxLayout(self))

        # Create label instance
        qwsgilabel = QWSGILabel("Hello World!", parent=self)
        self.layout().addWidget(qwsgilabel)

        # Create and start WSGI server
        wsgi_server = QHttpThread(
                simple_server.make_server(host, port, qwsgilabel), parent=self)
        wsgi_server.start()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window = QHttpWidget()
    window.show()
    sys.exit(app.exec_())