我获得了 RESTful Web 服务,可以将数据推送到另一个应用程序的远程数据库中。我需要通过将 JSON 格式的数据作为 GET/POST 参数发送到 Web 服务来调用这些服务以从 PostgreSQL DB 推送数据。是否可以从首先将数据推送到我的数据库的 PostgreSQL 函数(定期)调用这些 Web 服务,或者编写 JAVA 代码来调用这些在 PostgreSQL 数据库上运行查询的 Web 服务,并调用 Web 服务将它们传递给远程数据库。
最佳答案
使用plpython2u语言:
解决方案一:(使用 urllib2)
CREATE OR REPLACE FUNCTION public.py_pgrest(uri text, body text DEFAULT NULL::text, content_type text DEFAULT 'application/json'::text)
RETURNS text
LANGUAGE plpython2u
AS $function$
import urllib2
from urllib2 import Request, urlopen, URLError, HTTPError
req = Request(uri)
if body:
req.add_data(body)
if content_type:
req.add_header('Content-Type', content_type)
try:
data = urlopen(req)
except HTTPError as e:
return e
except URLError as e:
if hasattr(e, 'reason'):
return e.reason
elif hasattr(e, 'code'):
return e.code
else:
return e
else:
return data.read()
$function$
;
解决方案 2:(使用请求)
CREATE OR REPLACE FUNCTION public.py_pgrest(p_url text, p_method text DEFAULT 'GET'::text, p_data text DEFAULT ''::text, p_headers text DEFAULT '{"Content-Type": "application/json"}'::text)
RETURNS text
LANGUAGE plpython2u
AS $function$
import requests, json
try:
r = requests.request(method=p_method, url=p_url, data=p_data, headers=json.loads(p_headers))
except Exception as e:
return e
else:
return r.content
$function$
;
关于postgresql - 从 PostgreSQL 过程/函数调用 RESTful Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46540352/