加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Sanic 连接postgresql数据库

发布时间:2020-12-13 16:59:55 所属栏目:百科 来源:网络整理
导读:1.安装系统包 # 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

1.安装系统包

# 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.目录结构

/home/webapp

|--main.py

|--my_blueprint.py

templates

|--index.html



4.文件内容:


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='222221')


# 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.浏览器运行结果


wKiom1hOfM6CNvI6AABxnX5BLSc496.jpg-wh_50

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读