Last active
August 29, 2015 14:03
-
-
Save storborg/13bb287ae2583221de2b to your computer and use it in GitHub Desktop.
How to use Pyramid to turn a Python function into a local "GUI" app
This file contains 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
""" | |
The basic idea here is to wrap a Python function (in the case below, it is | |
``do_programming_crap()``) and make a basic GUI interface to call that | |
function. | |
Theoretically, it's much easier to create a packaged executable which is only | |
dependent on Pyramid vs. depending on something like PyGTK, WxWidgets, Kivy, | |
SDL, whatever. | |
""" | |
import webbrowser | |
from wsgiref.simple_server import make_server | |
from pyramid.config import Configurator | |
from pyramid.response import Response | |
page_templ = ''' | |
<!DOCTYPE html> | |
<html> | |
<body> | |
%s | |
</body> | |
</html> | |
''' | |
index_page = ''' | |
<form action="/program" method="post"> | |
<button type="submit">PROGRAM IT</button> | |
</form> | |
''' | |
def do_programming_crap(): | |
if 1 + 1 == 2: | |
return 'ok' | |
else: | |
return 'fail' | |
def program_view(request): | |
""" | |
Handle form submits from the programming button and call the function we're | |
wrapping. | |
""" | |
status = do_programming_crap() | |
return Response(page_templ % status) | |
def index_view(request): | |
""" | |
Serve up the index page, which is basically just a button to initiate | |
programming. | |
""" | |
return Response(page_templ % index_page) | |
if __name__ == '__main__': | |
# Initialize the Pyramid app, which has the above two 'pages'. | |
config = Configurator() | |
config.add_route('program', '/program') | |
config.add_route('index', '/') | |
config.add_view(program_view, route_name='program') | |
config.add_view(index_view, route_name='index') | |
app = config.make_wsgi_app() | |
port = 8080 | |
# Open a web browser pointing to the server we're about to start. Note that | |
# there is a race condition here which you might want to clean up for | |
# production: we're assuming that it takes longer to spawn the web browser | |
# than it does to launch our HTTP server. | |
webbrowser.open('http://localhost:%d' % port) | |
# Spawn the HTTP server. | |
server = make_server('0.0.0.0', port, app) | |
server.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment