Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
19 changes: 15 additions & 4 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

# Build and Release Folders
bin-debug/
bin-release/
Expand All @@ -7,12 +8,22 @@ bin-release/
# Other files and folders
.settings/

Virtualenv
# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
.Python
[Bb]in
[Ii]nclude
[Ll]ib
[Ll]ib64
[Ll]ocal
[Ss]cripts
pyvenv.cfg
.venv
.env
pip-selfcheck.json

# Executables
*.swf
*.air
*.ipa
*.apk

# Project files, i.e. `.project`, `.actionScriptProperties` and `.flexProperties`
# should NOT be excluded as they contain compiler settings and other important
# information for Eclipse / Flash Builder.
4 changes: 4 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
language: python
rvm: 3.7.0

sudo: enabled
Empty file added API/Questions/model.py
Empty file.
Binary file not shown.
2 changes: 2 additions & 0 deletions API/app/Questions/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@


Binary file added API/app/Questions/__pycache__/__init__.cpython-37.pyc
Binary file not shown.
Binary file added API/app/Questions/__pycache__/model.cpython-37.pyc
Binary file not shown.
Binary file not shown.
44 changes: 44 additions & 0 deletions API/app/Questions/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@

import json
from datetime import datetime
from flask import request, jsonify, abort
from . import Questions

@app.route('/questions/<int:id>', methods=['GET', 'PUT', 'DELETE'])
def question(id, **kwargs):
# GET request: Retrieve a buckelist using it's ID
question = Questions.query.filter_by(id=id).first()
if not :
# Raise an HTTPException with a 404 not found status code
abort(404)

if request.method == 'DELETE':
question.delete()
return {
"message": "Question {} deleted successfully".format(.id)
}, 200
#PUT request: Delete a question
elif request.method == 'PUT':
name = str(request.data.get('name', ''))
question.name = name
question.save()
response = jsonify({
'id': question.id,
'name': question.name,
'date_created': question.date_created,
'date_modified': question.date_modified
})
response.status_code = 200
return response
else:
# GET request: Retrieve a question
response = jsonify({
'id': question.id,
'name': question.name,
'date_created': question.date_created,
'date_modified': bucketlist.date_modified
})
response.status_code = 200
return response

return app
Empty file added API/app/Users/__init__.py
Empty file.
Binary file added API/app/Users/__pycache__/__init__.cpython-37.pyc
Binary file not shown.
Binary file not shown.
27 changes: 27 additions & 0 deletions API/app/Users/test_Users.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import pytest
import json
import os
import user.model



def test_new_user():

user = User('newuser@gmail.com', 'WelcometoAndela')
assert new_user.email == 'newuser@gmail.com'
assert new_user.hashed_password != 'WelcometoAndela'
assert not new_user.authenticated
assert new_user.role == 'user'


def post_json(client, url, json_dict):
return client.post(url, data=json.dumps(json_dict), content_type='application/json')

def json_of_response(response):
return json.loads(response.data.decode('utf8'))

def test_dummy(client):
response = client.get('/')
assert b'Each month, over 50 million developers come to StackOverflow-Lite to learn, share their knowledge, and build their careers.' in response.data


60 changes: 60 additions & 0 deletions API/app/Users/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@


from flask import flash, redirect, r, request, url_for, Blueprint
from flask.ext.login import login_user, login_required, logout_user

from .forms import LoginForm, RegisterForm
from project import db
from project.models import User, bcrypt



users_blueprint = Blueprint(
'users', __name__,
template_folder='templates'
)



@users_blueprint.route('/login', methods=['GET', 'POST'])
def login():
error = None
form = LoginForm(request.form)
if request.method == 'POST':
if form.validate_on_submit():
user = User.query.filter_by(name=request.form['username']).first()
if user is not None and bcrypt.check_password_hash(
user.password, request.form['password']
):
login_user(user)
flash('You have been logged in.')
return redirect(url_for('home.home'))

else:
error = 'Invalid username or password.'
return render_template('login.html', form=form, error=error)


@users_blueprint.route('/logout')
@login_required
def logout():
logout_user()
flash('You were logged out.')
return redirect(url_for('home.welcome'))


@users_blueprint.route(
'/register/', methods=['GET', 'POST'])
def register():
form = RegisterForm()
if form.validate_on_submit():
user = User(
name=form.username.data,
email=form.email.data,
password=form.password.data
)
db.session.add(user)
db.session.commit()
login_user(user)
return redirect(url_for('home.home'))
return render_template('register.html', form=form)
48 changes: 48 additions & 0 deletions API/app/run.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from flask import Flask, render_template, url_for, jsonify, request, abort, redirect


app = Flask(__name__)
app.config["SECRET_KEY"] = "17a0ff2d80017591818a5481f7e35e8b"

@app.route('/')
def index():
return render_template('index.html')

@app.route('/Login', methods=["GET","POST"])
def Login():

error = None
if request.method =="POST":
if request.form['username'] != 'admin' or request.form["password"] != 'admin':
error = "Invalid credentials. Please try again."
else:
return redirect(url_for("UserAccount"))
return render_template('Login.html', error=error)

@app.route('/SignUp',methods=["GET","POST"])
def SignUp():

form = SignUpForm()
return render_template('SignUp.html', title="SignUp", form=form)

@app.route('/Forum',methods=["GET","POST"])
def Forum():
return render_template('Forum.html')

@app.route('/UserAccount', methods=["GET","POST"])
def UserAccount():
return render_template('UserAccount.html')

@app.route('/Questions', methods=["GET","POST"])
def Questions():
return render_template('Questions.html')

@app.route('/ForumAnswers', methods=["GET","POST"])
def ForumAnswers():
return render_template('ForumAnswers.html')




if __name__ =="__main__":
app.run(debug=True)
121 changes: 121 additions & 0 deletions API/app/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import json
from datetime import datetime
from flask import request, jsonify, abort
from . import questions
from app.questions import questions


def locate(id, items):
"""This function takes 2 arguments (id : int and items : string)
To locate the item, question or user, with the identifier, id,
from the collection of items: either questions or users."""
collection = data[items]
required_item = {}
found = False
index = 0
for i in range(len(collection)):
if int(collection[i]['id']) == int(id):
required_item = collection[i]
found = True
index = i
if found:
return (required_item, index)
else:

return None


@questions.route('/api/v1/questions/', methods=['POST', 'GET'])
def get_questions():
"""This function handles request to the questions resource"""
if request.method == 'GET':
# return all questions in the db
response = jsonify(data['questions'])
response.status_code = 200
else:
# handles a POST request
# return the new question with the question id
question_id = int(data["questions"][-1]['id']) + 1
req_data = json.loads(
request.data.decode('utf-8').replace("'", '"'))
question_text = req_data['text']
asked_by = req_data['asked_by']
date = '{:%B %d, %Y}'.format(datetime.now())
new_question = {
"id": question_id,
"text": question_text,
"asked_by": asked_by,
"date": date,
"answers": []
}
data['questions'].append(new_question)
response = jsonify(new_question)
response.status_code = 201

return response


@questions.route('/api/v1/questions/<int:id>', methods=['GET', 'PUT', 'DELETE'])
def question(id, **kwargs):
"""This function, given a particular question id,
retrieves the question or edits the question"""
response = {}
# locate the question
q = locate(int(id), "questions")

if q is None:
# question not found
# return error 404
abort(404)

if request.method == 'GET':
# return the question
response = jsonify(q[0])
response.status_code = 200
elif request.method == 'PUT':
# obtain the required edit
edited_question = json.loads(request.data.decode('utf-8').replace("'", '"'))['text']
# edit the question in the data store
q[0]['text'] = edited_question
response = jsonify({
"id": id,
"text": edited_question
})
response.status_code = 200
else:
# delete the question
question_index = q[1]
del data["questions"][question_index]
response = jsonify({
"question_id": id,
"action": "deleted"})
response.status_code = 200

return response


@questions.route('/api/v1/questions/<int:id>/answers', methods=['POST'])
def answer(id, **kwargs):
""" This function allows the user to post an answer
to a particular question, given the question id """
questions = data['questions']
question = {}
answer = json.loads(request.data.decode('utf-8').replace("'", '"'))
# initialize up votes to 0
answer['up_votes'] = "0"
# locate the question
question = locate(int(id), "questions")[0]
if question:
# question is located, append answer
question['answers'].append(answer)
# return a response with the question id and the answer
response = jsonify({
"question_id": str(question['id']),
"text": answer['text'],
})
response.status_code = 201
return response
else:
# the question with the given id was not found
# return error 404
abort(404)
6 changes: 6 additions & 0 deletions API/run.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

from app import app


if __name__ == '__main__':
app.run()
Empty file added API/static/main.js
Empty file.
Loading