python+flask+postgresql 学习

本文介绍了如何利用PostgreSQL数据库和Python编程语言创建触发器,并结合psycopg2库实现实时消息流应用。通过创建触发器和表结构,实现了数据库与应用之间的高效交互,同时展示了如何使用Python进行实时数据处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、安装PostgreSQL

去官网下载安装:http://www.postgresql.org/download/


2、安装psycopg2

是一个PostgreSQL数据库连接库

去http://www.stickpeople.com/projects/python/win-psycopg/ 下载安装


一开始是pip install postgresql安装的,但是安装不成功。


3、创建postgresql触发器

create or replace function notify_on_insert() returns trigger as $$
begin
   PERFORM pg_notify('channel_'||new.channel,cast(row_to_json(new) as text));
   return null;
end;
$$ language plpgsql;

create trigger notify_on_message_insert after insert ON message
for each row execute procedure notify_on_insert();


4、创建表结构:

CREATE TABLE "public"."message" (
"id" int4 DEFAULT nextval('message_id_seq'::regclass) NOT NULL,
"channel" int4 NOT NULL,
"source" text COLLATE "default" NOT NULL,
"context" text COLLATE "default" NOT NULL,
CONSTRAINT "message_pkey" PRIMARY KEY ("id")
)
WITH (OIDS=FALSE)
;


5、创建应用

import flask
import psycopg2
import psycopg2.extensions
import select

app = flask.Flask(__name__)

def stream_messages(channel):
    conn = psycopg2.connect(database='MyTest',user='postgres',password='123456',host='localhost')
    conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)

    curs = conn.cursor()
    curs.execute('LISTEN channel_%d;'%int(channel))

    while True:
        select.select([conn],[],[])
        conn.poll()
        while conn.notifies:
            notify = conn.notifies.pop()
            yield "data:"+notify.payload+"\n\n"

@app.route("/message/<channel>",methods=['GET'])
def get_messages(channel):
    return flask.Response(stream_messages(channel),mimetype='text/event-stream')

if __name__ == "__main__":
    app.run()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值