Python aiohttp.web.post() Examples

The following are 30 code examples of aiohttp.web.post(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module aiohttp.web , or try the search function .
Example #1
Source File: server.py    From RPGBot with GNU General Public License v3.0 6 votes vote down vote up
def code(self, request: web.Request):
        if 'code' not in request.query:
            raise web.HTTPFound("/register?" + urlencode({"redirect": request.url}))

        code = request.query["code"]
        data = {
            "code": code,
            "grant_type": "authorization_code",
            "redirect_uri": "http://api.typheus.me/hub",
            "client_id": self.client_id,
            "client_secret": self.client_secret,
            "scope": 'identify guilds'
        }
        response = await self.session.post(
            f"https://discordapp.com/api/oauth2/token",
            data=urlencode(data),
            headers={'Content-Type': "application/x-www-form-urlencoded"}
        )
        js = await response.json()
        if 'error' in js:
            raise web.HTTPServerError(reason=f"Invalid code or redirect {js['error']}")
        token = js['access_token']
        logging.info("Received Discord OAuth2 code, grabbing token")
        raise web.HTTPFound(f"/hub?token={token}") 
Example #2
Source File: main.py    From aiohttp-swagger3 with Apache License 2.0 6 votes vote down vote up
def main():
    app = web.Application()
    s = SwaggerFile(
        app,
        spec_file="petstore.yaml",
        swagger_ui_settings=SwaggerUiSettings(path="/docs"),
    )
    s.add_routes(
        [
            web.get("/pets", get_all_pets),
            web.get("/pets/{pet_id}", get_one_pet),
            web.delete("/pets/{pet_id}", delete_one_pet),
            web.post("/pets", create_pet),
        ]
    )
    app["storage"] = {}
    web.run_app(app) 
Example #3
Source File: main.py    From aiohttp-swagger3 with Apache License 2.0 6 votes vote down vote up
def main():
    app = web.Application()
    s = SwaggerDocs(
        app,
        title="Swagger Petstore",
        version="1.0.0",
        components="components.yaml",
        swagger_ui_settings=SwaggerUiSettings(path="/docs"),
    )
    s.add_routes(
        [
            web.get("/pets", get_all_pets),
            web.get("/pets/{pet_id}", get_one_pet),
            web.delete("/pets/{pet_id}", delete_one_pet),
            web.post("/pets", create_pet),
        ]
    )
    app["storage"] = {}
    web.run_app(app) 
Example #4
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def register(app: web.Application):
    """Register routes."""

    app.add_routes(
        [
            web.get("/wallet/did", wallet_did_list, allow_head=False),
            web.post("/wallet/did/create", wallet_create_did),
            web.get("/wallet/did/public", wallet_get_public_did, allow_head=False),
            web.post("/wallet/did/public", wallet_set_public_did),
            web.post("/wallet/set-did-endpoint", wallet_set_did_endpoint),
            web.get(
                "/wallet/get-did-endpoint", wallet_get_did_endpoint, allow_head=False
            ),
            web.patch("/wallet/did/local/rotate-keypair", wallet_rotate_did_keypair),
        ]
    ) 
Example #5
Source File: webserver_with_module.py    From aries-staticagent-python with Apache License 2.0 6 votes vote down vote up
def main():
    """Create connection and start web server."""
    args = config()
    conn = StaticConnection(
        (args.my_verkey, args.my_sigkey),
        their_vk=args.their_verkey,
        endpoint=args.endpoint,
    )

    bmc = BasicMessageCounter()
    conn.route_module(bmc)

    async def handle(request):
        """ aiohttp handle POST. """
        await conn.handle(await request.read())
        raise web.HTTPAccepted()

    app = web.Application()
    app.add_routes([web.post('/', handle)])

    web.run_app(app, port=args.port) 
Example #6
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def register(app: web.Application):
    """Register routes."""
    app.add_routes(
        [
            web.post(
                "/credential-definitions",
                credential_definitions_send_credential_definition,
            ),
            web.get(
                "/credential-definitions/created",
                credential_definitions_created,
                allow_head=False,
            ),
            web.get(
                "/credential-definitions/{cred_def_id}",
                credential_definitions_get_credential_definition,
                allow_head=False,
            ),
        ]
    ) 
Example #7
Source File: test_http_transport.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def test_transport_coverage(self):
        transport = HttpTransport()
        assert transport.wire_format is None
        transport.wire_format = JsonWireFormat()
        assert transport.wire_format is not None

        await transport.start()

        with pytest.raises(OutboundTransportError):
            await transport.handle_message(None, None, None)

        with async_mock.patch.object(
            transport, "client_session", async_mock.MagicMock()
        ) as mock_session:
            mock_response = async_mock.MagicMock(status=404)
            mock_session.post = async_mock.MagicMock(
                return_value=async_mock.MagicMock(
                    __aenter__=async_mock.CoroutineMock(return_value=mock_response)
                )
            )
            with pytest.raises(OutboundTransportError):
                await transport.handle_message(None, "dummy", "http://localhost")

        await transport.__aexit__(KeyError, KeyError("just a drill"), None) 
Example #8
Source File: server.py    From graham_discord_bot with MIT License 6 votes vote down vote up
def __init__(self, bot: Bot, host: str, port: int):
        self.bot = bot
        self.app = web.Application(middlewares=[web.normalize_path_middleware()])
        self.app.add_routes([
            web.post('/callback', self.callback)
        ])
        cors = aiohttp_cors.setup(self.app, defaults={
            "*": aiohttp_cors.ResourceOptions(
                    allow_credentials=True,
                    expose_headers="*",
                    allow_headers="*",
                )
        })
        ufw_resource = cors.add(self.app.router.add_resource("/ufw/{wallet}"))
        cors.add(ufw_resource.add_route("GET", self.ufw)) 
        wfu_resource = cors.add(self.app.router.add_resource("/wfu/{user}"))
        cors.add(wfu_resource.add_route("GET", self.wfu))
        users_resource = cors.add(self.app.router.add_resource("/users"))
        cors.add(users_resource.add_route("GET", self.users))
        self.logger = logging.getLogger()
        self.host = host
        self.port = port
        self.min_amount = 10 if Env.banano() else 0.1 
Example #9
Source File: routes.py    From aries-vcr with Apache License 2.0 5 votes vote down vote up
def register(app: web.Application):
    """Register routes."""
    app.add_routes([web.post("/issuer_registration/send", issuer_registration_send)]) 
Example #10
Source File: graphql_aiohttp.py    From hiku with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    logging.basicConfig()
    app = web.Application()
    app.add_routes([
        web.post('/graphql', handle_graphql),
    ])
    app['graphql-endpoint'] = AsyncGraphQLEndpoint(
        Engine(AsyncIOExecutor()), QUERY_GRAPH, MUTATION_GRAPH,
    )
    web.run_app(app) 
Example #11
Source File: http_transport.py    From indy-agent with Apache License 2.0 5 votes vote down vote up
def send(self, dest: str, body: bytes):
        """ Send a message.
        """
        async with ClientSession() as session:
            async with session.post(dest, data=body, headers={'Content-Type':'application/ssi-agent-wire'}) as resp:
                self.logger.debug("Response Status: {}".format(resp.status))
                self.logger.debug("Response text: {}".format(await resp.text())) 
Example #12
Source File: mkctf_server.py    From mkctf with GNU General Public License v3.0 5 votes vote down vote up
def main():
    '''Main function
    '''
    parser = MKCTFArgumentParser(banner=BANNER, description="An HTTP API to perform operations on a mkCTF repository.")
    args = parser.parse_args()
    api = MKCTFAPI(args.repo_dir)
    handler = MKCTFWebHandler(api)
    app = web.Application()
    app.add_routes([
        web.get(r'/challenges', handler.enum_challenges),
        web.get(r'/{slug:[a-z0-9\-]+}/health', handler.challenge_status),
        web.post(r'/{slug:[a-z0-9\-]+}/check-flag', handler.check_challenge_flag),
    ])
    app_log.info(f"serving from {args.repo_dir}")
    web.run_app(app) 
Example #13
Source File: main.py    From aiohttp-swagger3 with Apache License 2.0 5 votes vote down vote up
def main():
    app = web.Application()
    s = SwaggerDocs(
        app,
        title="Swagger Petstore",
        version="1.0.0",
        swagger_ui_settings=SwaggerUiSettings(path="/docs"),
    )
    # register your handler before registering routes
    s.register_media_type_handler("my_cool/type", my_cool_handler)
    s.add_routes([web.post("/pets", create_pet)])
    web.run_app(app) 
Example #14
Source File: test_named_resources.py    From aiohttp-swagger3 with Apache License 2.0 5 votes vote down vote up
def test_named_resources(swagger_docs):
    async def handler(request):
        return web.json_response()

    swagger = swagger_docs()
    swagger.add_routes(
        [web.get("/", handler, name="get"), web.post("/", handler, name="post")]
    )

    assert "get" in swagger._app.router
    assert "post" in swagger._app.router 
Example #15
Source File: test_comment_commands.py    From lbry-sdk with MIT License 5 votes vote down vote up
def __init__(self, port=2903):
        self.port = port
        self.app = web.Application(debug=True)
        self.app.add_routes([web.post('/api', self.api)])
        self.runner = None
        self.server = None
        self.comments = []
        self.comment_id = 0 
Example #16
Source File: aiohttp_demo.py    From torpeewee with MIT License 5 votes vote down vote up
def create_handle(request):
    data = await request.post()
    data = data["data"]
    await Test.create(data=data, created_at=datetime.datetime.now())
    return web.HTTPFound('/') 
Example #17
Source File: http_transport.py    From indy-agent with Apache License 2.0 5 votes vote down vote up
def start_server(self):
        """ The main task for the server aspect of transport.
        """
        APP = web.Application()
        ROUTES = [
            web.post('/indy', self.handle_message)
        ]
        APP.add_routes(ROUTES)
        RUNNER = web.AppRunner(APP)
        await RUNNER.setup()
        SERVER = web.TCPSite(RUNNER, self.config.host, self.config.port)
        self.logger.info('Starting Server on: http://{}:{}'.format(self.config.host, self.config.port))
        await SERVER.start() 
Example #18
Source File: async_views.py    From jupyter-plotly-dash with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, port):
        self.port = port
        self.apps = {}

        self.app = web.Application()
        self.app.add_routes([web.get('/{id}/', self.main),
                    web.get('/{id}/_dash-dependencies', self.dependencies),
                    web.get('/{id}/_dash-layout', self.layout),
                    web.post('/{id}/_dash-update-component', self.update),
                    web.get('/{id}/_dash-routes', self.routes),
                    web.get('/{id}/_dash-component-suites', self.component_suites),
                   ])

        self.launch_task = asyncio.Task(self.launch_it(self.app, self.port)) 
Example #19
Source File: webhook.py    From TwitchIO with MIT License 5 votes vote down vote up
def __init__(self, *, bot, local: str, external: str, port: int, callback: str=None):
        self._bot = bot
        self.local = local
        self.external = external
        self.port = port
        self.callback = callback or uuid.uuid4().hex
        self.app = web.Application()
        self.app.add_routes([web.get(f'/{self.callback}', self.handle_callback),
                             web.post(f'/{self.callback}', self.handle_callback_post)])

        self.loop = None 
Example #20
Source File: preprocessors.py    From aries-staticagent-python with Apache License 2.0 5 votes vote down vote up
def main():
    """Create StaticConnection and start web server."""
    args = config()
    conn = StaticConnection(
        (args.my_verkey, args.my_sigkey),
        their_vk=args.their_verkey,
        endpoint=args.endpoint,
    )

    @conn.route(TYPE)
    @utils.validate(validate_basic_message)
    async def basic_message(msg, conn):
        """Respond to a basic message."""
        await conn.send_async({
            "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/"
                     "basicmessage/1.0/message",
            "~l10n": {"locale": "en"},
            "sent_time": utils.timestamp(),
            "content": (
                "The preprocessor validated this message and added: "
                "{}".format(msg['added_something'])
            )
        })

    async def handle(request):
        """aiohttp handle POST."""
        response = []
        with conn.session(response.append) as session:
            await conn.handle(await request.read(), session)

        if response:
            return web.Response(text=response.pop())

        raise web.HTTPAccepted()

    app = web.Application()
    app.add_routes([web.post('/', handle)])

    web.run_app(app, port=args.port) 
Example #21
Source File: return_route_server.py    From aries-staticagent-python with Apache License 2.0 5 votes vote down vote up
def main():
    """Start a server with a static connection."""
    keys = crypto.create_keypair(
        seed=hashlib.sha256(b'server').digest()
    )
    their_vk, _ = crypto.create_keypair(
        seed=hashlib.sha256(b'client').digest()
    )
    conn = StaticConnection(keys, their_vk=their_vk, endpoint=None)

    @conn.route('did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/basicmessage/1.0/message')
    async def basic_message_auto_responder(msg, conn):
        await conn.send_async({
            "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/"
                     "basicmessage/1.0/message",
            "~l10n": {"locale": "en"},
            "sent_time": utils.timestamp(),
            "content": "You said: {}".format(msg['content'])
        })

    async def handle(request):
        """aiohttp handle POST."""
        response = []
        with conn.session(response.append) as session:
            await conn.handle(await request.read(), session)

        if response:
            return web.Response(body=response.pop())

        raise web.HTTPAccepted()

    app = web.Application()
    app.add_routes([web.post('/', handle)])

    web.run_app(app, port=os.environ.get('PORT', 3000)) 
Example #22
Source File: webserver_aiohttp.py    From aries-staticagent-python with Apache License 2.0 5 votes vote down vote up
def main():
    """Create StaticConnection and start web server."""
    args = config()
    conn = StaticConnection(
        (args.my_verkey, args.my_sigkey),
        their_vk=args.their_verkey,
        endpoint=args.endpoint,
    )

    @conn.route("did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/basicmessage/1.0/message")
    async def basic_message(msg, conn):
        """Respond to a basic message."""
        await conn.send_async({
            "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/"
                     "basicmessage/1.0/message",
            "~l10n": {"locale": "en"},
            "sent_time": utils.timestamp(),
            "content": "You said: {}".format(msg['content'])
        })

    async def handle(request):
        """aiohttp handle POST."""
        response = []
        with conn.session(response.append) as session:
            await conn.handle(await request.read(), session)

        if response:
            return web.Response(text=response.pop())

        raise web.HTTPAccepted()

    app = web.Application()
    app.add_routes([web.post('/', handle)])

    web.run_app(app, port=args.port) 
Example #23
Source File: smart-contract-rest-api.py    From neo-python with MIT License 5 votes vote down vote up
def echo_post(request):
    # Parse POST JSON body

    body = await request.json()

    # Echo it
    res = {
        "post-body": body
    }
    return web.json_response(data=res)


#
# Main setup method
# 
Example #24
Source File: smart-contract-rest-api.py    From neo-python with MIT License 5 votes vote down vote up
def setup_and_start(loop):
    # Use TestNet
    settings.setup_privnet()

    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)

    p2p = NetworkService()
    loop.create_task(p2p.start())
    bg_task = loop.create_task(custom_background_code())

    # Disable smart contract events for external smart contracts
    settings.set_log_smart_contract_events(False)

    app = web.Application()
    app.add_routes([
        web.route('*', '/', home_route),
        web.get("/echo-get/{msg}", echo_msg),
        web.post("/echo-post/", echo_post),
    ])

    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, "0.0.0.0", API_PORT)
    await site.start()

    # Run all the things (blocking call)
    logger.info("Everything setup and running. Waiting for events...")
    return site 
Example #25
Source File: test_client_fake_server.py    From us-pycon-2019-tutorial with Apache License 2.0 5 votes vote down vote up
def test_get_post(aiohttp_server: Any) -> None:
    async def handler(request: web.Request) -> web.Response:
        data = await request.json()
        assert data["title"] == "test title"
        assert data["text"] == "test text"
        return web.json_response(
            {
                "status": "ok",
                "data": {
                    "id": 1,
                    "title": "test title",
                    "text": "test text",
                    "owner": "test_user",
                    "editor": "test_user",
                },
            }
        )

    app = web.Application()
    app.add_routes([web.post("/api", handler)])
    server = await aiohttp_server(app)
    async with Client(server.make_url("/"), "test_user") as client:
        post = await client.create("test title", "test text")

        assert post.id == 1
        assert post.title == "test title"
        assert post.text == "test text"
        assert post.owner == "test_user"
        assert post.editor == "test_user" 
Example #26
Source File: fake_hmip_server.py    From homematicip-rest-api with GNU General Public License v3.0 5 votes vote down vote up
def add_routes(self):
        self.app.router.add_routes([web.post("/getHost", self.get_host)]) 
Example #27
Source File: fake_hmip_server.py    From homematicip-rest-api with GNU General Public License v3.0 5 votes vote down vote up
def add_routes(self):
        self.app.router.add_routes(
            [
                web.post("/go_404", self.go_404),
                web.post("/go_200_no_json", self.go_200_no_json),
                web.post("/go_200_json", self.go_200_json),
            ]
        ) 
Example #28
Source File: attestation_endpoint.py    From py-ipv8 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def setup_routes(self):
        self.app.add_routes([web.get('', self.handle_get),
                             web.post('', self.handle_post)]) 
Example #29
Source File: server.py    From RPGBot with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, bot, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.pool = None

        with open("pyhtml/auth", 'r') as af:
            self.client_id, self.client_secret = json.loads(af.read())

        self.bot = bot
        self.session = aiohttp.ClientSession(loop=bot.loop)
        self.logger = logging.getLogger('currency-converter')
        self.logger.setLevel(logging.INFO)
        self.handler = logging.FileHandler(filename="transactions.log",
                                           encoding='utf-8',
                                           mode='a')
        self.handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
        self.logger.addHandler(self.handler)

        with open("pyhtml/register.html") as _rf:
            self.register_html = _rf.read()

        with open("pyhtml/hub.html") as _rf:
            self.hub_html = _rf.read()

        with open("pyhtml/guild.html") as _rf:
            self.guild_html = _rf.read()

        self.add_routes([
            web.get('/code', self.code),
            web.get('/hub', self.hub),
            web.get('/guilds', self.guilds),
            web.get('/authorize', self.mydata),
            web.get('/', self.index),
            web.get('/register', self.register),
            web.get('/add/', self.add),
            web.get('/bots/{snowflake:\d+}/', self.convert),
            web.post('/bots/{snowflake:\d+}/', self.convert),
            web.get('/user/{guild:\d+}/{user:\d+}{tail:.*}', self.getuser),
            web.get('/guild/{guild:\d+}{tail:.*}', self.getguild),
        ]) 
Example #30
Source File: test_admin_server.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def get_application(self):
        """
        Override the get_app method to return your application.
        """
        app = web.Application()
        app.add_routes([web.post("/topic/{topic}/", self.receive_hook)])
        return app