|
from flask import Flask |
|
from flask import request |
|
from flask import jsonify |
|
import os |
|
import csv |
|
|
|
app = Flask(__name__) |
|
|
|
# A simple dictionary is our in-memory data store. This will only work with a |
|
# single-threaded application on a local machine. |
|
# A potentially better option could be to use the :memory: file in SQlite: |
|
# https://flask.palletsprojects.com/en/1.1.x/patterns/sqlite3/ |
|
KEY_VALUE_PAIRS = {} |
|
|
|
CSV_NAME = 'kv_pairs.csv' |
|
CSV_HEADERS = ['key', 'value'] |
|
|
|
@app.route("/") |
|
def index(): |
|
return """Welcome to my RC Application!""" |
|
|
|
|
|
@app.route("/set", methods=["GET", "POST"]) |
|
def set_kv(): |
|
"""retrieves a key-value pair from the client and stores it in memory.""" |
|
data = request.args.to_dict() |
|
if data == {}: |
|
return ( |
|
jsonify( |
|
message="Please submit a key value pair.", statusCode=400, isError=True |
|
), |
|
400, |
|
) |
|
data = {str(k): str(v) for k, v in data.items()} |
|
try: |
|
KEY_VALUE_PAIRS.update(data) |
|
write_to_csv(CSV_NAME, data) |
|
except IOError: |
|
return jsonify(message='Application error!', statusCode=500, isError=True) |
|
return ( |
|
jsonify(message="Submitted! {}".format(data), statusCode=200, isError=False,), |
|
200, |
|
) |
|
|
|
def create_if_not_exists(csv_name): |
|
if not os.path.exists(csv_name): |
|
with open(CSV_NAME, 'w', newline='') as csvfile: |
|
filewriter = csv.writer(csvfile) |
|
filewriter.writerow(CSV_HEADERS) |
|
|
|
def write_to_csv(csv_name, kv_pair): |
|
create_if_not_exists(csv_name) |
|
with open(csv_name, 'a', newline='') as csvfile: |
|
csv_rows = [ {CSV_HEADERS[0]: k, CSV_HEADERS[1]: v} for k, v in kv_pair.items()] |
|
dw = csv.DictWriter(csvfile, CSV_HEADERS, -999) |
|
for row in csv_rows: |
|
dw.writerow(row) |
|
|
|
|
|
@app.route("/get", methods=["GET"]) |
|
def get_kv(): |
|
"""retrieves a key from the client and looks for an associated value in memory.""" |
|
key = request.args.get("key") |
|
if key is None: |
|
return ( |
|
jsonify( |
|
message="Malformed request. Please submit with a 'key' arg", |
|
statusCode=400, |
|
isError=True, |
|
), |
|
400, |
|
) |
|
value = KEY_VALUE_PAIRS.get(key) |
|
if value is not None: |
|
return jsonify(message=value, statusCode=200, isError=False), 200 |
|
return ( |
|
jsonify(message="{} not found".format(value), statusCode=204, isError=False), |
|
204, |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
app.run(debug=True, port=4000) |