Skip to content

Commit

Permalink
Merge pull request #335 from r0fls/remove-loop
Browse files Browse the repository at this point in the history
remove loop as argument and update examples
  • Loading branch information
seemethere authored Jan 28, 2017
2 parents c81c929 + c72bcc1 commit fad9fbc
Show file tree
Hide file tree
Showing 10 changed files with 143 additions and 122 deletions.
9 changes: 2 additions & 7 deletions examples/aiohttp_example.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
from sanic import Sanic
from sanic.response import json

import uvloop
import aiohttp

#Create an event loop manually so that we can use it for both sanic & aiohttp
loop = uvloop.new_event_loop()

app = Sanic(__name__)

async def fetch(session, url):
Expand All @@ -24,10 +20,9 @@ async def test(request):
"""
url = "https://api.github.com/repos/channelcat/sanic"

async with aiohttp.ClientSession(loop=loop) as session:
async with aiohttp.ClientSession() as session:
response = await fetch(session, url)
return json(response)


app.run(host="0.0.0.0", port=8000, loop=loop)

app.run(host="0.0.0.0", port=8000, workers=2)
36 changes: 36 additions & 0 deletions examples/limit_concurrency.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from sanic import Sanic
from sanic.response import json

import asyncio
import aiohttp

app = Sanic(__name__)

sem = None

def init(sanic, loop):
global sem
CONCURRENCY_PER_WORKER = 4
sem = asyncio.Semaphore(CONCURRENCY_PER_WORKER, loop=loop)

async def bounded_fetch(session, url):
"""
Use session object to perform 'get' request on url
"""
async with sem, session.get(url) as response:
return await response.json()


@app.route("/")
async def test(request):
"""
Download and serve example JSON
"""
url = "https://api.github.com/repos/channelcat/sanic"

async with aiohttp.ClientSession() as session:
response = await bounded_fetch(session, url)
return json(response)


app.run(host="0.0.0.0", port=8000, workers=2, before_start=init)
60 changes: 30 additions & 30 deletions examples/sanic_aiopg_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@
from sanic import Sanic
from sanic.response import json

asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

database_name = os.environ['DATABASE_NAME']
database_host = os.environ['DATABASE_HOST']
database_user = os.environ['DATABASE_USER']
Expand All @@ -21,45 +19,47 @@
database_password,
database_host,
database_name)
loop = asyncio.get_event_loop()


async def get_pool():
return await aiopg.create_pool(connection)

app = Sanic(name=__name__)
pool = loop.run_until_complete(get_pool())


async def prepare_db():
""" Let's create some table and add some data

async def prepare_db(app, loop):
"""
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute('DROP TABLE IF EXISTS sanic_polls')
await cur.execute("""CREATE TABLE sanic_polls (
id serial primary key,
question varchar(50),
pub_date timestamp
);""")
for i in range(0, 100):
await cur.execute("""INSERT INTO sanic_polls
(id, question, pub_date) VALUES ({}, {}, now())
""".format(i, i))
Let's create some table and add some data
"""
async with aiopg.create_pool(connection) as pool:
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute('DROP TABLE IF EXISTS sanic_polls')
await cur.execute("""CREATE TABLE sanic_polls (
id serial primary key,
question varchar(50),
pub_date timestamp
);""")
for i in range(0, 100):
await cur.execute("""INSERT INTO sanic_polls
(id, question, pub_date) VALUES ({}, {}, now())
""".format(i, i))


@app.route("/")
async def handle(request):
async with pool.acquire() as conn:
async with conn.cursor() as cur:
result = []
await cur.execute("SELECT question, pub_date FROM sanic_polls")
async for row in cur:
result.append({"question": row[0], "pub_date": row[1]})
return json({"polls": result})

result = []
async def test_select():
async with aiopg.create_pool(connection) as pool:
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT question, pub_date FROM sanic_polls")
async for row in cur:
result.append({"question": row[0], "pub_date": row[1]})
res = await test_select()
return json({'polls': result})

if __name__ == '__main__':
loop.run_until_complete(prepare_db())
app.run(host='0.0.0.0', port=8000, loop=loop)
app.run(host='0.0.0.0',
port=8000,
debug=True,
before_start=prepare_db)
49 changes: 21 additions & 28 deletions examples/sanic_aiopg_sqlalchemy_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
from sanic import Sanic
from sanic.response import json

asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

database_name = os.environ['DATABASE_NAME']
database_host = os.environ['DATABASE_HOST']
database_user = os.environ['DATABASE_USER']
Expand All @@ -23,8 +21,6 @@
database_password,
database_host,
database_name)
loop = asyncio.get_event_loop()


metadata = sa.MetaData()

Expand All @@ -34,40 +30,37 @@
sa.Column("pub_date", sa.DateTime))


async def get_engine():
return await create_engine(connection)

app = Sanic(name=__name__)
engine = loop.run_until_complete(get_engine())


async def prepare_db():
async def prepare_db(app, loop):
""" Let's add some data
"""
async with engine.acquire() as conn:
await conn.execute('DROP TABLE IF EXISTS sanic_polls')
await conn.execute("""CREATE TABLE sanic_polls (
id serial primary key,
question varchar(50),
pub_date timestamp
);""")
for i in range(0, 100):
await conn.execute(
polls.insert().values(question=i,
pub_date=datetime.datetime.now())
)
async with create_engine(connection) as engine:
async with engine.acquire() as conn:
await conn.execute('DROP TABLE IF EXISTS sanic_polls')
await conn.execute("""CREATE TABLE sanic_polls (
id serial primary key,
question varchar(50),
pub_date timestamp
);""")
for i in range(0, 100):
await conn.execute(
polls.insert().values(question=i,
pub_date=datetime.datetime.now())
)


@app.route("/")
async def handle(request):
async with engine.acquire() as conn:
result = []
async for row in conn.execute(polls.select()):
result.append({"question": row.question, "pub_date": row.pub_date})
return json({"polls": result})
async with create_engine(connection) as engine:
async with engine.acquire() as conn:
result = []
async for row in conn.execute(polls.select()):
result.append({"question": row.question, "pub_date": row.pub_date})
return json({"polls": result})


if __name__ == '__main__':
loop.run_until_complete(prepare_db())
app.run(host='0.0.0.0', port=8000, loop=loop)
app.run(host='0.0.0.0', port=8000, before_start=prepare_db)
53 changes: 23 additions & 30 deletions examples/sanic_asyncpg_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@
from sanic import Sanic
from sanic.response import json

asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

DB_CONFIG = {
'host': '<host>',
'user': '<username>',
Expand All @@ -21,45 +19,40 @@
}

def jsonify(records):
""" Parse asyncpg record response into JSON format
"""
Parse asyncpg record response into JSON format
"""
return [{key: value for key, value in
zip(r.keys(), r.values())} for r in records]

loop = asyncio.get_event_loop()

async def make_pool():
return await create_pool(**DB_CONFIG)

app = Sanic(__name__)
pool = loop.run_until_complete(make_pool())

async def create_db():
""" Create some table and add some data

async def create_db(app, loop):
"""
Create some table and add some data
"""
async with pool.acquire() as connection:
async with connection.transaction():
await connection.execute('DROP TABLE IF EXISTS sanic_post')
await connection.execute("""CREATE TABLE sanic_post (
id serial primary key,
content varchar(50),
post_date timestamp
);""")
for i in range(0, 100):
await connection.execute(f"""INSERT INTO sanic_post
(id, content, post_date) VALUES ({i}, {i}, now())""")
async with create_pool(**DB_CONFIG) as pool:
async with pool.acquire() as connection:
async with connection.transaction():
await connection.execute('DROP TABLE IF EXISTS sanic_post')
await connection.execute("""CREATE TABLE sanic_post (
id serial primary key,
content varchar(50),
post_date timestamp
);""")
for i in range(0, 100):
await connection.execute(f"""INSERT INTO sanic_post
(id, content, post_date) VALUES ({i}, {i}, now())""")


@app.route("/")
async def handler(request):
async with pool.acquire() as connection:
async with connection.transaction():
results = await connection.fetch('SELECT * FROM sanic_post')
return json({'posts': jsonify(results)})
async with create_pool(**DB_CONFIG) as pool:
async with pool.acquire() as connection:
async with connection.transaction():
results = await connection.fetch('SELECT * FROM sanic_post')
return json({'posts': jsonify(results)})


if __name__ == '__main__':
loop.run_until_complete(create_db())
app.run(host='0.0.0.0', port=8000, loop=loop)
app.run(host='0.0.0.0', port=8000, before_start=create_db)
16 changes: 7 additions & 9 deletions examples/sanic_peewee.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,18 @@
from sanic.response import json

## peewee_async related imports
import uvloop
import peewee
from peewee_async import Manager, PostgresqlDatabase

# we instantiate a custom loop so we can pass it to our db manager
loop = uvloop.new_event_loop()

database = PostgresqlDatabase(database='test',
host='127.0.0.1',
user='postgres',
password='mysecretpassword')
def setup(app, loop):
database = PostgresqlDatabase(database='test',
host='127.0.0.1',
user='postgres',
password='mysecretpassword')

objects = Manager(database, loop=loop)
objects = Manager(database, loop=loop)

## from peewee_async docs:
# Also there’s no need to connect and re-connect before executing async queries
Expand Down Expand Up @@ -76,5 +75,4 @@ async def get(request):


if __name__ == "__main__":
app.run(host='0.0.0.0', port=8000, loop=loop)

app.run(host='0.0.0.0', port=8000, before_start=setup)
3 changes: 0 additions & 3 deletions sanic/sanic.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ def __init__(self, name=None, router=None,
self.response_middleware = deque()
self.blueprints = {}
self._blueprint_order = []
self.loop = None
self.debug = None
self.sock = None
self.processes = None
Expand Down Expand Up @@ -296,7 +295,6 @@ def run(self, host="127.0.0.1", port=8000, debug=False, before_start=None,
:param sock: Socket for the server to accept connections from
:param workers: Number of processes
received before it is respected
:param loop: asyncio compatible event loop
:param protocol: Subclass of asyncio protocol class
:return: Nothing
"""
Expand All @@ -319,7 +317,6 @@ def run(self, host="127.0.0.1", port=8000, debug=False, before_start=None,
'error_handler': self.error_handler,
'request_timeout': self.config.REQUEST_TIMEOUT,
'request_max_size': self.config.REQUEST_MAX_SIZE,
'loop': loop,
'register_sys_signals': register_sys_signals,
'backlog': backlog
}
Expand Down
2 changes: 1 addition & 1 deletion sanic/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ def serve(host, port, request_handler, error_handler, before_start=None,
:param protocol: Subclass of asyncio protocol class
:return: Nothing
"""
loop = loop or async_loop.new_event_loop()
loop = async_loop.new_event_loop()
asyncio.set_event_loop(loop)

if debug:
Expand Down
4 changes: 2 additions & 2 deletions sanic/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ async def local_request(method, uri, cookies=None, *args, **kwargs):


def sanic_endpoint_test(app, method='get', uri='/', gather_request=True,
loop=None, debug=False, server_kwargs={},
debug=False, server_kwargs={},
*request_args, **request_kwargs):
results = []
exceptions = []
Expand All @@ -36,7 +36,7 @@ async def _collect_response(sanic, loop):
app.stop()

app.run(host=HOST, debug=debug, port=PORT,
after_start=_collect_response, loop=loop, **server_kwargs)
after_start=_collect_response, **server_kwargs)

if exceptions:
raise ValueError("Exception during request: {}".format(exceptions))
Expand Down
Loading

0 comments on commit fad9fbc

Please sign in to comment.