implemented sqlite3 db + added 400,404,500,counter generated errors
This commit is contained in:
parent
c5b3bf91ad
commit
ccc5993782
245
api.py
245
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'}
|
||||
# ]
|
||||
# }
|
||||
# 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
|
||||
|
||||
|
||||
with open('static/files/slogans.json', 'r', encoding='utf8') as sloganjson:
|
||||
slogans = json.load(sloganjson)
|
||||
@app.teardown_appcontext
|
||||
def close_connection(exception):
|
||||
db = getattr(g, '_database', None)
|
||||
if db is not None:
|
||||
db.close()
|
||||
|
||||
# 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)
|
||||
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():
|
||||
<p>A prototype API.</p>'''
|
||||
|
||||
|
||||
|
||||
@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":
|
||||
timestamp = moment.__str__()
|
||||
orgVal = str(request.args['org'])
|
||||
if orgVal == "refuse-tokenisms-tm-2021":
|
||||
org = "Transmediale"
|
||||
|
||||
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
|
||||
if 'rq' in request.args:
|
||||
rqstr = str(request.args['rq'])
|
||||
if rqstr == "generate":
|
||||
|
||||
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
|
||||
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())
|
||||
# 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)
|
||||
|
||||
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)
|
||||
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":
|
||||
count +=1
|
||||
return jsonify(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 == "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()
|
||||
|
BIN
queermottoapi.db
Normal file
BIN
queermottoapi.db
Normal file
Binary file not shown.
@ -1 +1 @@
|
||||
refWords = ["for", "a", "national", "lillian", "christian", "nationally", "john", "father", "religion"]
|
||||
refWords = ["no"]
|
||||
|
Loading…
Reference in New Issue
Block a user