-
Notifications
You must be signed in to change notification settings - Fork 1
/
webapp.py
100 lines (73 loc) · 2.9 KB
/
webapp.py
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import json
from datetime import datetime
import redis
from flask import Flask, Response, render_template, url_for, flash, request
from flask.ext.sqlalchemy import SQLAlchemy
from wtforms import *
from flask.ext.wtf import Form
from socketio import socketio_manage
from socketio.namespace import BaseNamespace
from socketio.mixins import RoomsMixin
app = Flask(__name__)
app.debug = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/msgs.db'
app.config['SECRET_KEY'] = 'blah'
db = SQLAlchemy(app)
r = redis.StrictRedis()
class Message(db.Model):
__tablename__ = 'messages'
id = db.Column(db.Integer, primary_key=True)
subject = db.Column(db.String(256), nullable=False)
content = db.Column(db.Text)
to = db.Column(db.Integer, nullable=False, index=True)
unread = db.Column(db.Boolean, default=True)
sent_at = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return 'To: id<{}> \n Sub: {}'.format(self.to, self.subject)
def dict(self):
return dict(id=self.id, subject=self.subject, content=self.content, to=self.to, unread=self.unread, sent_at=self.sent_at.isoformat())
def save(self):
db.session.add(self)
db.session.commit()
class ShowInterestForm(Form):
show_interest = SubmitField('Show Interest')
@app.route('/')
def user_list():
return render_template('users_list.html')
@app.route('/users/<int:id>', methods=['GET', 'POST'])
def users(id):
form = ShowInterestForm()
if form.validate_on_submit():
msg = Message(to=id, subject='Interest shown', content='Somebody has shown interest to user {}'.format(id))
msg.save()
r.publish('msg:{}'.format(id), json.dumps(msg.dict()))
flash('Thanks for showing interest.')
return render_template('user.html', id=id, form=form)
@app.route('/users/<id>/inbox')
def inbox(id):
msgs = Message.query.filter_by(to=id).order_by('sent_at').all()
return render_template('inbox.html', id=id, msgs=msgs)
class MessagesNamespace(BaseNamespace):
def initialize(self):
self.logger = app.logger
self.log("Socketio session started")
def log(self, message):
self.logger.info("[{0}] {1}".format(self.socket.sessid, message))
def on_join(self, user_id):
print 'User #{} has joined'.format(user_id)
self.room = 'msg:{}'.format(user_id)
self.pubsub = r.pubsub()
self.pubsub.subscribe('msg:{}'.format(user_id))
self.spawn(self.listener)
return True
def listener(self):
for item in self.pubsub.listen():
self.emit('newmsg', json.loads(str(item['data'])))
@app.route('/socket.io/<path:remaining>')
def socketio(remaining):
try:
socketio_manage(request.environ, {'/msgs': MessagesNamespace}, request)
except:
app.logger.error("Exception while handling socketio connection",
exc_info=True)
return Response()