BotZ/api/dev_server.py

83 lines
2.2 KiB
Python
Raw Normal View History

2019-08-02 00:09:39 +02:00
# -*- encoding: utf-8 -*-
from aiohttp import web
import logging
import click
logging.basicConfig(
format="%(message)s", level=logging.INFO, handlers=[logging.StreamHandler()]
)
alog = logging.getLogger(__name__)
routes = web.RouteTableDef()
@routes.get("/{tail:.*}")
async def get_handler(request: web.Request) -> web.Response:
2019-08-06 00:07:40 +02:00
alog.info("GET -> [%s]: %s", request.path, request.query)
return web.json_response(
{"method": request.method, "path": request.path},
headers={"Access-Control-Allow-Origin": "*"},
)
2019-08-02 00:09:39 +02:00
@routes.post("/{tail:.*}")
async def post_handler(request: web.Request) -> web.Response:
data = await request.post()
alog.info("POST -> [%s]: %s", request.path, data)
2019-08-06 00:07:40 +02:00
return web.json_response(
{"method": request.method, "path": request.path},
headers={"Access-Control-Allow-Origin": "*"},
)
2019-08-02 00:09:39 +02:00
@routes.put("/{tail:.*}")
async def put_handler(request: web.Request) -> web.Response:
2019-08-06 00:07:40 +02:00
data = await request.post()
2019-08-02 00:09:39 +02:00
alog.info("PUT -> [%s]: %s", request.path, data)
2019-08-06 00:07:40 +02:00
return web.json_response(
{"method": request.method, "path": request.path},
headers={"Access-Control-Allow-Origin": "*"},
)
2019-08-02 00:09:39 +02:00
@routes.delete("/{tail:.*}")
async def delete_handler(request: web.Request) -> web.Response:
2019-08-06 00:07:40 +02:00
data = await request.post()
alog.info("DELETE -> [%s]: %s", request.path, data)
return web.json_response(
{"method": request.method, "path": request.path},
headers={"Access-Control-Allow-Origin": "*"},
)
2019-08-02 00:09:39 +02:00
async def options_handler(request: web.Request) -> web.Response:
alog.info("OPTIONS -> [%s]", request.path)
2019-08-06 00:07:40 +02:00
return web.Response(status=200)
2019-08-02 00:09:39 +02:00
def run(address: str, port: int) -> None:
"""Application entrypoint."""
app = web.Application(logger=alog)
app.add_routes(routes)
app.router.add_route("OPTIONS", "/{tail:.*}", options_handler)
web.run_app(app, host=address, port=port)
@click.command()
@click.option(
"-a",
"--address",
type=click.STRING,
help="Address to bind the server to.",
default="127.0.0.1",
)
@click.option("-p", "--port", type=click.INT, help="Port to bind to", default=3003)
def cli(address: str, port: int) -> None:
run(address, port)
if __name__ == "__main__":
cli()