implemented sqlite3 db + added 400,404,500,counter generated errors

This commit is contained in:
Your Name 2021-01-12 14:29:39 +01:00
parent c5b3bf91ad
commit ccc5993782
3 changed files with 143 additions and 104 deletions

245
api.py
View File

@ -1,10 +1,14 @@
import flask, random, datetime, json import flask, random, datetime, json
from flask import request, jsonify from flask import request, jsonify
import sqlite3 import sqlite3
from flask import g
from multiprocessing import Value
app = flask.Flask(__name__, static_url_path='', static_folder='static') app = flask.Flask(__name__, static_url_path='', static_folder='static')
app.config["DEBUG"] = True app.config["DEBUG"] = True
counter = Value('i', 0)
DATABASE = 'queermottoapi.db'
availableWords = open('static/files/RNN_EditedText.txt', 'r', encoding='utf8') availableWords = open('static/files/RNN_EditedText.txt', 'r', encoding='utf8')
wordList = availableWords.read() wordList = availableWords.read()
wordList = wordList.split() wordList = wordList.split()
@ -55,46 +59,30 @@ def build_word_dict():
build_word_dict() build_word_dict()
# Example json file # Importing the database and turning it into dictionaries
# slogans = { def make_dicts(cursor, row):
# 'description' : 'Description here...', return dict((cursor.description[idx][0], value)
# 'source' : 'git url?', for idx, value in enumerate(row))
# 'data' : [
# {'generated_motto': "not no but fore possible particular southerner being all different be outside not find to our art black culture", def get_db():
# 'timestamp': 'date here', db = getattr(g, '_database', None)
# 'organization':'tm', if db is None:
# 'seedtext':'not for self but for all'}, db = g._database = sqlite3.connect(DATABASE)
# {'generated_motto': "not non-European not future body her sharing feel all fulfilled bring muse not face force World art black culture", # db.row_factory = make_dicts
# 'timestamp': 'date here', return db
# '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: @app.teardown_appcontext
slogans = json.load(sloganjson) def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
# slogans['data'].append( def query_db(query, args=(), one=False):
# {'refusal_code': "401", cur = get_db().execute(query, args)
# 'refusal_message': "new desires, new modes of gender, and new struggles are breaking open", rv = cur.fetchall()
# 'timestamp': 'date here', cur.close()
# 'oganization': 'tm', return (rv[0] if rv else None) if one else rv
# 'seedtext':'not for self but for all'
# }
# )
# with open('static/files/slogans.json', 'w', encoding='utf8') as sloganjson:
# json.dump(slogans, sloganjson)
@app.route('/', methods=['GET']) @app.route('/', methods=['GET'])
@ -103,88 +91,139 @@ def home():
<p>A prototype API.</p>''' <p>A prototype API.</p>'''
@app.route('/queermottoAPI/r1/refusal', methods=['GET']) @app.route('/queermottoAPI/r1/refusal', methods=['GET'])
def api_args(): def api_args():
buildDictElem = {}
buildDictElem['seedtext'] = 'not for self but for all'
moment = datetime.datetime.now() moment = datetime.datetime.now()
buildDictElem['timestamp'] = moment.__str__() timestamp = moment.__str__()
org = str(request.args['org']) orgVal = str(request.args['org'])
# buildDictElem['org']= org if orgVal == "refuse-tokenisms-tm-2021":
count = 0 org = "Transmediale"
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 = '' if 'rq' in request.args:
for i in range(len(seedTextList)): rqstr = str(request.args['rq'])
# Current word in the seed phrase if rqstr == "generate":
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()) # 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 the date # Check if one of the words has been refused
moment = datetime.datetime.now() for elem in refWords:
if (moment.month==3 and moment.day==8) or (moment.month==5 and moment.day==1) or (moment.month==7 and moment.day==20): if elem in api_phrase_str:
count +=1 refusal_code = 400
return jsonify(build_error_three()) 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)
count +=1 # 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) 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 == "all_log": elif rqstr == "success_log":
count +=1 success_slogans = query_db('SELECT * FROM mottos WHERE GENERATED_MOTTO IS NOT NULL AND GENERATED_MOTTO!="";')
return jsonify(slogans) return jsonify(success_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: else:
count = 0 moment = datetime.datetime.now()
buildDictElem['refusal_code'] = 402 timestamp = moment.__str__()
buildDictElem['refusal_message'] = build_error_three() refusal_code = 402
slogans['data'].append(buildDictElem) refusal_message = build_error_three()
with open('static/files/slogans.json', 'w', encoding='utf8') as sloganjson: # Write to the database
json.dump(slogans, sloganjson) with sqlite3.connect("queermottoapi.db") as con:
return jsonify(buildDictElem['refusal_message']) 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) @app.errorhandler(400)
def page_not_found(e): def error_fourzerozero(e):
moment = datetime.datetime.now()
return jsonify(build_error_two()) 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) @app.errorhandler(404)
def page_not_found(e): def error_fourzerofour(e):
return jsonify(build_error_two()) 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() # app.run()

BIN
queermottoapi.db Normal file

Binary file not shown.

View File

@ -1 +1 @@
refWords = ["for", "a", "national", "lillian", "christian", "nationally", "john", "father", "religion"] refWords = ["no"]