remove flask app

This commit is contained in:
j 2014-08-09 18:33:59 +02:00
parent 8b46a85d56
commit abf2bbf6a8
12 changed files with 70 additions and 71 deletions

View file

@ -10,7 +10,6 @@ import app
import server import server
if len(sys.argv) > 1 and sys.argv[1] == 'server': if len(sys.argv) > 1 and sys.argv[1] == 'server':
import server
server.run() server.run()
else: else:
app.manager.run() app.run()

View file

@ -2,17 +2,13 @@
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division
from flask import Flask
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
import logging import logging
import settings import settings
import db
import changelog import changelog
import item.models import item.models
import user.models import user.models
import item.person import item.person
@ -21,6 +17,7 @@ import api
import commands import commands
'''
app = Flask('openmedialibrary', static_folder=settings.static_path) app = Flask('openmedialibrary', static_folder=settings.static_path)
@ -42,3 +39,12 @@ manager.add_command('update_static', commands.UpdateStatic)
def main(path=None): def main(path=None):
return app.send_static_file('html/oml.html') return app.send_static_file('html/oml.html')
'''
def run():
import sys
command = sys.argv[1] if len(sys.argv) > 1 else None
if command and getattr(commands, "command_%s"%command):
getattr(commands, "command_%s"%command)(sys.argv[1:])
else:
print 'usage: ... fixme'
sys.exit(1)

View file

@ -15,8 +15,7 @@ logger = logging.getLogger('oml.downloads')
class Downloads(Thread): class Downloads(Thread):
def __init__(self, app): def __init__(self):
self._app = app
self._running = True self._running = True
Thread.__init__(self) Thread.__init__(self)
self.daemon = True self.daemon = True

View file

@ -10,16 +10,17 @@ from datetime import datetime
import tornado.web import tornado.web
from models import Item from models import Item
import settings import settings
import db
class OMLHandler(tornado.web.RequestHandler): class OMLHandler(tornado.web.RequestHandler):
def initialize(self, app): def initialize(self):
self._app = app pass
class EpubHandler(OMLHandler): class EpubHandler(OMLHandler):
def get(self, id, filename): def get(self, id, filename):
with self._app.app_context(): with db.session():
item = Item.get(id) item = Item.get(id)
path = item.get_path() path = item.get_path()
if not item or item.info['extension'] != 'epub' or not path: if not item or item.info['extension'] != 'epub' or not path:
@ -54,7 +55,7 @@ class FileHandler(OMLHandler):
self.get(id, include_body=False) self.get(id, include_body=False)
def get(self, id, include_body=True): def get(self, id, include_body=True):
with self._app.app_context(): with db.session():
item = Item.get(id) item = Item.get(id)
path = item.get_path() if item else None path = item.get_path() if item else None
if not item or not path: if not item or not path:
@ -70,7 +71,7 @@ class FileHandler(OMLHandler):
class ReaderHandler(OMLHandler): class ReaderHandler(OMLHandler):
def get(self, id): def get(self, id):
with self._app.app_context(): with db.session():
item = Item.get(id) item = Item.get(id)
if not item: if not item:
self.set_status(404) self.set_status(404)

View file

@ -9,7 +9,6 @@ import time
import ox import ox
from app import app
import settings import settings
import db import db
from item.models import File from item.models import File

View file

@ -13,6 +13,8 @@ import time
from utils import valid, get_public_ipv6, get_local_ipv4, get_interface from utils import valid, get_public_ipv6, get_local_ipv4, get_interface
from settings import preferences, server, USER_ID, sk from settings import preferences, server, USER_ID, sk
import state import state
import db
import user.models
logger = logging.getLogger('oml.localnodes') logger = logging.getLogger('oml.localnodes')
@ -36,10 +38,9 @@ class LocalNodesBase(Thread):
_PORT = 9851 _PORT = 9851
_TTL = 1 _TTL = 1
def __init__(self, app, nodes): def __init__(self, nodes):
self._active = True self._active = True
self._nodes = nodes self._nodes = nodes
self._app = app
Thread.__init__(self) Thread.__init__(self)
if not server['localnode_discovery']: if not server['localnode_discovery']:
return return
@ -113,8 +114,7 @@ class LocalNodesBase(Thread):
logger.debug('NEW NODE %s', data) logger.debug('NEW NODE %s', data)
if can_connect(data): if can_connect(data):
self._nodes[data['id']] = data self._nodes[data['id']] = data
with self._app.app_context(): with db.session():
import user.models
u = user.models.User.get_or_create(data['id']) u = user.models.User.get_or_create(data['id'])
u.info['username'] = data['username'] u.info['username'] = data['username']
u.info['local'] = data u.info['local'] = data
@ -196,13 +196,12 @@ class LocalNodes(object):
_nodes4 = None _nodes4 = None
_nodes6 = None _nodes6 = None
def __init__(self, app): def __init__(self):
self._nodes = {} self._nodes = {}
self._app = app
if not server['localnode_discovery']: if not server['localnode_discovery']:
return return
self._nodes4 = LocalNodes4(app, self._nodes) self._nodes4 = LocalNodes4(self._nodes)
self._nodes6 = LocalNodes6(app, self._nodes) self._nodes6 = LocalNodes6(self._nodes)
def get(self, user_id): def get(self, user_id):
if user_id in self._nodes: if user_id in self._nodes:

View file

@ -12,7 +12,7 @@ from websocket import trigger_event
import logging import logging
logger = logging.getLogger('oml.node.nodeapi') logger = logging.getLogger('oml.node.nodeapi')
def api_pullChanges(app, remote_id, user_id=None, from_=None, to=None): def api_pullChanges(remote_id, user_id=None, from_=None, to=None):
if user_id and not from_ and not to: if user_id and not from_ and not to:
from_ = user_id from_ = user_id
user_id = None user_id = None
@ -34,7 +34,7 @@ def api_pullChanges(app, remote_id, user_id=None, from_=None, to=None):
state.nodes.queue('add', remote_id) state.nodes.queue('add', remote_id)
return [c.json() for c in qs] return [c.json() for c in qs]
def api_pushChanges(app, user_id, changes): def api_pushChanges(user_id, changes):
user = User.get(user_id) user = User.get(user_id)
if not Changelog.apply_changes(user, changes): if not Changelog.apply_changes(user, changes):
logger.debug('FAILED TO APPLY CHANGE') logger.debug('FAILED TO APPLY CHANGE')
@ -42,7 +42,7 @@ def api_pushChanges(app, user_id, changes):
return False return False
return True return True
def api_requestPeering(app, user_id, username, message): def api_requestPeering(user_id, username, message):
user = User.get_or_create(user_id) user = User.get_or_create(user_id)
if not user.info: if not user.info:
user.info = {} user.info = {}
@ -61,7 +61,7 @@ def api_requestPeering(app, user_id, username, message):
return True return True
return False return False
def api_acceptPeering(app, user_id, username, message): def api_acceptPeering(user_id, username, message):
user = User.get(user_id) user = User.get(user_id)
logger.debug('incoming acceptPeering event: pending: %s', user.pending) logger.debug('incoming acceptPeering event: pending: %s', user.pending)
if user and user.peered: if user and user.peered:
@ -77,7 +77,7 @@ def api_acceptPeering(app, user_id, username, message):
return True return True
return False return False
def api_rejectPeering(app, user_id, message): def api_rejectPeering(user_id, message):
user = User.get(user_id) user = User.get(user_id)
if user: if user:
if not user.info: if not user.info:
@ -88,7 +88,7 @@ def api_rejectPeering(app, user_id, message):
return True return True
return False return False
def api_removePeering(app, user_id, message): def api_removePeering(user_id, message):
user = User.get(user_id) user = User.get(user_id)
if user: if user:
user.info['message'] = message user.info['message'] = message
@ -97,7 +97,7 @@ def api_removePeering(app, user_id, message):
return True return True
return False return False
def api_cancelPeering(app, user_id, message): def api_cancelPeering(user_id, message):
user = User.get(user_id) user = User.get(user_id)
if user: if user:
user.info['message'] = message user.info['message'] = message

View file

@ -26,9 +26,8 @@ logger = logging.getLogger('oml.node.server')
class NodeHandler(tornado.web.RequestHandler): class NodeHandler(tornado.web.RequestHandler):
def initialize(self, app): def initialize(self):
self.app = app pass
@tornado.web.asynchronous @tornado.web.asynchronous
@tornado.gen.coroutine @tornado.gen.coroutine
@ -63,7 +62,7 @@ class NodeHandler(tornado.web.RequestHandler):
'ip': self.request.remote_addr 'ip': self.request.remote_addr
} }
else: else:
content = yield tornado.gen.Task(api_call, self.app, action, key, args) content = yield tornado.gen.Task(api_call, action, key, args)
if content is None: if content is None:
content = {'status': 'not peered'} content = {'status': 'not peered'}
logger.debug('PEER %s IS UNKNOWN SEND 403', key) logger.debug('PEER %s IS UNKNOWN SEND 403', key)
@ -81,13 +80,13 @@ class NodeHandler(tornado.web.RequestHandler):
self.write('Open Media Library') self.write('Open Media Library')
@run_async @run_async
def api_call(app, action, key, args, callback): def api_call(action, key, args, callback):
with db.session(): with db.session():
u = user.models.User.get(key) u = user.models.User.get(key)
if action in ( if action in (
'requestPeering', 'acceptPeering', 'rejectPeering', 'removePeering' 'requestPeering', 'acceptPeering', 'rejectPeering', 'removePeering'
) or (u and u.peered): ) or (u and u.peered):
content = getattr(nodeapi, 'api_' + action)(app, key, *args) content = getattr(nodeapi, 'api_' + action)(key, *args)
else: else:
if u and u.pending: if u and u.pending:
logger.debug('ignore request from pending peer[%s] %s (%s)', key, action, args) logger.debug('ignore request from pending peer[%s] %s (%s)', key, action, args)
@ -98,12 +97,13 @@ def api_call(app, action, key, args, callback):
class ShareHandler(tornado.web.RequestHandler): class ShareHandler(tornado.web.RequestHandler):
def initialize(self, app): def initialize(self):
self.app = app pass
def get(self, id): def get(self, id):
with self.app.app_context(): import db
import item.models import item.models
with db.session():
i = item.models.Item.get(id) i = item.models.Item.get(id)
if not i: if not i:
self.set_status(404) self.set_status(404)
@ -123,14 +123,14 @@ class ShareHandler(tornado.web.RequestHandler):
break break
self.write(data) self.write(data)
def publish_node(app): def publish_node():
update_online() update_online()
if state.online: if state.online:
with db.session(): with db.session():
for u in user.models.User.query.filter_by(queued=True): for u in user.models.User.query.filter_by(queued=True):
logger.debug('adding queued node... %s', u.id) logger.debug('adding queued node... %s', u.id)
state.nodes.queue('add', u.id) state.nodes.queue('add', u.id)
state.check_nodes = PeriodicCallback(lambda: check_nodes(app), 120000) state.check_nodes = PeriodicCallback(check_nodes, 120000)
state.check_nodes.start() state.check_nodes.start()
state._online = PeriodicCallback(update_online, 60000) state._online = PeriodicCallback(update_online, 60000)
state._online.start() state._online.start()
@ -159,7 +159,7 @@ def update_online():
'online': state.online 'online': state.online
}) })
def check_nodes(app): def check_nodes():
if state.online: if state.online:
with db.session(): with db.session():
for u in user.models.User.query.filter_by(queued=True): for u in user.models.User.query.filter_by(queued=True):
@ -167,10 +167,10 @@ def check_nodes(app):
logger.debug('queued peering message for %s trying to connect...', u.id) logger.debug('queued peering message for %s trying to connect...', u.id)
state.nodes.queue('add', u.id) state.nodes.queue('add', u.id)
def start(app): def start():
application = Application([ application = Application([
(r"/get/(.*)", ShareHandler, dict(app=app)), (r"/get/(.*)", ShareHandler),
(r".*", NodeHandler, dict(app=app)), (r".*", NodeHandler),
], gzip=True) ], gzip=True)
if not os.path.exists(settings.ssl_cert_path): if not os.path.exists(settings.ssl_cert_path):
settings.server['cert'] = cert.generate_ssl() settings.server['cert'] = cert.generate_ssl()
@ -180,5 +180,5 @@ def start(app):
"keyfile": settings.ssl_key_path "keyfile": settings.ssl_key_path
}) })
http_server.listen(settings.server['node_port'], settings.server['node_address']) http_server.listen(settings.server['node_port'], settings.server['node_address'])
state.main.add_callback(publish_node, app) state.main.add_callback(publish_node)
return http_server return http_server

View file

@ -42,7 +42,6 @@ class Node(Thread):
def __init__(self, nodes, user): def __init__(self, nodes, user):
self._nodes = nodes self._nodes = nodes
self._app = nodes._app
self.user_id = user.id self.user_id = user.id
key = str(user.id) key = str(user.id)
self.vk = ed25519.VerifyingKey(key, encoding=ENCODING) self.vk = ed25519.VerifyingKey(key, encoding=ENCODING)
@ -358,11 +357,10 @@ class Nodes(Thread):
_nodes = {} _nodes = {}
_local = None _local = None
def __init__(self, app): def __init__(self):
self._app = app
self._q = Queue() self._q = Queue()
self._running = True self._running = True
self._local = LocalNodes(app) self._local = LocalNodes()
Thread.__init__(self) Thread.__init__(self)
self.daemon = True self.daemon = True
self.start() self.start()

View file

@ -72,7 +72,7 @@ def trim(docstring):
@run_async @run_async
def api_task(app, request, callback): def api_task(request, callback):
action = request.arguments.get('action', [None])[0] action = request.arguments.get('action', [None])[0]
data = request.arguments.get('data', ['{}'])[0] data = request.arguments.get('data', ['{}'])[0]
data = json.loads(data) if data else {} data = json.loads(data) if data else {}
@ -98,8 +98,8 @@ def api_task(app, request, callback):
callback(response) callback(response)
class ApiHandler(tornado.web.RequestHandler): class ApiHandler(tornado.web.RequestHandler):
def initialize(self, app): def initialize(self):
self._app = app pass
def get(self): def get(self):
self.write('use POST') self.write('use POST')
@ -113,7 +113,7 @@ class ApiHandler(tornado.web.RequestHandler):
self.write('') self.write('')
return return
response = yield tornado.gen.Task(api_task, self._app, self.request) response = yield tornado.gen.Task(api_task, self.request)
if not 'status' in response: if not 'status' in response:
response = json_response(response) response = json_response(response)
response = json_dumps(response) response = json_dumps(response)

View file

@ -8,7 +8,6 @@ from tornado.web import StaticFileHandler, Application
from tornado.httpserver import HTTPServer from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop from tornado.ioloop import IOLoop
from app import app
import settings import settings
import websocket import websocket
import logging import logging
@ -49,14 +48,14 @@ def run():
handlers = [ handlers = [
(r'/(favicon.ico)', StaticFileHandler, {'path': static_path}), (r'/(favicon.ico)', StaticFileHandler, {'path': static_path}),
(r'/static/(.*)', StaticFileHandler, {'path': static_path}), (r'/static/(.*)', StaticFileHandler, {'path': static_path}),
(r'/(.*)/epub/(.*)', EpubHandler, dict(app=app)), (r'/(.*)/epub/(.*)', EpubHandler),
(r'/(.*?)/reader/', ReaderHandler, dict(app=app)), (r'/(.*?)/reader/', ReaderHandler),
(r'/(.*?)/pdf/', FileHandler, dict(app=app)), (r'/(.*?)/pdf/', FileHandler),
(r'/(.*?)/txt/', FileHandler, dict(app=app)), (r'/(.*?)/txt/', FileHandler),
(r'/(.*)/(cover|preview)(\d*).jpg', IconHandler, dict(app=app)), (r'/(.*)/(cover|preview)(\d*).jpg', IconHandler),
(r'/api/', oxtornado.ApiHandler, dict(app=app)), (r'/api/', oxtornado.ApiHandler),
(r'/ws', websocket.Handler), (r'/ws', websocket.Handler),
(r"(.*)", MainHandler, dict(app=app)), (r"(.*)", MainHandler),
] ]
http_server = HTTPServer(Application(handlers, **options)) http_server = HTTPServer(Application(handlers, **options))
@ -69,21 +68,21 @@ def run():
state.main = IOLoop.instance() state.main = IOLoop.instance()
state.cache = Cache(ttl=10) state.cache = Cache(ttl=10)
state.tasks = tasks.Tasks(app) state.tasks = tasks.Tasks()
def start_node(): def start_node():
import user import user
import downloads import downloads
import nodes import nodes
import db import db
state.node = node.server.start(app) state.node = node.server.start()
state.nodes = nodes.Nodes(app) state.nodes = nodes.Nodes()
state.downloads = downloads.Downloads(app) state.downloads = downloads.Downloads()
def add_users(app): def add_users():
with db.session(): with db.session():
for p in user.models.User.query.filter_by(peered=True): for p in user.models.User.query.filter_by(peered=True):
state.nodes.queue('add', p.id) state.nodes.queue('add', p.id)
state.main.add_callback(add_users, app) state.main.add_callback(add_users)
state.main.add_callback(start_node) state.main.add_callback(start_node)
if ':' in settings.server['address']: if ':' in settings.server['address']:
host = '[%s]' % settings.server['address'] host = '[%s]' % settings.server['address']

View file

@ -13,10 +13,9 @@ logger = logging.getLogger('oml.websocket')
class Tasks(Thread): class Tasks(Thread):
def __init__(self, app): def __init__(self):
self.q = Queue() self.q = Queue()
self.connected = True self.connected = True
self._app = app
Thread.__init__(self) Thread.__init__(self)
self.daemon = True self.daemon = True
self.start() self.start()