python+flask+postgresql 学习

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 messagefor 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 flaskimport psycopg2import psycopg2.extensionsimport selectapp = 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+""@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()

免责声明:本网信息来自于互联网,目的在于传递更多信息,并不代表本网赞同其观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,并请自行核实相关内容。本站不承担此类作品侵权行为的直接责任及连带责任。如若本网有任何内容侵犯您的权益,请及时联系我们,本站将会在24小时内处理完毕。
相关文章
返回顶部