Last active
March 9, 2019 07:03
-
-
Save nszceta/087a14d8896e47bc6e7e441fd60b6ff4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# thanks Eli! https://github.com/seemethere | |
import os | |
import asyncio | |
import uvloop | |
from asyncpg import connect, create_pool | |
from sanic import Sanic | |
from sanic.response import json | |
DB_CONFIG = {} # FIXME: your DB config here | |
def jsonify(records): | |
""" | |
Parse asyncpg record response into JSON format | |
""" | |
return [dict(r.items()) for r in records] | |
app = Sanic(__name__) | |
@app.listener('before_server_start') | |
async def register_db(app, loop): | |
app.pool = await create_pool(**DB_CONFIG, loop=loop, max_size=100) | |
async with app.pool.acquire() as connection: | |
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, 1000): | |
await connection.execute(f"""INSERT INTO sanic_post | |
(id, content, post_date) VALUES ({i}, {i}, now())""") | |
@app.get('/') | |
async def root_get(request): | |
async with app.pool.acquire() as connection: | |
results = await connection.fetch('SELECT * FROM sanic_post') | |
return json({'posts': jsonify(results)}) | |
if __name__ == '__main__': | |
app.run(host='127.0.0.1', port=8080) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this demo, I'm a beginner of sanic and asyncpg, it help me much. But I ran this code and it seems my server can only handle about 220 requests per seconds, I'm super confused.
My environment:
Is there any possible reason could lead to this result? Thanks!