9.1 Single-call synchronous¶
This tutorial demonstrates the simplest synchronous OptServer API where the problem is submitted and optimzied in a single call.
Assuming that an HTTP/HTTPS connection to the OptServer was established, we submit a problem using submit+solve. The file format is passed in the Content-Type
header and the requested solution format in the Accept
header.
# POST problem data
submit = s.post(URL + "/api/v1/submit+solve",
data = probdata,
headers = { "Content-Type" : intype, "Accept": outtype },
verify = verify )
The request will return when optimization terminates. If there were no errors, the status codes are available in the headers and the solution in the body of the response.
if submit.status_code == 200:
if outtype in ["application/json", "application/x-mosek-jtask"]:
solution = json.loads(submit.text)
else:
solution = submit.text
token = submit.headers['X-Mosek-Job-Token']
res = submit.headers['X-Mosek-Res-Code']
trm = submit.headers['X-Mosek-Trm-Code']
It is also possible to retrieve the log from the solver (log) if we remembered the job token returned by the first call. Otherwise the token is not necessary.
log = s.get(URL + "/api/v1/log",
headers = { "X-Mosek-Job-Token" : token },
verify = verify )
print(log.text)
The full example is shown below.
# Create a connection
with requests.Session() as s:
with open(infile,'rb') as probdata:
# POST problem data
submit = s.post(URL + "/api/v1/submit+solve",
data = probdata,
headers = { "Content-Type" : intype, "Accept": outtype },
verify = verify )
if submit.status_code == 200:
if outtype in ["application/json", "application/x-mosek-jtask"]:
solution = json.loads(submit.text)
else:
solution = submit.text
token = submit.headers['X-Mosek-Job-Token']
res = submit.headers['X-Mosek-Res-Code']
trm = submit.headers['X-Mosek-Trm-Code']
## Obtain the solver log output
log = s.get(URL + "/api/v1/log",
headers = { "X-Mosek-Job-Token" : token },
verify = verify )
print(log.text)
print(f"Solution: {solution}")
print(f"Response code: {res}")
print(f"Termination code: {trm}")
else:
# In case of error in the first submission
print(f"Unexpected status {submit.status_code}")
print(f"Response: {submit.text}")
print(f"Headers: {submit.headers}")