Sanic如何连接postgresql数据库
admin
2023-05-29 16:01:56
0

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

Sanic

 

 

   

   

 

  {% for item in items %}

   

   

   

 

   

  {% endfor %}

 

idname
` item`.`id ` ` item`.`name `

5.浏览器运行结果

Sanic如何连接postgresql数据库

相关内容

热门资讯

从经贸合作到点名日本,中俄42... 【文/观察者网 王慧】5月19日至20日,俄罗斯总统普京对华进行国事访问,这是普京总统第25次到访中...
税务局工作人员上班时脚跷在桌上... 极目新闻记者 余渊5月21,国家税务总局海口市税务局发布情况通报:近期,有群众反映,我局一名工作人员...
太精辟!岛内二创《唐伯虎点秋香... “池塘里,板没电水没鱼,渔电共生可笑可笑”“货柜里,蛋发臭薯发芽,提醒民众提防提防”“二创版《唐伯虎...
胡锡进:我不认为特朗普真的能与... 特朗普周三表示,他将与赖清德就对台军售问题进行对话,引起轩然大波。周三,在被记者问到他是否计划就美国...
台北市选情突变:白营曾妍洁退党... 海峡导报综合报道 2026年底台湾地区“九合一”选举临近,岛内各政党积极部署。在国民党传统优势选区的...
空调室外机不转怎么办 如果是因为空调设置错了导致不转,那么可以重新调成正确的模式;如果是因为电源出现故障,那么可以重新插一...
防溅水龙头里面是怎么安的 安装防溅水龙头时,首先我们需要准备好工具:扳手、生料带、防溅水龙头。先将总闸关闭,以免在拆卸原先的水...
安卓手机怎么安装Adobe F... 安卓手机用户可能有时候看不了一些flash动画或者视频。那么安卓手机怎么安装Adobe Flash ...
博士洗衣机的洗涤专用盒A怎么安 1、首先要了解博士洗衣机是哪种型号的。依照小格子中的标注为“1”,此格用做预添加洗衣液,当选择带有预...