Skip to content
This repository was archived by the owner on Jan 20, 2025. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
4ccf8e8
initial commit
abhinandam Oct 24, 2016
f2aba96
update index
abhinandam Oct 24, 2016
06bc0c0
max length is 140
abhinandam Oct 24, 2016
3abd8e4
add assignment requirements
afeld Oct 26, 2016
43c5e5c
add empty requirements file
afeld Oct 29, 2016
731edd5
add basic python gitignore
afeld Oct 29, 2016
187c715
add django things to gitignore
afeld Oct 29, 2016
b8ce4bb
add instructions about how to run from the VM
afeld Oct 29, 2016
464908c
add more setup tips to readme
afeld Oct 30, 2016
2692370
add PEP8 configuration
afeld Oct 30, 2016
19b8d7b
copy in (and tweak) squawker tests
afeld Oct 30, 2016
e785e00
fix up tips section
afeld Oct 30, 2016
e5283d6
add travis config
afeld Oct 30, 2016
f64353f
Merge pull request #2 from startup-systems/travis
afeld Oct 30, 2016
d57d11c
add code climate config
afeld Oct 30, 2016
e37653c
kick code climate
afeld Oct 30, 2016
4f8544a
Merge pull request #3 from startup-systems/code-climate
afeld Oct 30, 2016
50de8ad
add more heroku instructions
afeld Oct 31, 2016
fc45b7d
check for status code of 400 when testing server-side validation
afeld Nov 1, 2016
45c0026
initial commit
abhinandam Nov 1, 2016
617b749
push to heroku
abhinandam Nov 1, 2016
3965510
Merge branch 'master' of https://github.com/startup-systems/squawker-…
abhinandam Nov 1, 2016
d821809
add static root
abhinandam Nov 1, 2016
b0ca004
add allowed hosts
abhinandam Nov 1, 2016
fcaa3a3
update indentation
abhinandam Nov 1, 2016
27ada08
update indentation
abhinandam Nov 1, 2016
1688b0a
update indentation
abhinandam Nov 1, 2016
f9915ef
add charts
abhinandam Mar 18, 2017
a2be54f
update to buddy bear
abhinandam Mar 27, 2017
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,8 @@ __pycache__/
*.db3
*.sqlite
*.sqlite3
<<<<<<< HEAD
=======
*.log
local_settings.py
>>>>>>> 1688b0ad1e792c142f9f753754c029e1225d374f
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: gunicorn squawker.wsgi --log-file -
106 changes: 6 additions & 100 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,106 +1,12 @@
# Squawker
# BuddyBear

In this assignment, you will build simplified Twitter clone. We'll refer to the individual messages as "squawks".
## Narrative
1 in 68 children suffer from autism spectrum disorder, a disorder that prevents them from comprehending basic human emotion. We are developing Buddy Bear, a companion that utilizes computer vision to recognize emotions in others and conveys this emotion to the child in a simple, easy to understand manner.

## Requirements
## Product

* The homepage (`/`) contains:
* A single form, to post a new squawk (**5%**)
* All past squawks (**20%**)
* Sorted from newest to oldest (**20%**)
* Submitting the form:
1. Creates a new squawk (**30%**)
1. Shows / takes the user back to the homepage (**5%**)
* In other words, they should see the updated homepage with the new squawk.
* Squawks are limited to 140 characters
* Client-side (**5%**)
* Uses HTML5 form validation
* Server-side (**10%**)
* Responds with a status code of 400 if the form is submitted with invalid data.
* Passes Code Climate checks (**5%**)
* The site works without JavaScript
* Built using [Flask](http://flask.pocoo.org/) and [`sqlite3`](https://docs.python.org/3/library/sqlite3.html)
Buddy Bear - physical device

Visual styling is not considered as part of the score, though feel free to get creative! In other words, feel free to make your site pretty, but not a problem if it isn't.
Dashboard - metric tracking

### Extra credit

* Pagination (**20%**)
* The squawks are shown 20 at a time
* There's a `Next` link to see older squawks, if there are any

## Setup

1. Update your [VM](https://github.com/startup-systems/vm), if you didn't do so for the [time](https://docs.google.com/document/d/15VzRMLHLGm_l9dzUObQlsOoY12J_jH3U0b9Bu2yi6EI/edit#heading=h.lyptz0o698my) assignment already. From your host machine:

```shell
cd path/to/vm/
git pull -s recursive -X ours https://github.com/startup-systems/vm.git master
vagrant reload
```

1. [Set up the database.](#set-up-the-database)

## Development workflow

1. Start the server. From your VM:

```shell
cd /vagrant/squawker
pip3 install -r requirements.txt
FLASK_APP=squawker/server.py FLASK_DEBUG=1 flask run --host=0.0.0.0
```

1. Open http://localhost:5000 from your host machine.
1. Modify [`squawker/server.py`](squawker/server.py).
1. Refresh.

## Set up the database

Note that this will delete any existing content.

1. Modify the [`squawker/schema.sql`](squawker/schema.sql) file.
1. Run

```shell
FLASK_APP=squawker/server.py flask initdb
```
Repeat these steps when you need to update the schema.

## Running tests locally

Run the following from this directory:

```shell
# run the pytests
pytest --tb short
# run the pep8 checks
pep8
# check the extra credit
pytest --tb short --runxfail
```

## Things you will need

* [Flask template(s)](http://flask.pocoo.org/docs/0.11/quickstart/#rendering-templates)
* [Jinja2 syntax](http://jinja.pocoo.org/docs/dev/templates/)
* An [HTML form](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms)
* Change/addition of routes in Flask
* Some basic SQL understanding
* SQLite3 CLI
* Useful for inspecting your database
* Install in your VM with

```shell
sudo apt-get update
sudo apt-get install sqlite3
```

### Code Climate checks

If you want to try running these locally:

1. [Install Docker](https://docs.docker.com/engine/installation/linux/ubuntulinux/) (follow the "Ubuntu Xenial 16.04 (LTS)" instructions)
1. Run the [Code Climate CLI](https://github.com/codeclimate/codeclimate#readme).

Note that **this is advanced**, so don't worry if you have trouble getting it running.
Empty file added main/__init__.py
Empty file.
5 changes: 5 additions & 0 deletions main/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.contrib import admin
from .models import Squawk

# Register your models here.
admin.site.register(Squawk)
21 changes: 21 additions & 0 deletions main/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
]

operations = [
migrations.CreateModel(
name='Squawk',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('message', models.CharField(max_length=140)),
('created', models.DateTimeField(auto_now_add=True)),
],
),
]
Empty file added main/migrations/__init__.py
Empty file.
7 changes: 7 additions & 0 deletions main/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.db import models

# Create your models here.
class Squawk(models.Model):
message = models.CharField(max_length=140)
created = models.DateTimeField(auto_now_add=True)

38 changes: 38 additions & 0 deletions main/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<!DOCTYPE html>
<html>

<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>

<head class="header" >
<div class="container">
<div class="page-heading">
<h1 class="text-center">Squawker > Twitter</h1>
</div>
</div>
</head>

<body>
<h3>Squawks</h3>
<form action="/" method="POST" class="form-inline">
{% csrf_token %}
<div class="form-group">
<label for="messageLabel">Message</label>
<input type="text" maxlength="140" class="form-control" name="message" id="message" placeholder="Sample Message">
</div>
<button type="submit" class="btn btn-primary">Post Message</button>


<div class="displayMessages">
<label for="loadMessages">All Squawks</label>
{% for squawk in squawks %}
<div>
<p>{{ squawk.message }}</p>
<p>{{ squawk.created }}</p>
</div>
{% endfor %}
</div>
</body>
</html>
3 changes: 3 additions & 0 deletions main/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
17 changes: 17 additions & 0 deletions main/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from django.shortcuts import render
from django.http import HttpResponseBadRequest
from django.http import HttpResponse
from .models import Squawk


def root(request):
if (request.method == "POST"):
inputMessage = request.POST['message']
if (len(inputMessage) <= 140):
squawk = Squawk(message=inputMessage)
squawk.save()
else:
return HttpResponseBadRequest("Error: Message Exceeded Max Length of 140")

squawkers = Squawk.objects.order_by('-created')
return render(request, "index.html", {"squawks":squawkers})
10 changes: 10 additions & 0 deletions manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "squawker.settings")

from django.core.management import execute_from_command_line

execute_from_command_line(sys.argv)
2 changes: 2 additions & 0 deletions pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[pytest]
DJANGO_SETTINGS_MODULE=squawker.settings
1 change: 1 addition & 0 deletions runtime.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
python-3.5.2
8 changes: 6 additions & 2 deletions squawker/schema.sql
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
-- TODO change this
DROP TABLE IF EXISTS mytable;
CREATE TABLE mytable (id integer);
DROP TABLE IF EXISTS squawks;
CREATE TABLE squawks(
id INTEGER PRIMARY KEY AUTOINCREMENT,
message VARCHAR(140) NOT NULL,
timestamp INTEGER DEFAULT CURRENT_TIMESTAMP
);
18 changes: 14 additions & 4 deletions squawker/server.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from flask import Flask, g
from flask import Flask, g, render_template, abort, request
import sqlite3


Expand Down Expand Up @@ -37,11 +37,21 @@ def close_connection(exception):
# ------------------------------


@app.route('/')
@app.route('/', methods=["GET", "POST"])
def root():
conn = get_db()
# TODO change this
return "Hello World!"
if (request.method == "POST"):
message = request.form['message']
if len(message) <= 140:
cc_object = conn.execute('INSERT INTO squawks (message) VALUES (?)', [message])
conn.commit()
else:
abort(400)

cc_object = conn.execute('SELECT * FROM squawks ORDER BY timestamp desc')
squawkers = cc_object.fetchall()

return render_template('index.html', squawks=squawkers)


if __name__ == '__main__':
Expand Down
103 changes: 103 additions & 0 deletions squawker/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
"""
Django settings for squawker project.

Generated by 'django-admin startproject' using Django 1.8.7.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# add this near the top
import dj_database_url

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '&1!5zbuw_rhff)pn85p25akvr9r5$f)5(a$2rw7ko#kl07c@=z'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['an536-squawker.herokuapp.com']


# Application definition

INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main'
)

MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'squawker.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'squawker.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
# replace the DATABASES config
DATABASES = {
"default": dj_database_url.config(default='sqlite:///db.sqlite3'),
}

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
Empty file added squawker/static/.keep
Empty file.
Loading