|
| 1 | +function json_response = web_eval(headers, varargin); |
| 2 | +%WEB_EVAL: Returns a json object of the result of calling the function |
| 3 | +% |
| 4 | +% json_response = WEB_EVAL(headers); |
| 5 | +% json_response = WEB_EVAL(headers, config); |
| 6 | +% |
| 7 | +% This allows you to run any matlab code. To be used with webserver.m. |
| 8 | +% HTTP POST to /web_eval.m with the following parameters: |
| 9 | +% code: a string which contains the code to be run in the matlab session |
| 10 | +% |
| 11 | +% Should return a json object containing the result |
| 12 | +% |
| 13 | +% Based on Max Jaderberg's web_feval |
| 14 | + |
| 15 | +response.success = 'false'; |
| 16 | +field_names = fieldnames(headers.Content); |
| 17 | + |
| 18 | +% URL decode the POST data |
| 19 | +for i=1:numel(field_names) |
| 20 | + headers.Content.(field_names{i}) = urldecode(headers.Content.(field_names{i})); |
| 21 | +end |
| 22 | + |
| 23 | +response.content = ''; |
| 24 | + |
| 25 | +code_check = false; |
| 26 | +if size(field_names) |
| 27 | + if isfield(headers.Content, 'code') |
| 28 | + code_check = true; |
| 29 | + end |
| 30 | +end |
| 31 | + |
| 32 | +if ~code_check |
| 33 | + response.message = 'No code provided as POST parameter'; |
| 34 | + json_response = mat2json(response); |
| 35 | + return; |
| 36 | +end |
| 37 | + |
| 38 | +code = headers.Content.code; |
| 39 | + |
| 40 | +try |
| 41 | + % tempname is less likely to get bonked by another process. |
| 42 | + diary_file = [tempname() '_diary.txt']; |
| 43 | + diary(diary_file); |
| 44 | + evalin('base', code); |
| 45 | + diary('off'); |
| 46 | + |
| 47 | + datadir = fullfile(tempdir(),'MatlabData'); |
| 48 | + response.content.datadir = [datadir, filesep()]; |
| 49 | + mkdir(datadir); |
| 50 | + |
| 51 | + fig_files = make_figs(datadir); |
| 52 | + |
| 53 | + response.success = 'true'; |
| 54 | + response.content.figures = fig_files; |
| 55 | + |
| 56 | + % this will not work on Windows: |
| 57 | + %[ignore_status, stdout] = system(['cat ' diary_file]); |
| 58 | + % cf. http://rosettacode.org/wiki/Read_entire_file#MATLAB_.2F_Octave |
| 59 | + FID = fopen(diary_file,'r'); |
| 60 | + if (FID > 0) |
| 61 | + [stdout,count] = fread(FID, [1,inf], 'uint8=>char'); |
| 62 | + fclose(FID); |
| 63 | + response.content.stdout = stdout; |
| 64 | + else |
| 65 | + response.success = 'false'; |
| 66 | + response.content.stdout = sprintf('could not open %s for read',diary_file); |
| 67 | + end |
| 68 | + delete(diary_file) |
| 69 | +catch ME |
| 70 | + diary('off'); |
| 71 | + response.success = 'false'; |
| 72 | + response.content.stdout = ME.message; |
| 73 | +end |
| 74 | + |
| 75 | +response.content.code = code; |
| 76 | + |
| 77 | +json_response = mat2json(response); |
| 78 | + |
| 79 | +end %function |
0 commit comments