1. Install the System Package
# yum Install Postgresql-devel
2. Install the Python package
Peewee-2.8.5.tar.gz
Psycopg2-2.6.2.tar.gz
1). Install Peewee-async
# pip Install Peewee-async
Collecting Peewee-async
Downloading PEEWEE_ASYNC-0.5.6-PY3-NONE-ANY.WHL
Requirement already satisfied:peewee>=2.8.0 in/usr/local/lib/python3.5/site-packages (from Peewee-async)
Installing collected Packages:peewee-async
Successfully installed peewee-async-0.5.6
#
2). Install AIOPG
# pip Install AIOPG
Collecting AIOPG
Using Cached AIOPG-0.13.0-PY3-NONE-ANY.WHL
Requirement already satisfied:psycopg2>=2.5.2 in/usr/local/lib/python3.5/site-packages/ Psycopg2-2.6.2-py3.5-linux-x86_64.egg (from AIOPG)
Installing collected PACKAGES:AIOPG
Successfully installed aiopg-0.13.0
#
3. Directory structure
/home/webapp
|--main.py
|--my_blueprint.py
Templates
|--index.html
4. Contents of the file:
1). main.py
# more main.py
From sanic import sanic
From My_blueprint import bp
App = Sanic (__name__)
App.blueprint (BP)
App.run (host= ' 0.0.0.0 ', port=8000, Debug=true)
#
2). my_blueprint.py
# more my_blueprint.py
From sanic import Blueprint
From Sanic.response import JSON, text, HTML
# # JINJA2 Template # # # #
From JINJA2 import Environment, Packageloader
ENV = Environment (Loader=packageloader (' my_blueprint ', ' templates '))
# # database # # #
Import Uvloop, PeeWee
From Peewee_async import postgresqldatabase
bp = Blueprint (' My_blueprint ')
# init DB connection
Global database
Database = Postgresqldatabase (database= ' webdb ',
Host= ' 127.0.0.1 ',
User= ' Postgres ',
password= ' 111111 ')
# router Define
@bp. Route ('/')
Async def bp_root (request):
Serialized_obj = []
cursor = Database.execute_sql (' select * from T1; ')
For row in Cursor.fetchall ():
Serialized_obj.append ({
' ID ': row[0],
' Name ': row[1]}
)
Template = Env.get_template (' index.html ')
Content=template.render (Items=serialized_obj)
return HTML (content)
#
3). index.html
# more Index.html
<!doctype html>
<title> Sanic </title>
<div class=page>
<table border= "1" cellpadding= "ten" >
<tr>
<th>id</th>
<th>name</th>
</tr>
{% for item in items%}
<tr>
<td> {{item.id}} </td>
<td> {{Item.name}} </td>
</tr>
{% ENDFOR%}
</table>
</div>
#
5. Browser Run Results
This article is from the "Yiyi" blog, make sure to keep this source http://heyiyi.blog.51cto.com/205455/1882032
Sanic Connecting the PostgreSQL database