/
app.py
153 lines (125 loc) · 4.66 KB
/
app.py
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
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# Author: Binux<i@binux.me>
# http://binux.me
# Created on 2014-02-22 23:17:13
import os
import sys
import signal
import logging
logger = logging.getLogger("webui")
import gunicorn.app.base
from six import reraise
from six.moves import builtins
from six.moves.urllib.parse import urljoin
from flask import Flask
from pyspider.fetcher import tornado_fetcher
if os.name == 'nt':
import mimetypes
mimetypes.add_type("text/css", ".css", True)
class QuitableFlask(Flask):
"""Add quit() method to Flask object"""
@property
def logger(self):
return logger
def run(self, host=None, port=None, debug=None, **options):
from werkzeug.serving import make_server, run_with_reloader
if host is None:
host = '127.0.0.1'
if port is None:
server_name = self.config['SERVER_NAME']
if server_name and ':' in server_name:
port = int(server_name.rsplit(':', 1)[1])
else:
port = 5000
if debug is not None:
self.debug = bool(debug)
hostname = host
port = port
application = self
use_reloader = self.debug
use_debugger = self.debug
if use_debugger:
from werkzeug.debug import DebuggedApplication
application = DebuggedApplication(application, True)
try:
from .webdav import dav_app
except ImportError as e:
logger.error('WebDav interface not enabled: %r', e)
dav_app = None
if dav_app:
from werkzeug.wsgi import DispatcherMiddleware
application = DispatcherMiddleware(application, {
'/dav': dav_app
})
def inner():
self.server = make_server(hostname, port, application)
self.server.serve_forever()
if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
display_hostname = hostname != '*' and hostname or 'localhost'
if ':' in display_hostname:
display_hostname = '[%s]' % display_hostname
self.logger.info('webui running on http://%s:%d/', display_hostname, port)
if use_reloader:
run_with_reloader(inner)
else:
inner()
def quit(self):
if hasattr(self, 'server'):
self.server.shutdown_signal = True
self.logger.info('webui exiting...')
class GunicornApplication(gunicorn.app.base.Application):
def __init__(self, app, options=None):
self.options = options or {}
self.application = app
super(GunicornApplication, self).__init__()
def load_config(self):
pass
def init(self, parser, opts, args):
config = dict([(key, value) for key, value in self.options.iteritems()
if key in self.cfg.settings and value is not None])
for key, value in config.iteritems():
self.cfg.set(key.lower(), value)
def load(self):
return self.application
class GunicornFlask(QuitableFlask):
def run(self, host=None, port=None, debug=None, **options):
options.update({
'bind': '%s:%s' % (host or '0.0.0.0', port or 5000),
'reload': debug or False,
'preload': True
})
self.pid = os.getpid()
self.gunicorn_server = GunicornApplication(self, options)
self.gunicorn_server.run()
def quit(self):
if hasattr(self, 'pid'):
os.kill(self.pid, signal.SIGTERM)
app = GunicornFlask('webui',
static_folder=os.path.abspath(os.path.join(os.path.dirname(__file__), 'static')),
template_folder=os.path.abspath(os.path.join(os.path.dirname(__file__), 'templates')))
app.secret_key = os.urandom(24)
app.jinja_env.line_statement_prefix = '#'
app.jinja_env.globals.update(builtins.__dict__)
app.config.update({
'fetch': lambda x: tornado_fetcher.Fetcher(None, None, async=False).fetch(x)[1],
'taskdb': None,
'projectdb': None,
'scheduler_rpc': None,
'queues': dict(),
})
def cdn_url_handler(error, endpoint, kwargs):
if endpoint == 'cdn':
path = kwargs.pop('path')
# cdn = app.config.get('cdn', 'http://cdn.staticfile.org/')
# cdn = app.config.get('cdn', '//cdnjs.cloudflare.com/ajax/libs/')
cdn = app.config.get('cdn', '//cdnjscn.b0.upaiyun.com/libs/')
return urljoin(cdn, path)
else:
exc_type, exc_value, tb = sys.exc_info()
if exc_value is error:
reraise(exc_type, exc_value, tb)
else:
raise error
app.handle_url_build_error = cdn_url_handler