Cut down and add very basic data cleaning.

This commit is contained in:
Matt
2020-05-17 22:50:34 -05:00
parent 58f96b9f51
commit 224c84f72e

67
app.py
View File

@ -1,23 +1,17 @@
#!flask/bin/python #!flask/bin/python
from flask import Flask, jsonify, abort, make_response, request from flask import Flask, jsonify, abort, make_response, request
from flask_httpauth import HTTPBasicAuth from flask_httpauth import HTTPBasicAuth
import datetime
auth = HTTPBasicAuth() auth = HTTPBasicAuth()
app = Flask(__name__) app = Flask(__name__)
tasks = [ statuses = [
{ {
'id': 1, 'title': 'curl -u matt:python -i http://localhost:5000/log/api/v1.0/new?title="example_status_no_spaces"',
'title': u'Buy groceries', 'timestamp': datetime.datetime.now().timestamp(),
'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', 'timestamp_readable': datetime.datetime.now()
'done': False
},
{
'id': 2,
'title': u'Learn Python',
'description': u'Need to find a good Python tutorial on the web',
'done': False
} }
] ]
@ -30,35 +24,34 @@ def get_password(username):
@auth.error_handler @auth.error_handler
def unauthorized(): def unauthorized():
return make_response(jsonify({'error': 'Unauthorized access'}), 403) return make_response(jsonify({'error': 'Unauthorized access'}), 403)
@app.route('/')
def index():
return "Hello, World!"
@app.route('/todo/api/v1.0/new', methods=['POST']) @app.route('/new', methods=['POST', 'GET'])
@auth.login_required @auth.login_required
def create_task(): def create_status():
if not request.json or not 'title' in request.json: # At least try to clean up user-submitted data
abort(400) # https://stackoverflow.com/a/7406369/2152245
task = { keepcharacters = (' ','.','_')
'id': tasks[-1]['id'] + 1, safer_title = "".join(c for c in request.args.get("title") if c.isalnum() or c in keepcharacters).rstrip()
'title': request.json['title'], # Limit the length
'description': request.json.get('description', ""), safer_title = safer_title[:256]
'done': False
}
tasks.append(task)
return jsonify({'task': task}), 201
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET']) status = {
def get_task(task_id): 'title': safer_title,
task = [task for task in tasks if task['id'] == task_id] 'timestamp': datetime.datetime.now().timestamp(),
if len(task) == 0: 'timestamp_readable': datetime.datetime.now()
abort(404) }
return jsonify({'task': task[0]}) # Add status to list
statuses.append(status)
# If list is too big, delete the first item
# Simple way to prevent someone filling up memory
if len(statuses) > 1000:
statuses.pop(0)
return jsonify({'status': status}), 201
@app.route('/', methods=['GET'])
def get_statuses():
return jsonify({'statuses': statuses[::-1]})
@app.errorhandler(404) @app.errorhandler(404)
def not_found(error): def not_found(error):