Skip to content

Commit

Permalink
Merge branch '2.3'
Browse files Browse the repository at this point in the history
  • Loading branch information
asvetlov committed Nov 17, 2017
2 parents 51c4609 + 03b13c6 commit 9414e92
Show file tree
Hide file tree
Showing 10 changed files with 181 additions and 9 deletions.
8 changes: 8 additions & 0 deletions 1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import asyncio
import aiohttp

async def fetch():
async with aiohttp.ClientSession() as session:
await session.get('https://雜草工作室.香港')

asyncio.get_event_loop().run_until_complete(fetch())
11 changes: 11 additions & 0 deletions 2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from aiohttp import web

async def handle(request):
return web.Response(text='<h1>testing</h1>', content_type='text/html')

app = web.Application()
app.router.add_get('/', handle)


if __name__ == '__main__':
web.run_app(app, port=8001)
46 changes: 46 additions & 0 deletions 3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import asyncio
import aiohttp
import uvloop
import time
import logging

from aiohttp import ClientSession, TCPConnector

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()

urls = ["http://www.yahoo.com","http://www.bbcnews.com","http://www.cnn.com","http://www.buzzfeed.com","http://www.walmart.com","http://www.emirates.com","http://www.kayak.com","http://www.expedia.com","http://www.apple.com","http://www.youtube.com"]
bigurls = 10 * urls

def run(enable_uvloop):
try:
if enable_uvloop:
loop = uvloop.new_event_loop()
else:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
start = time.time()
conn = TCPConnector(limit=5000, use_dns_cache=True, loop=loop, verify_ssl=False)
with ClientSession(connector=conn) as session:
tasks = asyncio.gather(*[asyncio.ensure_future(do_request(url, session)) for url in bigurls]) # tasks to do
results = loop.run_until_complete(tasks) # loop until done
end = time.time()
logger.debug('total time:')
logger.debug(end - start)
return results
loop.close()
except Exception as e:
logger.error(e, exc_info=True)

async def do_request(url, session):
"""
"""
try:
async with session.get(url) as response:
resp = await response.text()
return resp
except Exception as e:
logger.error(e, exc_info=True)

#run(True)
run(False)
34 changes: 34 additions & 0 deletions 4.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/usr/bin/env python
# run it as:
# python -m unittest test_example.TestClientCase

from aiohttp import web
from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
from aiohttp.test_utils import TestClient, TestServer


class TestClientCase(AioHTTPTestCase):
def _app_index(self, request):
return web.Response(body="<html><body>Here we are</body></html",
content_type='text/html')

async def get_application(self):
app = web.Application()
app.router.add_get('/', self._app_index)

return app

@unittest_run_loop
async def test_using_class_attribute(self):
request = await self.client.request("GET", "/")
print(request.status)
assert request.status == 200

@unittest_run_loop
async def test_using_client(self):
tc = TestClient(
TestServer(self.app, loop=self.loop),
loop=self.loop)
request = await tc.request("GET", "/")
print(request.status)
assert request.status == 200
16 changes: 7 additions & 9 deletions docs/web_advanced.rst
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,6 @@ and safe to use as the key.
Otherwise, something based on your company name/url would be satisfactory (i.e.
``org.company.app``).


.. _aiohttp-web-middlewares:

Middlewares
Expand All @@ -301,14 +300,7 @@ Middlewares
:mod:`aiohttp.web` provides a powerful mechanism for customizing
:ref:`request handlers<aiohttp-web-handler>` via *middlewares*.

*Middlewares* are setup by providing a sequence of *middleware factories* to
the keyword-only ``middlewares`` parameter when creating an
:class:`Application`::

app = web.Application(middlewares=[middleware_factory_1,
middleware_factory_2])

A *middleware* is just a coroutine that can modify either the request or
A *middleware* is a coroutine that can modify either the request or
response. For example, here's a simple *middleware* which appends
``' wink'`` to the response::

Expand All @@ -325,6 +317,12 @@ response. For example, here's a simple *middleware* which appends
Every *middleware* should accept two parameters, a
:class:`request <Request>` instance and a *handler*, and return the response.

When creating an :class:`Application`, these *middlewares* are passed to
the keyword-only ``middlewares`` parameter::

app = web.Application(middlewares=[middleware_1,
middleware_2])

Internally, a single :ref:`request handler <aiohttp-web-handler>` is constructed
by applying the middleware chain to the original handler in reverse order,
and is called by the :class:`RequestHandler` as a regular *handler*.
Expand Down
8 changes: 8 additions & 0 deletions notes.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Google analytics
Add Python to main page
v:stable doesn't work
Mention "Latest stable" in Library Installation, version number and release date

Add asyncio to Title
Add PyPI badge
hotjar
26 changes: 26 additions & 0 deletions run_aiohttp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import asyncio

import ujson
from aiohttp import web


async def index(request):
data = {'message': 'hello world'}
body = ujson.dumps(data)
return web.Response(body=body.encode(), content_type='application/json')


# import tokio
# asyncio.set_event_loop_policy(tokio.TokioLoopPolicy())

import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

app = web.Application()
# app.on_startup.append(startup)
# app.on_cleanup.append(cleanup)
app.router.add_get('/', index)
# app.router.add_get('/db', db)

# web.run_app(app, port=8000)
web.run_app(app, port=8000, access_log=None)
11 changes: 11 additions & 0 deletions run_aiohttp2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import asyncio
from aiohttp import web

async def hello(request):
return web.Response(body=b"Hello, world")

app = web.Application()
app.router.add_route('GET', '/', hello)

if __name__ == '__main__':
web.run_app(app)
15 changes: 15 additions & 0 deletions run_aiohttp3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import asyncio
from aiohttp import web

import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())


async def hello(request):
return web.Response(body=b"Hello, world")

app = web.Application()
app.router.add_route('GET', '/', hello)

if __name__ == '__main__':
web.run_app(app)
15 changes: 15 additions & 0 deletions run_aiohttp4.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import asyncio
from aiohttp import web

import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())


async def hello(request):
return web.Response(body=b"Hello, world")

app = web.Application()
app.router.add_route('GET', '/', hello)

if __name__ == '__main__':
web.run_app(app, access_log=None)

0 comments on commit 9414e92

Please sign in to comment.