Permalink
Browse files

finally got this running locally and on heroku

  • Loading branch information...
0 parents commit 3098ec0cdf7d9d90cf6fcda52b7124dfc98859d5 @cpdean committed Jun 10, 2012
Showing with 318 additions and 0 deletions.
  1. +5 −0 .gitignore
  2. +1 −0 Procfile
  3. +71 −0 app.py
  4. +98 −0 db.py
  5. +3 −0 dev_server.sh
  6. +2 −0 manage.py
  7. +7 −0 requirements.txt
  8. +3 −0 run_tests.sh
  9. +9 −0 schema.sql
  10. +9 −0 start-server.sh
  11. 0 static/style.css
  12. +34 −0 templates/posts.html
  13. +22 −0 templates/view_post.html
  14. +54 −0 tests.py
@@ -0,0 +1,5 @@
+v
+*.swp
+*.pyc
+database
+test-db
@@ -0,0 +1 @@
+web: python app.py
71 app.py
@@ -0,0 +1,71 @@
+#!/usr/bin/python
+from flask import Flask
+from flask import render_template
+from flask import request
+from flask import redirect
+from flask import url_for
+
+from werkzeug import secure_filename
+import os
+
+
+app = Flask(__name__)
+
+ALLOWED_EXTENSIONS = set(['jpg'])
+
+import db
+
+
+@app.route('/')
+def index():
+ return redirect(url_for("post_list"))
+
+@app.route('/posts/',methods=['POST','GET'])
+def post_list():
+ if request.method == 'POST':
+ p = db.Post()
+ p.title = request.form['title']
+ p.caption = request.form['caption']
+ i_data = get_image(request)
+ p.image_data = i_data if i_data is not None else ''
+ p.save()
+ return redirect(url_for("post_list"))
+
+ elif request.method == 'GET':
+ posts = db.Post().show()
+ return render_template("posts.html", posts=posts )
+
+#FILE HANDLING
+
+def allowed_file(filename):
+ return '.' in filename and\
+ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
+
+def get_image(r):
+ image = r.files['file']
+ if image and allowed_file(image.filename):
+ return image.read()
+
+@app.route('/post/',methods=['POST','GET'])
+def redirect_to_latest():
+ return redirect(url_for("show_latest_post"))
+
+@app.route('/post/latest',methods=['POST','GET'])
+def show_latest_post():
+ post = db.get_latest_post()
+ return render_template("view_post.html", post=post )
+
+@app.route('/post/<int:post_id>',methods=['POST','GET'])
+def show_post(post_id=None):
+ if request.method == 'POST':
+ pass
+
+ elif request.method == 'GET':
+ post = db.Post(post_id)
+ return render_template("view_post.html", post=post )
+
+
+if __name__ == '__main__':
+ port = int(os.environ.get("PORT",5000))
+ app.debug = True if port == 5000 else False
+ app.run(host="0.0.0.0",port=port)
98 db.py
@@ -0,0 +1,98 @@
+from datetime import datetime
+
+import psycopg2
+
+from os.path import exists
+from os import makedirs
+import os
+
+import urlparse
+
+urlparse.uses_netloc.append('postgres')
+url = urlparse.urlparse(os.environ.get('DATABASE_URL',"postgres://herokuflask@localhost/herokudb"))
+
+db = "dbname=%s user=%s password=%s host=%s " % (url.path[1:], url.username, url.password, url.hostname)
+
+schema = "schema.sql"
+
+def open_database_connection():
+ #return psycopg2.connect('dbname=herokudb user=herokuflask')
+ return psycopg2.connect(db)
+
+def connect_db():
+ return open_database_connection()
+
+def init_db():
+ conn = open_database_connection()
+ with open(schema) as s:
+ c = conn.cursor()
+
+ c.execute(s.read())
+ conn.commit()
+ conn.close()
+
+def get_latest_post():
+ conn = connect_db()
+ c = conn.cursor()
+ c.execute( """
+ select post_id
+ from
+ Post
+ order by
+ post_date DESC
+ limit 1;
+ """)
+ id_record = c.fetchone()
+ post_id = id_record[0]
+ post_id = int(post_id)
+ conn.close()
+ return Post(post_id)
+
+
+
+class Post:
+
+ def __init__(self,post_id=None):
+ if not post_id:
+ self.post_date = datetime.now()
+ self.title = "This is the title"
+ self.caption = "The caption"
+ self.post_id = None
+ self.image_data = ""
+ else:
+ conn = connect_db()
+ c = conn.cursor()
+ c.execute("""select post_id,post_date,title,caption
+ from Post
+ where post_id = (%s)""", (post_id,))
+
+ post_id,post_date,title,caption = c.fetchone()
+ self.post_id = post_id
+ self.post_date = post_date
+ self.title = title
+ self.caption = caption
+ conn.close()
+
+
+ def save(self):
+ if self.post_id is None:
+ conn = connect_db()
+ c = conn.cursor()
+ c.execute("""insert into post
+ (post_date,title,caption,image_data)
+ VALUES
+ (%s,%s,%s,%s);
+ """,(self.post_date, self.title, self.caption,self.image_data))
+ conn.commit()
+ conn.close()
+
+ def show(self):
+ conn = connect_db()
+ c = conn.cursor()
+ c.execute("select post_id,post_date,title,caption from Post order by post_date")
+ r = c.fetchall() #rows
+ posts = [(i,d,t,com) for i,d,t,com in r]
+
+ conn.close()
+ return posts
+
@@ -0,0 +1,3 @@
+export DATABASE_URL="postgres://herokuflask@localhost/herokudb"
+source v/bin/activate
+python app.py
@@ -0,0 +1,2 @@
+import db
+db.init_db()
@@ -0,0 +1,7 @@
+Flask==0.8
+Jinja2==2.6
+Werkzeug==0.8.3
+argparse==1.2.1
+distribute==0.6.24
+psycopg2==2.4.5
+wsgiref==0.1.2
@@ -0,0 +1,3 @@
+export DATABASE_URL="postgres://herokuflask@localhost/herokudb"
+source v/bin/activate
+python tests.py
@@ -0,0 +1,9 @@
+drop table if exists post;
+create table post (
+ post_id SERIAL,
+ post_date TIMESTAMP,
+ title VARCHAR(80),
+ caption VARCHAR(80),
+ image_data BYTEA,
+ PRIMARY KEY (post_id)
+);
@@ -0,0 +1,9 @@
+#!/bin/bash
+
+#naive dependency check
+if [ ! -d "v" ]; then
+ virtualenv v
+ pip install -r requirements.txt -E v
+fi
+source v/bin/activate
+python app.py
No changes.
@@ -0,0 +1,34 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <meta http-equiv="content-type" content="text/html; charset=utf-8">
+
+ <title>Posts</title>
+
+</head>
+<body>
+ <ul>
+ {% for id,date,title,caption in posts %}
+ <li>
+ <h3>
+ <a href="/post/{{ id }}"> {{ title }} </a>
+ </h3>
+ <h4>
+ {{ date }}
+ </h4>
+ <div>
+ {{ caption }}
+ </div>
+ </li>
+ {% endfor %}
+ </ul>
+ <form action="/posts/" method="POST" enctype=multipart/form-data>
+ title
+ <input type="text" name="title" value=""/>
+ caption
+ <input type="text" name="caption" value=""/>
+ <input type="file" name="file"/>
+ <input type="submit" name="some_name" value=""/>
+ </form>
+</body>
+</html>
@@ -0,0 +1,22 @@
+
+<!DOCTYPE HTML>
+<html>
+<head>
+ <meta http-equiv="content-type" content="text/html; charset=utf-8">
+
+ <title>{{ post.title }}</title>
+
+</head>
+<body>
+ <h3>
+ <a href="/post/{{ post.id }}"> {{ post.title }} </a>
+ </h3>
+ <h4>
+ {{ post.date }}
+ </h4>
+ <div>
+ {{ post.body }}
+ </div>
+ <a href="/posts/">back</a>
+</body>
+</html>
@@ -0,0 +1,54 @@
+import unittest
+import db
+import os
+import datetime
+
+os.environ['DATABASE_URL'] = "postgres://herokuflask@localhost/herokudb"
+
+class TestDatabase(unittest.TestCase):
+
+ def setUp(self):
+ db.init_db()
+
+ def injectSeveralPosts(self,n):
+ for i in range(n):
+ p = db.Post()
+ p.title = "injected"
+ p.save()
+
+
+ def test_connect(self):
+ c = db.connect_db()
+ cur = c.cursor()
+ # ensure the post table is there
+ cur.execute("select exists(select * from information_schema.tables where table_name=%s)", ('post',))
+ self.assertEqual(cur.fetchone()[0],True)
+
+ def test_make_post(self):
+ p = db.Post()
+ p.title = "PostTitle"
+ p.caption = "Postcaption"
+ p.save()
+ new_p = db.get_latest_post()
+
+ self.assertEqual(new_p.title,p.title)
+ self.assertEqual(new_p.caption,p.caption)
+
+ def test_date_datatype(self):
+ now = datetime.datetime.now()
+ p = db.Post()
+ p.post_date = now
+ p.save()
+ new_p = db.get_latest_post()
+
+ self.assertEqual(new_p.post_date,p.post_date)
+
+ def test_show_posts(self):
+ self.injectSeveralPosts(10)
+ posts = db.Post().show()
+ self.assertEquals(len(posts),10)
+
+
+
+if __name__ == '__main__':
+ unittest.main()

0 comments on commit 3098ec0

Please sign in to comment.