def __init__(self, configuration):
self.client_queue = multiprocessing.Queue(0)
self.apply_patch()
self.logger = self.init_logger()
if ["debug", "html", "content_type", "notify", "ports"] not in configuration:
raise PJFMissingArgument()
if configuration.debug:
print("[\033[92mINFO\033[0m] Starting HTTP ({0}) and HTTPS ({1}) built-in server...".format(
configuration.ports["servers"]["HTTP_PORT"],
configuration.ports["servers"]["HTTPS_PORT"]
))
if not configuration.content_type:
configuration.content_type = False
if not configuration.content_type:
configuration.content_type = "application/json"
self.config = configuration
self.json = PJFFactory(configuration)
self.https = SSLWSGIRefServer(host="0.0.0.0", port=self.config.ports["servers"]["HTTPS_PORT"])
self.http = WSGIRefServer(host="0.0.0.0", port=self.config.ports["servers"]["HTTP_PORT"])
self.httpsd = multiprocessing.Process(target=run, kwargs={"server": self.https, "quiet": True})
self.httpd = multiprocessing.Process(target=run, kwargs={"server": self.http, "quiet": True})
if self.config.fuzz_web:
self.request_checker = Thread(target=self.request_pool, args=())
self.logger.debug("[{0}] - PJFServer successfully initialized".format(time.strftime("%H:%M:%S")))
python类run()的实例源码
def main():
if len(sys.argv) > 1:
print "Serves the demo. Needs bottle.py to run. Will serve via bjoern"
print "if installed, otherwise via wsgi_ref. Reads its configuration "
print "from config.ini."
return
# load configuration
port = int(CONFIG.get('port', 9090))
staticdir = os.path.join(os.path.dirname(__file__), 'static')
# start web server
print "Starting web server on localhost:%d..." % port
app.route('/static/:path#.+#', callback=lambda path:
bottle.static_file(path, root=staticdir))
try:
import bjoern
except ImportError:
bjoern = None
bottle.run(app, host='localhost', port=port,
server='bjoern' if bjoern else 'wsgiref')
def run(self, handler):
from wsgiref.simple_server import make_server, WSGIRequestHandler
import ssl
if self.quiet:
class QuietHandler(WSGIRequestHandler):
def log_request(*args, **kw):
pass
self.options['handler_class'] = QuietHandler
srv = make_server(self.host, self.port, handler, **self.options)
srv.socket = ssl.wrap_socket(
srv.socket,
keyfile=self.keyfile,
certfile=self.certfile,
ca_certs=self.cafile,
cert_reqs=ssl.CERT_REQUIRED,
server_side=True)
srv.serve_forever()
def db_create():
"Create database tables"
try:
print("- DROPPING DATABASE")
r.db_drop('census').run(conn())
except:
pass
print("- CREATING DATABASE")
r.db_create('census').run(conn())
print("- CREATING USER TABLE")
r.table_create('users', primary_key='identity').run(conn())
print("- CREATING USER INDEXES")
r.table('users').index_create("identity_check", [r.row["identity_type"], r.row["identity"]]).run(conn())
r.table('users').index_wait("identity_check").run(conn())
r.table_create('result_cache', primary_key='name').run(conn())
print("- CREATING QUESTION TABLES")
for page in config['PAGES']:
for question in page.questions:
r.table_create("%s_answers" % question.name, primary_key='user_identity').run(conn())
def do_delete(keyword):
keyword = keyword.replace("_", " ")
new_file = ""
with open("keywords.txt", "r") as f:
file = f.readlines()
f.close()
for line in file:
line = line.rstrip('\n\t ')
line = line.strip('\t ')
line = line.strip('\r')
if line == keyword:
continue
else:
new_file += line +"\n"
new_file = new_file.rstrip('\n')
with open("keywords.txt", "w") as f:
f.write(new_file)
return "Keyword was deleted successfully.\n"
# run api
def run(self, handler):
class QuietHandler(WSGIRequestHandler):
def log_request(*args, **kw):
pass
def log_error(self, format, *args):
pass
self.options['handler_class'] = QuietHandler
srv = make_server(self.host, self.port, handler, **self.options)
srv.serve_forever()
def run(self, handler):
class QuietHandler(WSGIRequestHandler):
def log_request(*args, **kw):
pass
def log_error(self, format, *args):
pass
self.options['handler_class'] = QuietHandler
srv = make_server(self.host, self.port, handler, **self.options)
srv.socket = ssl.wrap_socket(srv.socket, certfile=CERT_PATH, server_side=True)
srv.serve_forever()
def run(self):
"""
Start the servers
"""
route("/")(self.serve)
if self.config.html:
route("/<filepath:path>")(self.custom_html)
if self.config.fuzz_web:
self.request_checker.start()
self.httpd.start()
self.httpsd.start()
def __init__(self, host, port):
# associate the session to our app
local_app = SessionMiddleware(bottle.app())
bottle.run(
app=local_app,
server='cherrypy',
host=host,
port=port,
reloader=True
)
def execute():
app = request.forms['app']
user = request.forms['user']
cid = request.forms['cid']
desc = request.forms['desc']
np = request.forms['np']
appmod = pickle.loads(request.forms['appmod'])
# remove the appmod key
del request.forms['appmod']
appmod.write_params(request.forms, user)
# if preprocess is set run the preprocessor
try:
if appmod.preprocess:
run_params, _, _ = appmod.read_params(user, cid)
base_dir = os.path.join(user_dir, user, app)
process.preprocess(run_params, appmod.preprocess, base_dir)
if appmod.preprocess == "terra.in":
appmod.outfn = "out"+run_params['casenum']+".00"
except:
return template('error', err="There was an error with the preprocessor")
# submit job to queue
try:
priority = db(users.user==user).select(users.priority).first().priority
uid = users(user=user).id
jid = sched.qsub(app, cid, uid, np, priority, desc)
return str(jid)
#redirect("http://localhost:"+str(config.port)+"/case?app="+str(app)+"&cid="+str(cid)+"&jid="+str(jid))
except OSError:
return "ERROR: a problem occurred"
def main():
sched.poll()
run(host='0.0.0.0', port=config.port+1, debug=False)
def execute():
app = request.forms['app']
user = request.forms['user']
cid = request.forms['cid']
desc = request.forms['desc']
np = request.forms['np']
appmod = pickle.loads(request.forms['appmod'])
# remove the appmod key
del request.forms['appmod']
appmod.write_params(request.forms, user)
# if preprocess is set run the preprocessor
try:
if appmod.preprocess:
run_params, _, _ = appmod.read_params(user, cid)
base_dir = os.path.join(user_dir, user, app)
process.preprocess(run_params, appmod.preprocess, base_dir)
if appmod.preprocess == "terra.in":
appmod.outfn = "out"+run_params['casenum']+".00"
except:
return template('error', err="There was an error with the preprocessor")
# submit job to queue
try:
priority = db(users.user==user).select(users.priority).first().priority
uid = users(user=user).id
jid = sched.qsub(app, cid, uid, np, priority, desc)
return str(jid)
#redirect("http://localhost:"+str(config.port)+"/case?app="+str(app)+"&cid="+str(cid)+"&jid="+str(jid))
except OSError:
return "ERROR: a problem occurred"
def run(self, handler):
server = wsgiserver.CherryPyWSGIServer((self.host, self.port), handler)
server.ssl_adapter = SecuredSSLServer(ssl_cert, ssl_key)
try:
server.start()
finally:
server.stop()
def main():
setup.setup_common()
model.connect()
if FLAGS.run_cron_in_background:
_run_cron_in_background()
bottle.run(
# wsgiref is unstable with reloader.
# See: https://github.com/bottlepy/bottle/issues/155
server='paste',
port=FLAGS.port,
host='0.0.0.0',
reloader=True)
def start_listening():
logger.info("Running bottle app: quiet=%s, port=%s, host='0.0.0.0'" % (quiet_bottle, port))
bottle.run(app=app, quiet=quiet_bottle, port=port, host='0.0.0.0')
def web_server_worker(data_q, config):
wsapp = WService(queue=data_q, config=config)
wrouter = WRouter(wsapp)
wrouter.route_server(config.server())
# Start SSL-wrapped bottle
logging.info('Starting Webservice server (daemon) ')
sslsrv = SSLWSGIRefServer(host=config.server()['web']['host'],
port=config.server()['web']['port'])
bottle.run(server=sslsrv, debug=config.server()['web']['debug'],
quiet=config.server()['web']['quiet'])
return
def web_client_worker(data_q, config):
wsapp = WService(queue=data_q, config=config)
wrouter = WRouter(wsapp)
wrouter.route_client(config.client())
# Start SSL-wrapped bottle
sslsrv = SSLWSGIRefServer(host=config.client()['web']['host'],
port=config.client()['web']['port'])
logging.info('Starting Webservice client (daemon) ')
bottle.run(server=sslsrv, debug=config.client()['web']['debug'],
quiet=config.client()['web']['quiet'])
return
def main():
parser = argparse.ArgumentParser(description='') # @TODO fill in
# server options
parser.add_argument('-host', '--host', default="localhost", help='host for the server')
parser.add_argument('-p', '--port', default=8080, help='port for the server')
parser.add_argument('--debug', action='store_true', dest="debug", help='Debug mode (autoreloads the server)')
parser.add_argument('--server', default="auto", help='Server backend to use (see http://bottlepy.org/docs/dev/deployment.html#switching-the-server-backend)')
# elasticsearch options
parser.add_argument('--es-host', default="localhost", help='host for the elasticsearch instance')
parser.add_argument('--es-port', default=9200, help='port for the elasticsearch instance')
parser.add_argument('--es-url-prefix', default='', help='Elasticsearch url prefix')
parser.add_argument('--es-use-ssl', action='store_true', help='Use ssl to connect to elasticsearch')
parser.add_argument('--es-index', default='charitysearch', help='index used to store charity data')
parser.add_argument('--es-type', default='charity', help='type used to store charity data')
args = parser.parse_args()
app.config["es"] = Elasticsearch(
host=args.es_host,
port=args.es_port,
url_prefix=args.es_url_prefix,
use_ssl=args.es_use_ssl
)
app.config["es_index"] = args.es_index
app.config["es_type"] = args.es_type
bottle.debug(args.debug)
bottle.run(app, server=args.server, host=args.host, port=args.port, reloader=args.debug)
def local(reload, port):
"""run local app server, assumes into the account
"""
import logging
from bottle import run
from app import controller, app
from c7n.resources import load_resources
load_resources()
print("Loaded resources definitions")
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('botocore').setLevel(logging.WARNING)
if controller.db.provision():
print("Table Created")
run(app, reloader=reload, port=port)
def delete(entry_id):
entry = GuestbookEntry.get(entry_id)
if not entry:
return "<h1>Entry not found.</h1>"
entry.delete()
return redirect("/")
# [END delete-route]
# [START run]
def do_login():
username = request.forms.username
password = request.forms.password
user = User.login(username, password)
if not user:
return {"error": "Invalid credentials."}
create_session(user)
return redirect("/")
# [END login]
# [START run]
def run(self):
print("shutter dash")
def __init__(self, bot, **kwargs):
super().__init__(**kwargs)
self.bot = bot
self.file = os.path.join('data', 'ricedb.json')
datadir = os.path.dirname(self.file)
try:
with open(self.file, 'r') as fd:
self.update(json.load(fd))
except FileNotFoundError:
# Database file itself doesn't need to exist on first run, it will be created on first write.
if not os.path.exists(datadir):
os.mkdir(datadir)
self.bot.log.debug('Created {0}/ directory'.format(datadir))
try:
self.config = self.bot.config[__name__]
if not self.config.get('enable_http_server'):
return
host, port = self.config['http_host'], int(self.config['http_port'])
except KeyError:
host, port = '127.0.0.1', 8080
bottle.hook('before_request')(self.__strip_path)
bottle.route('/')(self.__http_index)
bottle.route('/<user>')(self.__http_index)
bottle.route('/<user>/<key>')(self.__http_index)
bottle_thread = threading.Thread(
target=bottle.run,
kwargs={'quiet': True, 'host': host, 'port': port},
name='{0} HTTP server'.format(__name__),
daemon=True
)
bottle_thread.start()
self.bot.log.info('{0} started on http://{1}:{2}'.format(bottle_thread.name, host, port))
def run():
bottle.debug(not PROD)
bottle.run(
app=app,
host='localhost',
port='2081',
reloader=not PROD
)
def start():
#http://stackoverflow.com/questions/13760109/ec2-bottle-py-connection
app.run(host='0.0.0.0', port=18080)
logging.info('completed %.3f' % time.clock())
def db_upgrade():
"Create non-existent question tables; use if questions are updated"
tables = r.table_list().run(conn())
print(tables)
for page in config['PAGES']:
for question in page.questions:
name = "%s_answers" % question.name
if name not in tables:
print("CREATING TABLE %s" % name)
r.table_create(name, primary_key = 'user_identity').run(conn())
def followup(dry_run):
if dry_run:
print("DRY RUN -- Not sending actual emails")
config['DEBUG'] = True
"Run after changing the question schema; sends out email updates. Recommended at most once per month."
emails = []
usrs = []
for user in r.table('users').run(conn()):
if 'subscribed' not in user or user['subscribed'] == False:
# Ignore anonymous or unsubscribed users
continue
# Get email for email/xenforo accounts
usrs.append(user)
emails.append(user['email'] if 'email' in user else user['identity'])
print("Sending emails to the following %s users", (len(emails), emails))
desc = sys.stdin.read()
for user in usrs:
users.mail(user, 'Questions have been updated',
"""You are receiving this email because the questions have been updated. Please consider logging in and updating your response.<br>
<br>
Update notes:<br>
%s<br>
""" % desc.replace('\n', '<br>'),
"""You are receiving this email because the questions have been updated. Please conisder logging in and updating your response\n
\n
Update notes:%s\n""" % desc, use_flash = False)
def runserver(debug):
"Run HTTP server"
config['DEBUG'] = debug
if debug == True:
config['SITE_NAME'] = '%s debug' % (config['SITE_NAME'])
config['DEBUG'] = True
if 'ondebug' in config:
config['ondebug'](config)
run(app, host='0.0.0.0', port=8080, debug = debug, reloader = True)
def run(self):
try:
while True:
buf = self.converter.stdout.read(512)
if buf:
self.websocket_server.manager.broadcast(buf, binary=True)
elif self.converter.poll() is not None:
break
finally:
self.converter.stdout.close()
def http_server():
bottle.run(app=get(), host='0.0.0.0', port=8000, server="gevent", debug=True)