0

i started developing my app with aiopg to access data in postgres and everything was OK , i decided to replace it with asyncpg .

this is one of my view function :

@router.get('/{post}')
@aiohttp_jinja2.template("view.html")
async def view_post(request):
    ret = {'id':'1','owner':'shooooobi','editor':'shooooobi','title':'new_title','text':'nothing'}

    return {"post":ret}

it is a simple view and is ok but when i added some asyncpg code like following ,i added line 4 to 7 line by line and run app ...

@router.get('/{post}')
@aiohttp_jinja2.template("view.html")
async def view_post(request):
    pg  = request.config_dict["PG"]
    post_id = request.match_info["post"]
    con = pg.acquire()
    cur = con.cursor('SELECT id, owner, editor, title, text FROM mshma.posts where id=$1',post_id)
    ret = {'id':'1','owner':'shooooobi','editor':'shooooobi','title':'new_title','text':'nothing'}

    return {"post":ret}

line 7 cause that i received following text in my web page.

context should be mapping, not <class 'set'>

when i comment this line (line 7) my view function works as expected . what is the problem??

Shoobi
  • 88
  • 1
  • 10
  • If your question was answered please mark it as [solved](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – Ionut Ticus May 12 '20 at 21:41

2 Answers2

0

You need to use await for async calls; here is a snippet on how to acquire a connection from the pool, run a query and release the connection back to the pool

conn = await pg.acquire()
try:
    result = await conn.fetchrow("SELECT id, owner, editor, title, text FROM mshma.posts where id=$1", post_id)
finally:
    await pg.release(conn)
# do something with result (which is an asyncpg.Record object)

Ionut Ticus
  • 2,683
  • 2
  • 17
  • 25
  • it doesn't work !!, i think asyncpg change something in aiohttp_jinja2 . – Shoobi May 09 '20 at 18:27
  • 1
    The error message `context should be mapping` does point to a jinja issue; try to return the data retrieved using asyncpg without the jinja2 decorator like: `return json.dumps(dict(result))` – Ionut Ticus May 10 '20 at 09:15
  • Try: `return {"post": dict(result)}` where result is from my above snippet – Ionut Ticus May 10 '20 at 19:00
  • i just convert parameter to integer : int(post_id) , now it works ! it didn't show me errore until i delete jinja2 template .thanks . – Shoobi May 13 '20 at 08:46
0

executing this query is failed , because the parameter id column is integer and the parameter post_id is string , errors wouldn't be shown when we use jinja2 template!!. we just need to convert post_id to integer (int(post_id))

Shoobi
  • 88
  • 1
  • 10