def __init__(self, host='', porta=8080):
self._h = host
self._p = porta
self._a = Bottle()
self._rota()
self._g = core
python类Bottle()的实例源码
def __init__(self, host, port):
serv_host = FLAGS.host
serv_port = FLAGS.port
model_name = FLAGS.model_name
model_version = FLAGS.model_version
self.request_timeout = FLAGS.request_timeout
config = tf.ConfigProto(log_device_placement=False)
config.gpu_options.allow_growth = True
self.sess = tf.Session(config=config)
init = tf.global_variables_initializer()
config = Config()
self.woipv = WoipvPspNetModel(config)
self.input_tensor = tf.placeholder(tf.string, name="input_tensor")
processed = tf.cast(tf.decode_raw(self.input_tensor, tf.uint8), tf.float32)
processed = tf.reshape(processed, [288, 288, 3])
self.image_op = processed
processed = tf.image.per_image_standardization(processed)
processed = tf.expand_dims(processed, axis=0)
self.result_op = tf.nn.sigmoid(self.woipv.inference(processed))
self.sess.run(init)
ckpt = tf.train.get_checkpoint_state("/training/woipv_train")
ckpt_name = os.path.basename(ckpt.model_checkpoint_path)
variables_to_restore = tf.global_variables()
chkpt_saver = tf.train.Saver(variables_to_restore,
write_version=tf.train.SaverDef.V2)
chkpt_saver.restore(self.sess, ckpt.model_checkpoint_path)
self._host = host
self._port = port
self._app = bottle.Bottle()
self._route()
def create_app(engine):
app = Bottle()
@app.error()
@app.error(404)
def handle_error(error):
if issubclass(type(error.exception), ApiException):
response.status = error.exception.code
else:
response.status = error.status_code
response.set_header('Content-type', 'application/json')
resp = {
'type': type(error.exception).__name__,
'message': repr(error.exception) if error.exception else '',
'traceback': error.traceback,
'status_code': response.status
}
log.error('Exception, type=%s, message=%s, status_code=%s, traceback=%s'\
% (resp['type'], resp['message'], resp['status_code'], resp['traceback']))
return '%s %s' % (resp['status_code'], resp['message'])
@app.route('/ping', method=['GET'])
def ping():
return {'name': 'xFlow', 'version': '0.1' }
@app.route('/publish', method=['POST'])
def publish():
data = json.loads(request.body.read())
try:
publish_schema.validate(data)
except jsonschema.ValidationError as err:
raise BadRequest(err)
stream = data['stream']
event = json.dumps(data['event'])
try:
engine.publish(stream, event)
except core.KinesisStreamDoesNotExist as ex:
raise NotFoundException(str(ex))
return {}
@app.route('/track/workflows/<workflow_id>/executions/<execution_id>', method=['GET'])
def track(workflow_id, execution_id):
try:
tracking_info = engine.track(workflow_id, execution_id)
return tracking_info
except (core.CloudWatchStreamDoesNotExist,
core.WorkflowDoesNotExist,
core.CloudWatchLogDoesNotExist) as ex:
raise NotFoundException(str(ex))
raise Exception("Something went wrong!")
return app
def _start_server(self):
class BottleServerAdapter(bottle.ServerAdapter):
proxy = self
def close_session(self):
self.proxy.ctx.model.log._session.remove()
def run(self, app):
class Server(wsgiref.simple_server.WSGIServer):
allow_reuse_address = True
bottle_server = self
def handle_error(self, request, client_address):
pass
def serve_forever(self, poll_interval=0.5):
try:
wsgiref.simple_server.WSGIServer.serve_forever(self, poll_interval)
finally:
# Once shutdown is called, we need to close the session.
# If the session is not closed properly, it might raise warnings,
# or even lock the database.
self.bottle_server.close_session()
class Handler(wsgiref.simple_server.WSGIRequestHandler):
def address_string(self):
return self.client_address[0]
def log_request(*args, **kwargs): # pylint: disable=no-method-argument
if not self.quiet:
return wsgiref.simple_server.WSGIRequestHandler.log_request(*args,
**kwargs)
server = wsgiref.simple_server.make_server(
host=self.host,
port=self.port,
app=app,
server_class=Server,
handler_class=Handler)
self.proxy.server = server
self.proxy._started.put(True)
server.serve_forever(poll_interval=0.1)
def serve():
# Since task is a thread_local object, we need to patch it inside the server thread.
self._ctx_patcher(self.ctx)
bottle_app = bottle.Bottle()
bottle_app.post('/', callback=self._request_handler)
bottle.run(
app=bottle_app,
host='localhost',
port=self.port,
quiet=True,
server=BottleServerAdapter)
thread = threading.Thread(target=serve)
thread.daemon = True
thread.start()
return thread
def get_app(self):
'''Eliminate the builder by producing a new Bottle application.
This should be the final call in your method chain. It uses all
of the built up options to create a new Bottle application.
:rtype: :class:`bottle.Bottle`
'''
if self.config is None:
# If the user never sets a config instance, then just create
# a default.
self.config = Config()
if self.mount_prefix is None:
self.mount_prefix = self.config.config.get('url_prefix')
self.inject('config', lambda: self.config)
self.inject('kvlclient', lambda: self.config.kvlclient)
self.inject('store', lambda: self.config.store)
self.inject('label_store', lambda: self.config.label_store)
self.inject('tags', lambda: self.config.tags)
self.inject('search_engines', lambda: self.search_engines)
self.inject('filters', lambda: self.filters)
self.inject('request', lambda: bottle.request)
self.inject('response', lambda: bottle.response)
# DEPRECATED. Remove. ---AG
self.inject('visid_to_dbid', lambda: self.visid_to_dbid)
self.inject('dbid_to_visid', lambda: self.dbid_to_visid)
# Also DEPRECATED.
self.inject('label_hooks', lambda: [])
# Load routes defined in entry points.
for extroute in self.config.config.get('external_routes', []):
mod, fun_name = extroute.split(':')
logger.info('Loading external route: %s', extroute)
fun = getattr(__import__(mod, fromlist=[fun_name]), fun_name)
self.add_routes(fun())
# This adds the `json=True` feature on routes, which always coerces
# the output to JSON. Bottle, by default, only permits dictionaries
# to be JSON, which is the correct behavior. (Because returning JSON
# arrays is a hazard.)
#
# So we should fix the routes and then remove this. ---AG
self.app.install(JsonPlugin())
# Throw away the app and return it. Because this is elimination!
app = self.app
self.app = None
if self.mount_prefix is not None:
root = bottle.Bottle()
root.mount(self.mount_prefix, app)
return root
else:
return app