我是靠谱客的博主 敏感康乃馨,这篇文章主要介绍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触发器

复制代码
1
2
3
4
5
6
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;

复制代码
1
2
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、创建应用

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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+"nn" @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()


最后

以上就是敏感康乃馨最近收集整理的关于python+flask+postgresql 学习的全部内容,更多相关python+flask+postgresql内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(72)

评论列表共有 0 条评论

立即
投稿
返回
顶部