-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathCherryPyApp.py
More file actions
354 lines (258 loc) · 11.5 KB
/
Copy pathCherryPyApp.py
File metadata and controls
354 lines (258 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#!/usr/bin/env python
# -*- mode: python; indent-tabs-mode: nil; -*- coding: utf-8 -*-
"""
CherryPyApp.py
Copyright 2009-2014 by Marcello Perathoner
Distributable under the GNU General Public License Version 3 or newer.
The Project Gutenberg Catalog App Server.
Config and route setup.
"""
from __future__ import unicode_literals
import logging
import logging.handlers # rotating file handler
import os
import cherrypy
from cherrypy.process import plugins
from libgutenberg import GutenbergDatabase
import i18n_tool
# this import causes ConnectionPool.ConnectionPool to become the cherrypy connection pool
import ConnectionPool
import Page
import StartPage
import SuggestionsPage
from SearchPage import BookSearchPage, AuthorSearchPage, SubjectSearchPage, BookshelfSearchPage, \
AuthorPage, SubjectPage, BookshelfPage, AlsoDownloadedPage
from BibrecPage import BibrecPage
from AdvSearchPage import AdvSearchPage
import CoverPages
import EbookCount
import QRCodePage
import MetricsPage
import Sitemap
import Formatters
from errors import ErrorPage
import Timer
plugins.Timer = Timer.TimerPlugin
install_dir = os.path.dirname(os.path.abspath(__file__))
CHERRYPY_CONFIG = os.path.join(install_dir, 'CherryPy.conf')
LOCAL_CONFIG = [os.path.expanduser('~/.autocat3'), '/etc/autocat3.conf']
def error_page_404(status, message, traceback, version):
resp = ErrorPage(status, message).index()
# signal that we needn't save the session
cherrypy.session.loaded = False
return resp
class MyRoutesDispatcher(cherrypy.dispatch.RoutesDispatcher):
""" Dispatcher that tells us the matched route.
CherryPy makes it hard for us by forgetting the matched route object.
Here we add a 'route_name' parameter, that will tell us the route's name.
"""
def connect(self, name, route, controller, **kwargs):
""" Add a 'route_name' parameter that will tell us the matched route. """
kwargs['route_name'] = name
kwargs.setdefault('action', 'index')
cherrypy.dispatch.RoutesDispatcher.connect(self, name, route, controller, **kwargs)
def configure():
# default config
cherrypy.config.update({
'server_name': 'localhost',
'genshi.template_dir': os.path.join(install_dir, 'templates'),
'host': 'localhost',
'file_host': 'localhost',
'devmode': False,
})
cherrypy.config.update(CHERRYPY_CONFIG)
extra_config = ''
for config_filename in LOCAL_CONFIG:
try:
cherrypy.config.update(config_filename)
extra_config = config_filename
break
except IOError:
pass
cherrypy.config['all_hosts'] = (
cherrypy.config['host'], cherrypy.config['file_host'])
cherrypy.config.update({'error_page.404': error_page_404})
cherrypy.tools.I18nTool = i18n_tool.I18nTool()
Formatters.init()
# configure database
GutenbergDatabase.options.update(cherrypy.config)
cherrypy.engine.pool = plugins.ConnectionPool(
cherrypy.engine, params=GutenbergDatabase.get_connection_params(cherrypy.config))
cherrypy.engine.pool.subscribe()
# configure timers
plugins.Timer(cherrypy.engine).subscribe()
return extra_config
def get_app():
cherrypy.log("Setting up routes", context='ENGINE', severity=logging.INFO)
# setup 'routes' dispatcher
d = MyRoutesDispatcher(full_result=True)
cherrypy.routes_mapper = d.mapper
def check_id(environ, result):
""" Check if id is a valid number. """
try:
return str(int(result['id'])) == result['id']
except:
return False
d.connect('start', r'/ebooks{.format}/',
controller=StartPage.Start())
d.connect('suggest', r'/ebooks/suggest{.format}/',
controller=SuggestionsPage.Suggestions())
# search pages
d.connect('search', r'/ebooks/search{.format}/',
controller=BookSearchPage())
d.connect('author_search', r'/ebooks/authors/search{.format}/',
controller=AuthorSearchPage())
d.connect('subject_search', r'/ebooks/subjects/search{.format}/',
controller=SubjectSearchPage())
d.connect('bookshelf_search', r'/ebooks/bookshelves/search{.format}/',
controller=BookshelfSearchPage())
d.connect('results', r'/ebooks/results{.format}/',
controller=AdvSearchPage())
# 'id' pages
d.connect('author', r'/ebooks/author/{id:\d+}{.format}',
controller=AuthorPage(), conditions=dict(function=check_id))
d.connect('subject', r'/ebooks/subject/{id:\d+}{.format}',
controller=SubjectPage(), conditions=dict(function=check_id))
d.connect('bookshelf', r'/ebooks/bookshelf/{id:\d+}{.format}',
controller=BookshelfPage(), conditions=dict(function=check_id))
d.connect('also', r'/ebooks/{id:\d+}/also/',
controller=AlsoDownloadedPage(), conditions=dict(function=check_id))
# bibrec pages
d.connect('download', r'/ebooks/{id:\d+}/download{.format}',
controller=Page.NullPage(), _static=True)
d.connect('bibrec', r'/ebooks/{id:\d+}{.format}',
controller=BibrecPage(), conditions=dict(function=check_id))
# legacy compatibility with /ebooks/123.bibrec
d.connect('bibrec2', r'/ebooks/{id:\d+}.bibrec{.format}',
controller=BibrecPage(), conditions=dict(function=check_id))
d.connect('cover', r'/covers/{size:small|medium}/{order:latest|popular|random}/{count}',
controller=CoverPages.CoverPages())
d.connect('ebook_count', r'/ebook_count/',
controller=EbookCount.EbookCount())
d.connect('qrcode', r'/qrcode/',
controller=QRCodePage.QRCodePage())
d.connect('iplimit', r'/iplimit/',
controller=Page.NullPage())
d.connect('metrics', r'/metrics/',
controller=MetricsPage.MetricsPage())
d.connect('metrics', r'/metrics/',
controller=MetricsPage.MetricsPage())
d.connect('stats', r'/stats/',
controller=Page.NullPage(), _static=True)
# /w/captcha/question/ so varnish will cache it
d.connect('captcha.question', r'/w/captcha/question/',
controller=Page.GoHomePage())
d.connect('captcha.answer', r'/w/captcha/answer/',
controller=Page.GoHomePage())
# sitemap protocol access control requires us to place sitemaps in /ebooks/
d.connect('sitemap', r'/ebooks/sitemaps/',
controller=Sitemap.SitemapIndex())
d.connect('sitemap_index', r'/ebooks/sitemaps/{page:\d+}',
controller=Sitemap.Sitemap())
if 'dropbox_client_id' in cherrypy.config:
import Dropbox
dropbox = Dropbox.Dropbox
cherrypy.log("Dropbox Client Id: %s" % cherrypy.config['dropbox_client_id'],
context='ENGINE', severity=logging.INFO)
d.connect('dropbox_send', r'/ebooks/send/dropbox/{id:\d+}.{filetype}',
controller=dropbox, conditions=dict(function=check_id))
d.connect('dropbox_callback', r'/ebooks/send/dropbox/',
controller=dropbox)
if 'gdrive_client_id' in cherrypy.config:
import GDrive
gdrive = GDrive.GDrive
cherrypy.log("GDrive Client Id: %s" % cherrypy.config['gdrive_client_id'],
context='ENGINE', severity=logging.INFO)
d.connect('gdrive_send', r'/ebooks/send/gdrive/{id:\d+}.{filetype}',
controller=gdrive, conditions=dict(function=check_id))
d.connect('gdrive_callback', r'/ebooks/send/gdrive/',
controller=gdrive)
if 'msdrive_client_id' in cherrypy.config:
import MSDrive
msdrive = MSDrive.MSDrive
cherrypy.log("MSDrive Client Id: %s" % cherrypy.config['msdrive_client_id'],
context='ENGINE', severity=logging.INFO)
d.connect('msdrive_send', r'/ebooks/send/msdrive/{id:\d+}.{filetype}',
controller=msdrive, conditions=dict(function=check_id))
d.connect('msdrive_callback', r'/ebooks/send/msdrive/',
controller=msdrive)
cherrypy.log("Mounting root", context='ENGINE', severity=logging.INFO)
app = cherrypy.tree.mount(root=None, config=CHERRYPY_CONFIG)
app.merge({'/': {'request.dispatch': d}})
if cherrypy.config.get('devmode', False):
app.merge({'/gutenberg': {'tools.staticdir.on': True,
'tools.staticdir.dir': install_dir + "/gutenberg"}})
app.merge({'/pics': {'tools.staticdir.on': True,
'tools.staticdir.dir': install_dir + "/pics"}})
return app
def main():
""" Main function. """
# CherryPy HTTP server config
cherrypy.config.update({
'uid': 0,
'gid': 0,
'daemonize': False,
'pidfile': None,
'devmode': False,
})
extra_config = configure()
# Rotating Logs
# CherryPy will already open log files if present in config
error_file = access_file = ''
# read the logger file locations from config file.
if not cherrypy.log.error_file:
error_file = cherrypy.config.get('logger.error_file', '')
if not cherrypy.log.access_file:
access_file = cherrypy.config.get('logger.access_file', '')
# disable log file handlers
cherrypy.log.error_file = ""
cherrypy.log.access_file = ""
# set up python logging
max_bytes = getattr(cherrypy.log, "rot_max_bytes", 100 * 1024 * 1024)
backup_count = getattr(cherrypy.log, "rot_backup_count", 2)
if error_file:
h = logging.handlers.RotatingFileHandler(error_file, 'a', max_bytes, backup_count, 'utf-8')
h.setLevel(logging.WARNING)
h.setFormatter(cherrypy._cplogging.logfmt)
cherrypy.log.error_log.addHandler(h)
if access_file:
h = logging.handlers.RotatingFileHandler(access_file, 'a', max_bytes, backup_count, 'utf-8')
h.setLevel(logging.INFO)
h.setFormatter(cherrypy._cplogging.logfmt)
cherrypy.log.access_log.addHandler(h)
if not cherrypy.config['daemonize']:
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(cherrypy._cplogging.logfmt)
cherrypy.log.error_log.addHandler(ch)
# continue app init
#
cherrypy.log('*' * 80, context='ENGINE', severity=logging.INFO)
cherrypy.log("Using config file '%s'." % CHERRYPY_CONFIG,
context='ENGINE', severity=logging.INFO)
if extra_config:
cherrypy.log('extra_config: %s' % extra_config, context='ENGINE', severity=logging.INFO)
# after cherrypy.config is parsed
if hasattr(cherrypy.engine, 'signal_handler'):
cherrypy.engine.signal_handler.subscribe()
# start http server
#
cherrypy.log("Daemonizing", context='ENGINE', severity=logging.INFO)
if cherrypy.config['daemonize']:
plugins.Daemonizer(cherrypy.engine).subscribe()
uid = cherrypy.config['uid']
gid = cherrypy.config['gid']
if uid > 0 or gid > 0:
plugins.DropPrivileges(cherrypy.engine, uid=uid, gid=gid, umask=0o22).subscribe()
if cherrypy.config['pidfile']:
pid = plugins.PIDFile(cherrypy.engine, cherrypy.config['pidfile'])
# Write pidfile after privileges are dropped(prio == 77)
# or we will not be able to remove it.
cherrypy.engine.subscribe('start', pid.start, 78)
cherrypy.engine.subscribe('exit', pid.exit, 78)
app = get_app()
return app
if __name__ == '__main__':
main()
cherrypy.engine.start()
cherrypy.engine.block()