I'm just getting started with flask and I'm trying to build the tutorial micro-blog using redis. Here is my app:
from flask import Flask, render_template, request, url_for, redirect
import redis
from datetime import datetime
app = Flask(__name__)
app.config.from_object(__name__)
app.config.update(dict(
DEBUG = True,
))
POOL = redis.ConnectionPool(host='localhost', port=6379, db=0)
@app.route("/")
def index():
r = redis.StrictRedis(connection_pool = POOL)
print r
pipe = r.pipeline()
print pipe
last_ten = pipe.zrange('post:created_on', 0, 9)
print last_ten
posts = []
for post in last_ten:
posts.append(pipe.hgetall('{}{}'.format('post:', post)))
print posts
pipe.execute()
return render_template('index.html', posts)
@app.route('/new', methods = ['POST'])
def addPost():
r = redis.StrictRedis(connection_pool = POOL)
title = request.form['title']
author = request.form['author']
now = datetime.now()
pipe = r.pipeline()
post_format = 'post:'
pid = pipe.incr('post')
pipe.hmset('{}{}'.format(post_format,pid), {'title':title, 'author':author})
pipe.zadd('post:created_on', pid = now)
pipe.execute()
return redirect(url_for('index'))
if __name__ == "__main__":
app.run()
When I run python testapp.py
I get
* Running on http://127.0.0.1:5000/
* Restarting with reloader
However the page never loads at http://127.0.0.1:5000/
nor does it return an error. It just hangs, trying to load forever. I've left it for a while and it just keeps on going. I'm not sure what would be causing this but thank you for your help.
UPDATE: I have added several print
statements in my index
view to see what is happening while that code runs and this is what was printed to the terminal.
* Running on http://127.0.0.1:5000/
* Restarting with reloader
StrictRedis<ConnectionPool<Connection<host=localhost,port=6379,db=0>>>
StrictPipeline<ConnectionPool<Connection<host=localhost,port=6379,db=0>>>
StrictPipeline<ConnectionPool<Connection<host=localhost,port=6379,db=0>>>
I believe I have solved the issue. The problem was that I opened a pipeline
and tried acting on the data retrieved from the db before I had called pipe.execute
. I'm still working on getting the overall function to work but this is how I solved this particular issue.