コード例 #1
0
@app.route("/elo/<outcome>/<team_a>/<team_b>/<int:k>")
def elo(outcome, team_a, team_b, k=16):
    outcome = {"win": "a", "loss": "b", "draw": "draw"}[outcome]
    listy = "," in team_a
    team_a = [int(score) for score in team_a.split(",")]
    team_b = [int(score) for score in team_b.split(",")]
    assert len(team_a) == len(
        team_b), "Teams have to have the same amount of players"
    mod_a, mod_b = _elo(team_a, team_b, outcome, k)
    if listy:
        return jsonify([[round(x + mod_a) for x in team_a],
                        [round(x + mod_b) for x in team_b]])
    return jsonify([round(team_a[0] + mod_a), round(team_b[0] + mod_b)])


app.route("/slack", methods=["POST"])(slack)

app.register_blueprint(chord_views, url_prefix="/chords")
app.register_blueprint(krank_views, url_prefix="/krank")
app.register_blueprint(grafana_views, url_prefix="/grafana")


@app.after_request
def add_cors(response):
    response.headers["Access-Control-Allow-Origin"] = "*"
    response.headers[
        "Access-Control-Allow-Headers"] = "Content-Type,Authorization"
    response.headers["Access-Control-Allow-Methods"] = "GET,POST"
    return response

コード例 #2
0
ファイル: server.py プロジェクト: smurfix/deframed
class App:
    """
    This is deframed's main code.

    You probably don't need to subclass this.
    """
    def __init__(self, cfg: dict, worker: Worker, debug:bool=False):
        cfg = combine_dict(cfg, CFG, cls=attrdict)
        self.cfg = cfg
        self.main = None # Nursery
        self.clients = WeakValueDictionary()
        self.worker = worker
        self.sub_worker = WeakValueDictionary()
        self._sw_id = 0
        self.version = worker.version or deframed.__version__
        self.debug=debug or cfg.debug

        self.app = Quart(cfg.server.name,
                # no, we do not want any of those default folders and whatnot
                static_folder=None,template_folder=None,root_path="/nonexistent",
                )

        #@self.app.route("/<path:p>", methods=['GET'])
        @self.app.route("/", defaults={"p":None}, methods=['GET'])
        async def index(p):
            # "path" is unused, the app will get it via Javascript
            mainpage = os.path.join(os.path.dirname(deframed.__file__), cfg.mainpage)
            with open(mainpage, 'r') as f:
                data = cfg.data.copy()

                data['debug'] = self.debug
                data['version'] = self.version
                if data['title'] == CFG.data.title:
                    data['title'] = self.worker.title

                return Response(chevron.render(f, data),
                        headers={"Access-Control-Allow-Origin": "*"})

        @self.app.websocket('/ws')
        async def ws():
            """Main websocket"""
            w = self.worker(self)
            await w.run(websocket._get_current_object())

        @self.app.route("/sub/<int:sid>", methods=['GET'])
        async def index_sub(sid):
            """SubWorker main page"""
            w = self.sub_worker[sid]
            return await w.index()

        @self.app.websocket('/ws/<int:sid>')
        async def ws_sub(sid):
            """SubWorker websocket"""
            try:
                w = self.sub_worker[sid]
            except KeyError:
                raise NotFound

            else:
                await w.run(websocket._get_current_object())

        static = os.path.join(os.path.dirname(deframed.__file__), cfg.data.static)
        @self.app.route("/static/<path:filename>", methods=['GET'])
        async def send_static(filename):
            print("GET",filename)
            return await send_from_directory(static, filename)

    def route(self,*a,**k):
        return self.app.route(*a,**k)


    async def run (self) -> None:
        """
        Run this application.

        This is a simple Hypercorn runner.
        You should probably use something more elaborate in a production setting.
        """
        config = HyperConfig()
        cfg = self.cfg.server
        config.access_log_format = "%(h)s %(r)s %(s)s %(b)s %(D)s"
        config.access_logger = create_serving_logger()  # type: ignore
        config.bind = [f"{cfg.host}:{cfg.port}"]
        config.ca_certs = cfg.ca_certs
        config.certfile = cfg.certfile
#   if debug is not None:
#       config.debug = debug
        config.error_logger = config.access_logger  # type: ignore
        config.keyfile = cfg.keyfile
        config.use_reloader = cfg.use_reloader

        scheme = "http" if config.ssl_enabled is None else "https"
        async with trio.open_nursery() as n:
            self.main = n
            await hyper_serve(self.app, config)

    def attach_sub(self, subworker):
        """
        Attach a sub-worker, typically displayed in an iframe.
        
        There is no "detach", as the worker is weakly referenced.

        There is no "get", as the ID only shows up in the path.
        """
        self._sw_id += 1
        sw_id = self._sw_id

        self.sub_worker[sw_id] = subworker
        return sw_id
コード例 #3
0
ファイル: render.py プロジェクト: pepe5/papyri
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)