import requests
import json
from subprocess import Popen, PIPE
import tempfile
import os

config = {}
with open ('../config/conversion.json') as fp:
  config = json.load(fp)


def to_cml(inchi):
  request = requests.get('%s/service/chemical/cjson/?q=inchi~eq~%s' % (config['baseUrl'], inchi))

  if request.status_code == 200:
    cjson = request.json();
  else:
    return None

  print cjson

  # Call convertion routine
  p = Popen([config['cjsonToCmlPath']], stdin=PIPE, stdout=PIPE, stderr=PIPE)
  stdout, stderr = p.communicate(json.dumps(cjson['results'][0]))

  fd, path = tempfile.mkstemp(suffix='.cml')

  with open(path, 'w') as fp:
    fp.write(str(stdout))

  os.close(fd)

  return path


@@ -81,16 +81,27 @@
 mport os
+%0Aimport sys
 %0A%0Aconfig
@@ -375,34 +375,98 @@
     
-return None%0A%0A  print cjs
+print %3E%3E sys.stderr, %22Unable to access REST API: %25s%22 %25 request.status_code%0A    return N
 on
+e
 %0A%0A  

Add log statement if REST API can't be accessed