您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“Sanic如何連接postgresql數(shù)據(jù)庫(kù)”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Sanic如何連接postgresql數(shù)據(jù)庫(kù)”這篇文章吧。
1.安裝系統(tǒng)包
# yum install postgresql-devel
2.安裝Python包
peewee-2.8.5.tar.gz
psycopg2-2.6.2.tar.gz
1).安裝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).安裝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.目錄結(jié)構(gòu)
/home/webapp
|-- main.py
|-- my_blueprint.py
templates
|-- index.html
4.文件內(nèi)容:
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="10">
<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.瀏覽器運(yùn)行結(jié)果
以上是“Sanic如何連接postgresql數(shù)據(jù)庫(kù)”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。