add file upload to api

This commit is contained in:
Fabian Dill 2020-10-29 01:43:23 +01:00
parent 3eca405595
commit 99dc16895e
2 changed files with 39 additions and 28 deletions

View File

@ -28,7 +28,7 @@ def mysterycheck():
if type(options) == str: if type(options) == str:
flash(options) flash(options)
else: else:
results, _ = roll_yamls(options) results, _ = roll_options(options)
return render_template("checkresult.html", results=results) return render_template("checkresult.html", results=results)
return render_template("check.html") return render_template("check.html")
@ -60,12 +60,15 @@ def get_yaml_data(file) -> Union[Dict[str, str], str]:
return options return options
def roll_yamls(options: Dict[str, Union[str, str]]) -> Tuple[Dict[str, Union[str, bool]], Dict[str, dict]]: def roll_options(options: Dict[str, Union[dict, str]]) -> Tuple[Dict[str, Union[str, bool]], Dict[str, dict]]:
results = {} results = {}
rolled_results = {} rolled_results = {}
for filename, text in options.items(): for filename, text in options.items():
try: try:
yaml_data = parse_yaml(text) if type(text) is dict:
yaml_data = text
else:
yaml_data = parse_yaml(text)
except Exception as e: except Exception as e:
results[filename] = f"Failed to parse YAML data in {filename}: {e}" results[filename] = f"Failed to parse YAML data in {filename}: {e}"
else: else:

View File

@ -13,7 +13,7 @@ import pickle
from .models import * from .models import *
from WebHostLib import app from WebHostLib import app
from .check import get_yaml_data, roll_yamls from .check import get_yaml_data, roll_options
@app.route('/generate', methods=['GET', 'POST']) @app.route('/generate', methods=['GET', 'POST'])
@ -29,7 +29,7 @@ def generate(race=False):
if type(options) == str: if type(options) == str:
flash(options) flash(options)
else: else:
results, gen_options = roll_yamls(options) results, gen_options = roll_options(options)
if any(type(result) == str for result in results.values()): if any(type(result) == str for result in results.values()):
return render_template("checkresult.html", results=results) return render_template("checkresult.html", results=results)
elif len(gen_options) > app.config["MAX_ROLL"]: elif len(gen_options) > app.config["MAX_ROLL"]:
@ -55,34 +55,40 @@ def generate(race=False):
@app.route('/api/generate', methods=['POST']) @app.route('/api/generate', methods=['POST'])
def generate_api(): def generate_api():
try: try:
options = {}
if 'file' in request.files:
file = request.files['file']
options = get_yaml_data(file)
json_data = request.get_json() json_data = request.get_json()
if json_data: if 'weights' in json_data:
# example: options = {"player1weights" : {<weightsdata>}} # example: options = {"player1weights" : {<weightsdata>}}
options = json_data["weights"] options = json_data["weights"]
if len(options) > app.config["MAX_ROLL"]: if not options:
return {"text": "Max size of multiworld exceeded", return {"text": "No options found. Expected file attachment or json weights."
"detail": app.config["MAX_ROLL"]}, 409 }, 400
race = bool(json_data["race"]) if len(options) > app.config["MAX_ROLL"]:
results, gen_options = roll_yamls(options) return {"text": "Max size of multiworld exceeded",
if any(type(result) == str for result in results.values()): "detail": app.config["MAX_ROLL"]}, 409
return {"text": str(results),
"detail": results}, 400
else: race = bool(json_data["race"])
gen = Generation( results, gen_options = roll_options(options)
options=pickle.dumps({name: vars(options) for name, options in gen_options.items()}), if any(type(result) == str for result in results.values()):
# convert to json compatible return {"text": str(results),
meta=pickle.dumps({"race": race}), state=STATE_QUEUED, "detail": results}, 400
owner=session["_id"])
commit()
return {"text" : f"Generation of seed {gen.id} started successfully.",
"detail": gen.id,
"encoded": app.url_map.converters["suuid"].to_url(gen.id),
"wait_api_url": url_for(wait_seed_api, seed=gen.id),
"url": url_for(wait_seed, seed=gen.id)}, 201
else: else:
return {"text": "POST data empty or incorrectly headered."}, 400 gen = Generation(
options=pickle.dumps({name: vars(options) for name, options in gen_options.items()}),
# convert to json compatible
meta=pickle.dumps({"race": race}), state=STATE_QUEUED,
owner=session["_id"])
commit()
return {"text": f"Generation of seed {gen.id} started successfully.",
"detail": gen.id,
"encoded": app.url_map.converters["suuid"].to_url(gen.id),
"wait_api_url": url_for(wait_seed_api, seed=gen.id),
"url": url_for(wait_seed, seed=gen.id)}, 201
except Exception as e: except Exception as e:
return {"text": "Uncaught Exception:" + str(e)}, 500 return {"text": "Uncaught Exception:" + str(e)}, 500
@ -151,12 +157,13 @@ def wait_seed(seed: UUID):
return "Generation failed, please retry." return "Generation failed, please retry."
return render_template("wait_seed.html", seed_id=seed_id) return render_template("wait_seed.html", seed_id=seed_id)
@app.route('/api/status/<suuid:seed>') @app.route('/api/status/<suuid:seed>')
def wait_seed_api(seed: UUID): def wait_seed_api(seed: UUID):
seed_id = seed seed_id = seed
seed = Seed.get(id=seed_id) seed = Seed.get(id=seed_id)
if seed: if seed:
return {"text" : "Generation done"}, 201 return {"text": "Generation done"}, 201
generation = Generation.get(id=seed_id) generation = Generation.get(id=seed_id)
if not generation: if not generation:
@ -165,6 +172,7 @@ def wait_seed_api(seed: UUID):
return {"text": "Generation failed"}, 500 return {"text": "Generation failed"}, 500
return {"text": "Generation running"}, 202 return {"text": "Generation running"}, 202
def upload_to_db(folder, owner, sid): def upload_to_db(folder, owner, sid):
patches = set() patches = set()
spoiler = "" spoiler = ""