def serve(): app = QuartTrio(__name__) store = Store(str(ingest_dir)) gstore = GraphStore(ingest_dir) async def full(package, version, sub, ref): return await _route(ref, store, version, gstore=gstore) async def full_gallery(module, version): return await gallery(module, store, version, gstore=gstore) async def g(module): return await gallery(module, store, gstore=gstore) async def gr(): return await gallery("*", store, gstore=gstore) async def index(): import papyri v = str(papyri.__version__) return redirect(f"/p/papyri/{v}/api/papyri") async def ex(module, version, subpath): return await examples(module=module, store=store, version=version, subpath=subpath) # return await _route(ref, GHStore(Path('.'))) app.route("/logo.png")(logo) app.route("/favicon.ico")(static("favicon.ico")) # sub here is likely incorrect app.route("/p/<package>/<version>/img/<path:subpath>")(img) app.route("/p/<module>/<version>/examples/<path:subpath>")(ex) app.route("/p/<module>/<version>/gallery")(full_gallery) app.route("/p/<package>/<version>/<sub>/<ref>")(full) app.route("/gallery/")(gr) app.route("/gallery/<module>")(g) app.route("/")(index) port = os.environ.get("PORT", 5000) print("Seen config port ", port) prod = os.environ.get("PROD", None) if prod: app.run(port=port, host="0.0.0.0") else: app.run(port=port)
def main(): if os.getuid() != 0: raise RuntimeError("need to be root, sorry about that") known_env_vars = ( "MESHPING_REDIS_HOST", "MESHPING_PING_TIMEOUT", "MESHPING_PING_INTERVAL", "MESHPING_PEERS", "MESHPING_PROMETHEUS_URL", "MESHPING_PROMETHEUS_QUERY", ) for key in os.environ.keys(): if key.startswith("MESHPING_") and key not in known_env_vars: print("env var %s is unknown" % key, file=sys.stderr) sys.exit(1) app = QuartTrio(__name__, static_url_path="") app.config["TEMPLATES_AUTO_RELOAD"] = True app.secret_key = str(uuid4()) app.debug = False redis = StrictRedis( host=os.environ.get("MESHPING_REDIS_HOST", "127.0.0.1")) mp = MeshPing(redis, int(os.environ.get("MESHPING_PING_TIMEOUT", 5)), int(os.environ.get("MESHPING_PING_INTERVAL", 30))) add_api_views(app, mp) @app.before_serving async def startup(): app.nursery.start_soon(mp.run) app.nursery.start_soon(run_peers, mp) app.run(host="::", port=9922)
@app.websocket("/ws") async def chat(): try: connections.add(websocket._get_current_object()) async with trio.open_nursery() as nursery: nursery.start_soon(heartbeat) while True: message = await websocket.receive() await broadcast(message) finally: connections.remove(websocket._get_current_object()) async def broadcast(message): for connection in connections: await connection.send(json.dumps({ "type": "message", "value": message })) async def heartbeat(): while True: await trio.sleep(1) await websocket.send(json.dumps({"type": "heartbeat"})) if __name__ == "__main__": app.run()
import asks from asks import Session from quart import request, Response from quart_trio import QuartTrio ENABLE_DEBUG = bool(os.environ.get('ROCKETCHAT_WEBHOOK_PROXY_DEBUG', False)) TARGET_URL = os.environ.get("ROCKETCHAT_WEBHOOK_PROXY_TARGET") if not TARGET_URL: raise RuntimeError( "Required env variable ROCKETCHAT_WEBHOOK_PROXY_TARGET is missing.") asks.init("trio") session = Session(connections=8) app = QuartTrio(__name__) @app.route("/<token_a>/<token_b>", methods=["POST"]) async def webhook(token_a, token_b): request_data = await request.get_json(force=True) if ENABLE_DEBUG: print(f"Request data:\n{json.dumps(request_data, indent=2)}") target_url = f"{TARGET_URL}/{token_a}/{token_b}" response = await session.post(target_url, json=request_data) return Response(response.text, content_type=response.headers["content-type"]) if __name__ == "__main__": app.run("localhost", port=5000, debug=True)
from quart import request from quart_trio import QuartTrio app = QuartTrio(__name__) @app.route('/<int:number>') async def index(number=1): return "{}-fib({})={}".format(__file__, number, _fib(int(number))) @app.route('/', methods=['POST']) async def post(): data = await request.form number = data['fib'] return "{}-fib({})={}".format(__file__, number, _fib(int(number))) def _fib(n): if n == 0: return 0 elif n == 1: return 1 else: return _fib(n - 1) + _fib(n - 2) if __name__ == '__main__': app.run(host='127.0.0.1', port=5000)
def main(): if os.getuid() != 0: raise RuntimeError("need to be root, sorry about that") known_env_vars = ( "MESHPING_DATABASE_PATH", "MESHPING_REDIS_HOST", "MESHPING_PING_TIMEOUT", "MESHPING_PING_INTERVAL", "MESHPING_HISTOGRAM_DAYS", "MESHPING_PEERS", "MESHPING_PEERING_INTERVAL", "MESHPING_PROMETHEUS_URL", "MESHPING_PROMETHEUS_QUERY", ) deprecated_env_vars = ( "MESHPING_PROMETHEUS_URL", "MESHPING_PROMETHEUS_QUERY", ) for key in os.environ: if key.startswith("MESHPING_") and key not in known_env_vars: print("env var %s is unknown" % key, file=sys.stderr) sys.exit(1) if key.startswith("MESHPING_") and key in deprecated_env_vars: print("env var %s is deprecated, ignored" % key, file=sys.stderr) app = QuartTrio(__name__, static_url_path="") #app.config["TEMPLATES_AUTO_RELOAD"] = True app.secret_key = str(uuid4()) app.jinja_options = dict(variable_start_string='{[', variable_end_string=']}') @app.context_processor def _inject_icons(): # I'm not happy about hardcoding this path here, but I'm also not sure what else to do icons_dir = "/opt/meshping/ui/node_modules/bootstrap-icons/icons/" return dict( icons={ filename: Markup( open(os.path.join(icons_dir, filename), "r").read()) for filename in os.listdir(icons_dir) }) # Transition period: Read all targets from redis and add them to our DB try: redis = StrictRedis( host=os.environ.get("MESHPING_REDIS_HOST", "127.0.0.1")) for target in redis.smembers("meshping:targets"): target = target.decode("utf-8") name, addr = target.split("@", 1) Target.db.add(addr, name) for target in redis.smembers("meshping:foreign_targets"): target = target.decode("utf-8") name, addr = target.split("@", 1) Target.db.get(addr).set_is_foreign(True) except: # Probably no redis here, ignore pass mp = MeshPing(int(os.environ.get("MESHPING_PING_TIMEOUT", 5)), int(os.environ.get("MESHPING_PING_INTERVAL", 30)), int(os.environ.get("MESHPING_HISTOGRAM_DAYS", 3))) add_api_views(app, mp) @app.before_serving async def _(): app.nursery.start_soon(mp.run) app.nursery.start_soon(run_peers, mp) app.run(host="::", port=9922, debug=False, use_reloader=False)
from quart import request from quart_trio import QuartTrio app = QuartTrio(__name__) @app.route("/<int:number>") async def index(number=1): return "{}-fib({})={}".format(__file__, number, _fib(int(number))) @app.route("/", methods=["POST"]) async def post(): data = await request.form number = data["fib"] return "{}-fib({})={}".format(__file__, number, _fib(int(number))) def _fib(n): if n == 0: return 0 elif n == 1: return 1 else: return _fib(n - 1) + _fib(n - 2) if __name__ == "__main__": app.run(host="127.0.0.1", port=5000)
app.connected.remove(websocket._get_current_object()) return wrapper async def broadcast(message: str): active = len(app.connected) for websock in app.connected: await websock.send(f"Broadcast: {message.upper()} : to {active}") @app.route('/') async def index(): return await render_template('index.html') @app.websocket('/ws') @collect_websocket async def ws(): await broadcast("new connection") try: while True: data: str = await websocket.receive() await websocket.send(f"got {data}") await trio.sleep(1) await broadcast(f"{data.upper()}") finally: print("client closed connection") if __name__ == '__main__': app.run(port=5000)