python+flask+postgresql 学习

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()

猜你喜欢

转载自blog.csdn.net/hanyuyang19940104/article/details/80479630