spring调Python实时接口

@RequestMapping(value="ask")
    @ResponseBody
    public JSONObject queryJ(@RequestParam("company_id") String company_id ,
    	   HttpServletRequest request){
    	String json = ""  ; 
		try {
			Process pr = Runtime.getRuntime().exec("python "  + _getPath(request, "test.py ") + company_id) ;
			BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream() , "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				json += line ;
			}
			in.close();
			pr.waitFor();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		JSONObject jo = JSONObject.parseObject(json) ;
		System.out.println(jo.getLong("company_id")) ;
		System.out.println(jo.getString("organization_code")) ;
		return jo ;
    }
    
	private String _getPath(HttpServletRequest request , String pyFileName){
		String needDbPath = request.getSession().getServletContext().getRealPath("/");
		needDbPath += "pythonFiles"+ File.separator +pyFileName ;
		return needDbPath ;
	}


#coding=utf-8
import psycopg2
import sys
import demjson
reload(sys)
sys.setdefaultencoding('utf8')

def gao():
   company_id = sys.argv[1] ;
   conn = psycopg2.connect(database="", user="", password="", host="", port="") ;
   cur = conn.cursor() ;
   cur.execute("select company_id , organization_code  , company_full_name  from ebd_coding_company_name where company_id =  " + company_id ) ;
   rows = cur.fetchall()[0] ;
   company_id =  rows[0]  ;
   organization_code = rows[1]   ;
   company_full_name =  rows[2]
   conn.close() ;
   data = {}
   data["company_id"] = company_id
   data["organization_code"] = organization_code
   return  demjson.encode(data)


if __name__ == '__main__':
   print gao()




 
  

{"company_id":20,"organization_code":"675031462"}





你可能感兴趣的:(工作足迹)