Browse Source

Strategická: Odpověď na /api je vždy JSON

master
Jiří Kalvoda 2 years ago
parent
commit
8dfb39f996
  1. 18
      server/hra/web/__init__.py
  2. 32
      server/hra/web/api.py
  3. 6
      server/hra/web/pages.py

18
server/hra/web/__init__.py

@ -19,6 +19,8 @@ import hra.config as config
import hra.web.html as html
import hra.db as db
import json
import logging
logging.basicConfig()
@ -89,7 +91,21 @@ def init_request():
app.before_request(init_request)
@app.errorhandler(werkzeug.exceptions.HTTPException)
def handle_exception(e):
path = request.path
if path.startswith('/api/'):
response = e.get_response()
response.data = json.dumps({
"status": "error",
"description": e.description,
"http-code": e.code,
"http-name": e.name,
})
response.content_type = "application/json"
return response
else:
return e
import hra.web.pages as pages
import hra.web.api

32
server/hra/web/api.py

@ -9,6 +9,17 @@ from hra.web import app, NeedLoginError
import hra.web.jinja_mac as jinja_mac
import hra.lib as lib
def json_endpoint(f):
def l(*arg, **kvarg):
x = f(*arg, **kvarg)
response = e.get_response()
response.content_type = "application/json"
response.data = json.dumps(x)
return response
l.__name__ = f.__name__
return l
def args_get(name, type, optional=False, default=None):
v = request.args.get(name)
if v is None:
@ -33,6 +44,7 @@ def get_context():
@app.route("/api/state", methods=['GET'])
@json_endpoint
def api_state():
team = get_context()
game = team.game
@ -54,15 +66,16 @@ def api_state():
"status": "too_early",
"wait": time_to_end + 1.0 if time_to_end is not None else 3.0,
})
return json.dumps({
return {
"status": "ok",
"round": state.round,
"team_id": team_id,
"time_to_response": time_to_end,
"state": game.get_logic().personalize_state(state.get_state(), team_id, state.round),
})
}
@app.route("/api/action", methods=['POST'])
@json_endpoint
def api_action():
def to_late():
return json.dumps({
@ -82,10 +95,10 @@ def api_action():
try:
warnings = game.get_logic().validate_move(state.get_state(), team_id, j, round_id)
except Exception as e:
return json.dumps({
return {
"status": "error",
"description": f"{type(e).__name__}: {e}"
})
}
db.get_session().expire_all()
game = game.lock()
@ -104,13 +117,14 @@ def api_action():
db.get_session().commit()
if warnings is not None:
return json.dumps(warnings)
return json.dumps({
return warnings
return {
"status": "ok",
})
}
@app.route("/api/step", methods=['POST'])
@json_endpoint
def api_step():
team = get_context()
game = team.game
@ -119,6 +133,6 @@ def api_step():
lib.game_step(game.game_id)
return json.dumps({
return {
"status": "ok",
})
}

6
server/hra/web/pages.py

@ -326,9 +326,9 @@ def web_org_games():
b.h2("Hry")
with b.p().table(_class="data full"):
with b.thead():
b.line().th()("Id: Jméno")
b.line().th()("Kolo")
b.line().th()("Akce")
b.line().th("Id: Jméno")
b.line().th("Kolo")
b.line().th("Akce")
for g in games:
with b.tr():
b.line().td()(g.print())

Loading…
Cancel
Save