Browse Source

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

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

209
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,24 +91,19 @@ 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: if 'rq' in request.args:
rqstr = str(request.args['rq']) rqstr = str(request.args['rq'])
if rqstr == "generate": if rqstr == "generate":
# Generate the motto
api_phrase_str = '' api_phrase_str = ''
for i in range(len(seedTextList)): for i in range(len(seedTextList)):
# Current word in the seed phrase # Current word in the seed phrase
@ -135,56 +118,112 @@ def api_args():
api_phrase_str = api_phrase_str + '\\n' + api_phrase_str_word api_phrase_str = api_phrase_str + '\\n' + api_phrase_str_word
api_phrase_str_word = '' api_phrase_str_word = ''
api_phrase_str = api_phrase_str[2:] 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 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 # Check the date
moment = datetime.datetime.now() 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): 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 refusal_code = 402
return jsonify(build_error_three()) refusal_message = build_error_three()
# Write to the database
count +=1 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": elif rqstr == "all_log":
count +=1 all_slogans = query_db('SELECT * FROM mottos;')
return jsonify(slogans) return jsonify(all_slogans)
elif rqstr == "success_log": elif rqstr == "success_log":
success_slogans = [] success_slogans = query_db('SELECT * FROM mottos WHERE GENERATED_MOTTO IS NOT NULL AND GENERATED_MOTTO!="";')
for call in slogans:
if "refusal_code" not in call.keys():
success_slogans.append(call)
count +=1
return jsonify(success_slogans) return jsonify(success_slogans)
else: else:
count +=1 moment = datetime.datetime.now()
return jsonify(build_error_two()) timestamp = moment.__str__()
else: refusal_code = 402
count = 0 refusal_message = build_error_three()
buildDictElem['refusal_code'] = 402 # Write to the database
buildDictElem['refusal_message'] = build_error_three() with sqlite3.connect("queermottoapi.db") as con:
slogans['data'].append(buildDictElem) cur = con.cursor()
with open('static/files/slogans.json', 'w', encoding='utf8') as sloganjson: cur.execute("INSERT INTO mottos (TIMESTAMP,SEEDTEXT,REFUSAL_CODE,REFUSAL_MESSAGE) VALUES (?,?,?,?)",(timestamp,seedText,refusal_code,refusal_message) )
json.dump(slogans, sloganjson) con.commit()
return jsonify(buildDictElem['refusal_message']) 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