def run_webserver():
app = bottle.app()
app.catchall = False
app = Sentry(app, raven.Client(SENTRY_DSN))
bottle.run(app, server='paste', host='0.0.0.0', port=3350)
python类run()的实例源码
def w2v():
subWordPython = (request.forms.get('submittedWord')).lower()
#get IP address
ipAddress = request.environ.get('REMOTE_ADDR')
# logger.info('word: %s ip: %s' % (subWordPython, ipAddress))
#add subWordPython + ip address to user_words table every time.
conn = sqlite3.connect('/w2v/hp_w2v.db')
c = conn.cursor()
c.execute("INSERT INTO user_words (submitted_word, ip) VALUES (?, ?)", (subWordPython, ipAddress))
conn.commit()
conn.close()
#run w2v, if word is not in HP corpus, return keyerror.tpl
try:
wordResults = w2v_results(subWordPython)
except KeyError as err:
errorPage = template('/w2v/keyerror.tpl', word = subWordPython)
return (errorPage)
#return results to user
output = template('/w2v/results.tpl', rows = wordResults, word = subWordPython)
return (output)
#call BottleDaemon script and launch a daemon in the background
def theidfobject(idfindex, keyindex, objindex):
idf, edges = eppystuff.an_idfedges(idfindex)
objkeys = idf_helpers.idfobjectkeys(idf)
objkey = objkeys[keyindex]
idfobjects = idf.idfobjects[objkey]
idfobject = idfobjects[objindex]
fields = idfobject.objls
values = idfobject.obj
valuesfields = [(value, field) for value, field in zip(values, fields)]
urls = ["%s/%s" % (objindex, field) for field in fields]
linktags = ['<a href=%s>%s %s %s</a>' % (url, i, abullet, value,)
for i, (url, value) in enumerate(zip(urls, values))]
iddinfos = ['<a href=%s/iddinfo>%s</a>' % (url, '?')
for url in urls]
lines = ["%s %s %s %s %s" % (linktag, aspace, field, abullet, iddinfo)
for linktag, field, iddinfo in zip(linktags, fields, iddinfos)]
# ---
lines.pop(0)
url = 'showlinks/%s' % (objindex, )
showlinkslink = '<a href=%s>show links to other objects</a>' % (url, )
url = 'nodementions/%s' % (objindex, )
showmentionslink = '<a href=%s>show node connections</a> <hr>' % (url, )
url = 'objfunctions/%s' % (objindex, )
objfunctionslink = '<hr> <a href=%s>run functions of this object</a>' % (url, )
lines.append(objfunctionslink)
url = 'refferingobjs/%s' % (objindex, )
refferingobjslink = '<a href=%s>Show objects that refer to this object</a> ->this runs slow :-(' % (url, )
lines.append(refferingobjslink)
url = 'mentioningobjs/%s' % (objindex, )
mentioningobjslink = '<a href=%s>Show objects that mention this object</a>' % (url, )
lines.append(mentioningobjslink)
# - hvac links
url = 'hvacprevnext/%s' % (objindex, )
hvacprevnextlink = 'HVAC object in loop -> <a href=%s>prev objects & next objects</a>' % (url, )
lines.append(hvacprevnextlink)
# -
heading = '%s <a href=%s/key/iddinfo> %s</a>' % (objkey, objindex, '?')
headingdoc = '<a href="%s" target="_blank">docs</a>' % (getdoclink(objkey.upper()))
headingwithdoc = '%s (%s)' % (heading, headingdoc)
lineswithtitle = [headingwithdoc, "=" * len(objkey)] + lines
lineswithtitle.insert(0, showmentionslink)
lineswithtitle.insert(0, showlinkslink)
lineswithtitle = putfilenameontop(idf, lineswithtitle)
html = '<br>'.join(lineswithtitle)
return html
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 daemon_run(host="localhost", port="8080", pidfile=None, logfile=None,
keyfile='priv.key', certfile='pub.crt', cafile='ca.crt',
action="start"):
"""
Get the bottle 'run' function running in the background as a daemonized
process.
:host: The host interface to listen for connections on. Enter 0.0.0.0
to listen on all interfaces. Defaults to localhost.
:port: The host port to listen on. Defaults to 8080.
:pidfile: The file to use as the process id file. Defaults to "bottle.pid"
:logfile: The file to log stdout and stderr from bottle to. Defaults to "bottle.log"
"""
if pidfile is None:
pidfile = os.path.join(
os.getcwd(),
"bottle.pid"
)
if logfile is None:
logfile = os.path.join(
os.getcwd(),
"bottle.log"
)
if action == "start":
log = open(logfile, "w+")
context = daemon.DaemonContext(
pidfile=__locked_pidfile(pidfile),
stdout=log,
stderr=log
)
with context:
# bottle.run(host=host, port=port)
srv = SSLWSGIRefServer(host=host, port=port, keyfile=keyfile,
certfile=certfile, cafile=cafile)
bottle.run(server=srv)
else:
with open(pidfile, "r") as p:
pid = int(p.read())
os.kill(pid, signal.SIGTERM)
def main():
starttime = time.time()
#parser = argparse.ArgumentParser(description='')
#parser.add_argument("action", choices=["start", "stop"])
#parser.add_argument("--basemodel", dest="model", help="base model path")
#parser.add_argument("-t", "--test", action="store_true",
# help="run a test instead of the server")
#parser.add_argument("--log", action="store", dest="loglevel", default="WARNING", help="Log level")
#options = parser.parse_args()
numeric_level = getattr(logging, "DEBUG", None)
#if not isinstance(numeric_level, int):
# raise ValueError('Invalid log level: %s' % options.loglevel)
#while len(logging.root.handlers) > 0:
# logging.root.removeHandler(logging.root.handlers[-1])
logging_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)s:%(funcName)s %(message)s'
logging.basicConfig(level=numeric_level, format=logging_format)
logging.getLogger().setLevel(numeric_level)
logging.debug("Initializing the server...")
server = IBENT(entities=[("mirtex_train_mirna_sner", "stanfordner", "mirna"),
("chemdner_train_all", "stanfordner", "chemical"),
("banner", "banner", "gene"),
("genia_sample_gene", "stanfordner", "gene")],
relations=[("all_ddi_train_slk", "jsre", "ddi"),
("mil_classifier4k", "smil", "mirna-gene")])
logging.debug("done.")
# Test server
bottle.route("/ibent/status")(server.hello)
# Fetch an existing document
bottle.route("/ibent/<doctag>")(server.get_document)
# Create a new document
bottle.route("/ibent/<doctag>", method='POST')(server.new_document)
# Get new entity annotations i.e. run a classifier again
bottle.route("/ibent/entities/<doctag>/<annotator>", method='POST')(server.run_entity_annotator)
# Get entity annotations i.e. fetch from the database
bottle.route("/ibent/entities/<doctag>/<annotator>")(server.get_annotations)
# Get new entity annotations i.e. run a classifier again
bottle.route("/ibent/relations/<doctag>/<annotator>", method='POST')(server.run_relation_annotator)
# Get new entity annotations i.e. run a classifier again
bottle.route("/ibent/relations/<doctag>/<annotator>")(server.get_relations)
# Get entity annotations i.e. fetch from the database
#bottle.route("/ibent/entities/<doctag>/<annotator>")(server.get_annotations)
#bottle.route("/iice/chemical/<text>/<modeltype>", method='POST')(server.process)
#bottle.route("/ibent/interactions", method='POST')(server.get_relations)
#daemon_run(host='10.10.4.63', port=8080, logfile="server.log", pidfile="server.pid")
bottle.run(host=config.host_ip, port=8080, DEBUG=True)