Browse Source

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

master
Your Name 3 years ago
parent
commit
ccc5993782
  1. 263
      api.py
  2. BIN
      queermottoapi.db
  3. 2
      refused_words.py

263
api.py

@ -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", @app.teardown_appcontext
# 'timestamp': 'date here', def close_connection(exception):
# 'organization': 'tm', db = getattr(g, '_database', None)
# 'seedtext':'not for self but for all'}, if db is not None:
# {'refusal_code': "401", db.close()
# 'refusal_message': "new desires, new modes of gender, and new struggles are breaking open",
# 'timestamp': 'date here', def query_db(query, args=(), one=False):
# 'organization': 'tm', cur = get_db().execute(query, args)
# 'seedtext':'not for self but for all'} rv = cur.fetchall()
# ] cur.close()
# } return (rv[0] if rv else None) if one else rv
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)
@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 'rq' in request.args:
# If ID is provided, assign it to a variable. rqstr = str(request.args['rq'])
# If no ID is provided, display an error in the browser. if rqstr == "generate":
if 'rq' in request.args:
rqstr = str(request.args['rq']) # Generate the motto
if rqstr == "generate": api_phrase_str = ''
for i in range(len(seedTextList)):
api_phrase_str = '' # Current word in the seed phrase
for i in range(len(seedTextList)): current = seedTextList[i]
# Current word in the seed phrase # Going through the letters in the above word
current = seedTextList[i] api_phrase = []
# Going through the letters in the above word for y in range(len(current)):
api_phrase = [] testKey = str(y) + current[y]
for y in range(len(current)): # print(current[y],random.choice(toChooseFrom[testKey]))
testKey = str(y) + current[y] api_phrase.append(random.choice(toChooseFrom[testKey]))
# print(current[y],random.choice(toChooseFrom[testKey])) api_phrase_str_word = ' '.join(api_phrase)
api_phrase.append(random.choice(toChooseFrom[testKey])) api_phrase_str = api_phrase_str + '\\n' + api_phrase_str_word
api_phrase_str_word = ' '.join(api_phrase) api_phrase_str_word = ''
api_phrase_str = api_phrase_str + '\\n' + api_phrase_str_word api_phrase_str = api_phrase_str[2:]
api_phrase_str_word = ''
api_phrase_str = api_phrase_str[2:] # Check if one of the words has been refused
print(api_phrase_str) for elem in refWords:
for elem in refWords: if elem in api_phrase_str:
if elem in api_phrase: refusal_code = 400
count +=1 refusal_message = build_error_one()
# Write to the database
return jsonify(build_error_one()) with sqlite3.connect("queermottoapi.db") as con:
cur = con.cursor()
# Check the date cur.execute("INSERT INTO mottos (TIMESTAMP,SEEDTEXT,REFUSAL_CODE,REFUSAL_MESSAGE) VALUES (?,?,?,?)",(timestamp,seedText,refusal_code,refusal_message) )
moment = datetime.datetime.now() con.commit()
if (moment.month==3 and moment.day==8) or (moment.month==5 and moment.day==1) or (moment.month==7 and moment.day==20): return jsonify(refusal_message)
count +=1
return jsonify(build_error_three()) # Check the date
moment = datetime.datetime.now()
count +=1 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 == "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: 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

Binary file not shown.

2
refused_words.py

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

Loading…
Cancel
Save