python+flask+postgresql 学习
2015-08-19 16:25
656 查看
1、安装PostgreSQL
去官网下载安装:http://www.postgresql.org/download/
2、安装psycopg2
是一个PostgreSQL数据库连接库
去http://www.stickpeople.com/projects/python/win-psycopg/ 下载安装
一开始是pip install postgresql安装的,但是安装不成功。
3、创建postgresql触发器
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、创建应用
去官网下载安装: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()
相关文章推荐
- Python中的tuple
- Python函数式编程指南(三):迭代器
- Python 使用正则表达式 - 1
- Python递归查找目录
- LeetCode:Sliding Window Maximum 题解 Python
- python文件小号单排。。。。(这局没打好。。。-25)
- 【转】Python调用C函数
- 64位win7下安装numpy,scipy,matplotlib
- Streaming+Python实现Itembased CF
- 学习python第一步,spyder开发环境的搭建
- Django 开发 Python Web应用
- python之路-----web应用的创建(python3.4下,django连接mysql)
- Python中如何创建文件夹和嵌套文件夹的方法
- Python——面向对象
- 03-树2. List Leaves (25) Python C
- wxPython+Boa Constructor环境配置
- Python数组排序
- wxpython 基本的控件 (文本)
- wxPython中文教程入门实例
- 如何选择python web开发框架