From ccc599378230bb063d90ce7c794f4808a79989e5 Mon Sep 17 00:00:00 2001 From: Your Name Date: Tue, 12 Jan 2021 14:29:39 +0100 Subject: [PATCH] implemented sqlite3 db + added 400,404,500,counter generated errors --- api.py | 263 +++++++++++++++++++++++++++-------------------- queermottoapi.db | Bin 0 -> 20480 bytes refused_words.py | 2 +- 3 files changed, 152 insertions(+), 113 deletions(-) create mode 100644 queermottoapi.db diff --git a/api.py b/api.py index 698bfc6..cadfddb 100644 --- a/api.py +++ b/api.py @@ -1,10 +1,14 @@ import flask, random, datetime, json from flask import request, jsonify import sqlite3 +from flask import g +from multiprocessing import Value app = flask.Flask(__name__, static_url_path='', static_folder='static') app.config["DEBUG"] = True +counter = Value('i', 0) +DATABASE = 'queermottoapi.db' availableWords = open('static/files/RNN_EditedText.txt', 'r', encoding='utf8') wordList = availableWords.read() wordList = wordList.split() @@ -55,46 +59,30 @@ def build_word_dict(): build_word_dict() -# Example json file -# slogans = { -# 'description' : 'Description here...', -# 'source' : 'git url?', -# 'data' : [ -# {'generated_motto': "not no but fore possible particular southerner being all different be outside not find to our art black culture", -# 'timestamp': 'date here', -# 'organization':'tm', -# 'seedtext':'not for self but for all'}, -# {'generated_motto': "not non-European not future body her sharing feel all fulfilled bring muse not face force World art black culture", -# 'timestamp': 'date here', -# 'organization':'tm', -# 'seedtext':'not for self but for all'}, -# {'generated_motto': "neither contracts hate face coals words seriously become relationship different bourgeois turning attach feminists work participate about flirty fall", -# 'timestamp': 'date here', -# 'organization': 'tm', -# 'seedtext':'not for self but for all'}, -# {'refusal_code': "401", -# 'refusal_message': "new desires, new modes of gender, and new struggles are breaking open", -# 'timestamp': 'date here', -# 'organization': 'tm', -# 'seedtext':'not for self but for all'} -# ] -# } - - -with open('static/files/slogans.json', 'r', encoding='utf8') as sloganjson: - slogans = json.load(sloganjson) - -# slogans['data'].append( -# {'refusal_code': "401", -# 'refusal_message': "new desires, new modes of gender, and new struggles are breaking open", -# 'timestamp': 'date here', -# 'oganization': 'tm', -# 'seedtext':'not for self but for all' -# } -# ) - -# with open('static/files/slogans.json', 'w', encoding='utf8') as sloganjson: -# json.dump(slogans, sloganjson) +# Importing the database and turning it into dictionaries +def make_dicts(cursor, row): + return dict((cursor.description[idx][0], value) + for idx, value in enumerate(row)) + +def get_db(): + db = getattr(g, '_database', None) + if db is None: + db = g._database = sqlite3.connect(DATABASE) + # db.row_factory = make_dicts + return db + + +@app.teardown_appcontext +def close_connection(exception): + db = getattr(g, '_database', None) + if db is not None: + db.close() + +def query_db(query, args=(), one=False): + cur = get_db().execute(query, args) + rv = cur.fetchall() + cur.close() + return (rv[0] if rv else None) if one else rv @app.route('/', methods=['GET']) @@ -103,88 +91,139 @@ def home():

A prototype API.

''' - @app.route('/queermottoAPI/r1/refusal', methods=['GET']) def api_args(): - buildDictElem = {} - buildDictElem['seedtext'] = 'not for self but for all' moment = datetime.datetime.now() - buildDictElem['timestamp'] = moment.__str__() - org = str(request.args['org']) - # buildDictElem['org']= org - count = 0 - if count < 40: - # Check if an ID was provided as part of the URL. - # If ID is provided, assign it to a variable. - # If no ID is provided, display an error in the browser. - if 'rq' in request.args: - rqstr = str(request.args['rq']) - if rqstr == "generate": - - api_phrase_str = '' - for i in range(len(seedTextList)): - # Current word in the seed phrase - current = seedTextList[i] - # Going through the letters in the above word - api_phrase = [] - for y in range(len(current)): - testKey = str(y) + current[y] - # print(current[y],random.choice(toChooseFrom[testKey])) - api_phrase.append(random.choice(toChooseFrom[testKey])) - api_phrase_str_word = ' '.join(api_phrase) - api_phrase_str = api_phrase_str + '\\n' + api_phrase_str_word - api_phrase_str_word = '' - api_phrase_str = api_phrase_str[2:] - print(api_phrase_str) - for elem in refWords: - if elem in api_phrase: - count +=1 - - return jsonify(build_error_one()) - - # Check the date - moment = datetime.datetime.now() - if (moment.month==3 and moment.day==8) or (moment.month==5 and moment.day==1) or (moment.month==7 and moment.day==20): - count +=1 - return jsonify(build_error_three()) - - count +=1 + timestamp = moment.__str__() + orgVal = str(request.args['org']) + if orgVal == "refuse-tokenisms-tm-2021": + org = "Transmediale" + + if 'rq' in request.args: + rqstr = str(request.args['rq']) + if rqstr == "generate": + + # Generate the motto + api_phrase_str = '' + for i in range(len(seedTextList)): + # Current word in the seed phrase + current = seedTextList[i] + # Going through the letters in the above word + api_phrase = [] + for y in range(len(current)): + testKey = str(y) + current[y] + # print(current[y],random.choice(toChooseFrom[testKey])) + api_phrase.append(random.choice(toChooseFrom[testKey])) + api_phrase_str_word = ' '.join(api_phrase) + api_phrase_str = api_phrase_str + '\\n' + api_phrase_str_word + api_phrase_str_word = '' + api_phrase_str = api_phrase_str[2:] + + # Check if one of the words has been refused + for elem in refWords: + if elem in api_phrase_str: + refusal_code = 400 + refusal_message = build_error_one() + # Write to the database + with sqlite3.connect("queermottoapi.db") as con: + cur = con.cursor() + cur.execute("INSERT INTO mottos (TIMESTAMP,SEEDTEXT,REFUSAL_CODE,REFUSAL_MESSAGE) VALUES (?,?,?,?)",(timestamp,seedText,refusal_code,refusal_message) ) + con.commit() + return jsonify(refusal_message) + + # Check the date + moment = datetime.datetime.now() + if (moment.month==3 and moment.day==8) or (moment.month==5 and moment.day==1) or (moment.month==7 and moment.day==20): + refusal_code = 402 + refusal_message = build_error_three() + # Write to the database + with sqlite3.connect("queermottoapi.db") as con: + cur = con.cursor() + cur.execute("INSERT INTO mottos (TIMESTAMP,SEEDTEXT,REFUSAL_CODE,REFUSAL_MESSAGE) VALUES (?,?,?,?)",(timestamp,seedText,refusal_code,refusal_message) ) + con.commit() + return jsonify(refusal_message) + + # Check if the counter is smaller than 10 + out = counter.value + if out < 10: + with counter.get_lock(): + counter.value += 1 + out = counter.value + # Write to the database + with sqlite3.connect("queermottoapi.db") as con: + cur = con.cursor() + cur.execute("INSERT INTO mottos (GENERATED_MOTTO,TIMESTAMP,ORGANISATION,SEEDTEXT) VALUES (?,?,?,?)",(api_phrase_str,timestamp,org,seedText) ) + con.commit() return jsonify(api_phrase_str) + else: + with counter.get_lock(): + counter.value = 0 + refusal_code = 402 + refusal_message = build_error_three() + # Write to the database + with sqlite3.connect("queermottoapi.db") as con: + cur = con.cursor() + cur.execute("INSERT INTO mottos (TIMESTAMP,SEEDTEXT,REFUSAL_CODE,REFUSAL_MESSAGE) VALUES (?,?,?,?)",(timestamp,seedText,refusal_code,refusal_message) ) + con.commit() + return jsonify(refusal_message) + elif rqstr == "all_log": + all_slogans = query_db('SELECT * FROM mottos;') + return jsonify(all_slogans) + + elif rqstr == "success_log": + success_slogans = query_db('SELECT * FROM mottos WHERE GENERATED_MOTTO IS NOT NULL AND GENERATED_MOTTO!="";') + return jsonify(success_slogans) - elif rqstr == "all_log": - count +=1 - return jsonify(slogans) - - elif rqstr == "success_log": - success_slogans = [] - for call in slogans: - if "refusal_code" not in call.keys(): - success_slogans.append(call) - count +=1 - return jsonify(success_slogans) - - else: - count +=1 - return jsonify(build_error_two()) else: - count = 0 - buildDictElem['refusal_code'] = 402 - buildDictElem['refusal_message'] = build_error_three() - slogans['data'].append(buildDictElem) - with open('static/files/slogans.json', 'w', encoding='utf8') as sloganjson: - json.dump(slogans, sloganjson) - return jsonify(buildDictElem['refusal_message']) + moment = datetime.datetime.now() + timestamp = moment.__str__() + refusal_code = 402 + refusal_message = build_error_three() + # Write to the database + with sqlite3.connect("queermottoapi.db") as con: + cur = con.cursor() + cur.execute("INSERT INTO mottos (TIMESTAMP,SEEDTEXT,REFUSAL_CODE,REFUSAL_MESSAGE) VALUES (?,?,?,?)",(timestamp,seedText,refusal_code,refusal_message) ) + con.commit() + return jsonify(refusal_message) @app.errorhandler(400) -def page_not_found(e): - - return jsonify(build_error_two()) +def error_fourzerozero(e): + moment = datetime.datetime.now() + timestamp = moment.__str__() + refusal_code = 401 + refusal_message = build_error_two() + # Write to the database + with sqlite3.connect("queermottoapi.db") as con: + cur = con.cursor() + cur.execute("INSERT INTO mottos (TIMESTAMP,SEEDTEXT,REFUSAL_CODE,REFUSAL_MESSAGE) VALUES (?,?,?,?)",(timestamp,seedText,refusal_code,refusal_message) ) + con.commit() + return jsonify(refusal_message) @app.errorhandler(404) -def page_not_found(e): - return jsonify(build_error_two()) - - +def error_fourzerofour(e): + moment = datetime.datetime.now() + timestamp = moment.__str__() + refusal_code = 401 + refusal_message = build_error_two() + # Write to the database + with sqlite3.connect("queermottoapi.db") as con: + cur = con.cursor() + cur.execute("INSERT INTO mottos (TIMESTAMP,SEEDTEXT,REFUSAL_CODE,REFUSAL_MESSAGE) VALUES (?,?,?,?)",(timestamp,seedText,refusal_code,refusal_message) ) + con.commit() + return jsonify(refusal_message) + +@app.errorhandler(500) +def error_fivezerozero(e): + moment = datetime.datetime.now() + timestamp = moment.__str__() + refusal_code = 401 + refusal_message = build_error_two() + # Write to the database + with sqlite3.connect("queermottoapi.db") as con: + cur = con.cursor() + cur.execute("INSERT INTO mottos (TIMESTAMP,SEEDTEXT,REFUSAL_CODE,REFUSAL_MESSAGE) VALUES (?,?,?,?)",(timestamp,seedText,refusal_code,refusal_message) ) + con.commit() + return jsonify(refusal_message) # app.run() diff --git a/queermottoapi.db b/queermottoapi.db new file mode 100644 index 0000000000000000000000000000000000000000..6144c1652cb9dbac209677e6608f08fb2f9577ee GIT binary patch literal 20480 zcmeHOOOqQ{71sC>cl?M01VVVFdE^Bdxm#}y<-%io;uvfX*b@v?s8mb3(lpcREBY}) zVL?V4mQ+z}sNx5(X2Y6d0UN6L4QyGkA{51j?>o1+0PaepO$U2PzL#9;iG}d7$z@<$=lrl?N&hR34~2PkTMzek5BBVX-JAFJZ1bA^>cu;I5B477_1o{<-#<9mw{N|<`|#Da^V;hd z5ANRIdvvgS|Lbe7?LWM;`{3@Q-GjUP5A3zqAMNekKG^%#!P-j?_uhEx(eAx>ZtdUR zv+q7Qc>QAj3Lg7t_s(AN-ixoX!9R2Lefs|V)qj}3{BH-MI(_AV$^(@LDi2g1s60@4 zpz=WFfyx7w2PzL#9;iG}c;MWt`0Lr{xSM~j7S*nP_nDtw`OW3OTz>7+{>2|Z{l}+2 zYQ1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