root/Python/geddit/controller.py

Revision 29, 4.2 kB (checked in by davbo, 20 months ago)

updated controller settings

Line 
1# -*- coding: utf-8 -*-
2#!/usr/bin/env python
3
4import operator, os, pickle, sys
5import cherrypy
6from formencode import Invalid
7from genshi.filters import HTMLFormFiller
8
9from geddit.form import LinkForm, CommentForm
10from geddit.model import Link, Comment
11from geddit.lib import template
12
13
14class Root(object):
15
16    def __init__(self, data):
17        self.data = data
18
19    @cherrypy.expose
20    @template.output('index.html')
21    def index(self):
22        links = sorted(self.data.values(), key=operator.attrgetter('time'))
23        return template.render(links=links)
24
25    @cherrypy.expose
26    @template.output('submit.html')
27    def submit(self, cancel=False, **data):
28        if cherrypy.request.method == 'POST':
29            if cancel:
30                raise cherrypy.HTTPRedirect('/')
31            form = LinkForm()
32            try:
33                data = form.to_python(data)
34                link = Link(**data)
35                self.data[link.id] = link
36                raise cherrypy.HTTPRedirect('/')
37            except Invalid, e:
38                errors = e.unpack_errors()
39        else:
40            errors = {}
41
42        return template.render(errors=errors) | HTMLFormFiller(data=data)
43   
44    @cherrypy.expose
45    @template.output('info.html')
46    def info(self, id):
47        link = self.data.get(id)
48        if not link:
49            raise cherrypy.NotFound()
50        return template.render(link=link)
51       
52    @cherrypy.expose
53    @template.output('index.xml', method='xml')
54    def feed(self, id=None):
55        if id:
56            link = self.data.get(id)
57            if not link:
58                raise cherrypy.NotFound()
59            return template.render('info.xml', link=link)
60        else:
61            links = sorted(self.data.values(), key=operator.attrgetter('time'))
62            return template.render(links=links)
63   
64    @cherrypy.expose
65    @template.output('comment.html')
66    def comment(self, id, cancel=False, **data):
67        link = self.data.get(id)
68        if not link:
69            raise cherrypy.NotFound()
70        if cherrypy.request.method == 'POST':
71            if cancel:
72                raise cherrypy.HTTPRedirect('/info/%s' % link.id)
73            form = CommentForm()
74            try:
75                data = form.to_python(data)
76                comment = link.add_comment(**data)
77                raise cherrypy.HTTPRedirect('/info/%s' % link.id)
78            except Invalid, e:
79                errors = e.unpack_errors()
80        else:
81            errors = {}
82
83        return template.render(link=link, comment=None,
84                               errors=errors) | HTMLFormFiller(data=data)
85
86def main(filename):
87    # load data from the pickle file, or initialize it to an empty list
88    if os.path.exists(filename):
89        fileobj = open(filename, 'rb')
90        try:
91            data = pickle.load(fileobj)
92        finally:
93            fileobj.close()
94    else:
95        data = {}
96
97    def _save_data():
98        # save data back to the pickle file
99        fileobj = open(filename, 'wb')
100        try:
101            pickle.dump(data, fileobj)
102        finally:
103            fileobj.close()
104    if hasattr(cherrypy.engine, 'subscribe'): # CherryPy >= 3.1
105        cherrypy.engine.subscribe('stop', _save_data)
106    else:
107        cherrypy.engine.on_stop_engine_list.append(_save_data)
108
109    # Some global configuration; note that this could be moved into a
110    # configuration file
111    cherrypy.config.update({'server.socket_port': 7671,
112                    'log.screen': False,
113                    'environment':'production',
114                    'server.socket_host': '127.0.0.1',
115                    'tools.proxy.on': True,
116                    'tools.proxy.base': "http://davbo.org/geddit/",
117                    'tools.proxy.local': "",
118             #       'tools.encode.on': True, 'tools.encode.encoding': 'utf-8',
119             #       'tools.decode.on': True,
120             #       'tools.trailing_slash.on': True,
121             #       'tools.staticdir.root': os.path.abspath(os.path.dirname(__file__))
122        })
123    cherrypy.quickstart(Root(data), '/geddit/', {
124        '/media': {
125            'tools.staticdir.on': True,
126            'tools.staticdir.dir': 'static'
127        }
128    })
129
130if __name__ == '__main__':
131    main("geddit.db")
Note: See TracBrowser for help on using the browser.