S_S*_*S_S 7 postgresql rest web-services
我已经获得了RESTful Web服务,可以将数据推送到另一个应用程序的远程数据库中。我需要调用这些服务以通过将JSON格式的数据作为GET / POST参数发送到Web服务来从PostgreSQL DB推送数据。是否可以从PostgreSQL函数(周期性地)首先调用这些Web服务,这些函数首先将数据推送到我的数据库中,或者编写JAVA代码来调用这些对PostgreSQL数据库运行查询的Web服务,然后调用Web服务将它们传递给远程数据库。
使用plpython2u语言:
解决方案1:(使用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$
;
Run Code Online (Sandbox Code Playgroud)
解决方案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$
;
Run Code Online (Sandbox Code Playgroud)
是的,虽然不是直接来自Postgresql本身,但有可能。我不了解Java,但是最快的方法是plperlu
与REST::Client
包一起使用,例如:
CREATE OR REPLACE FUNCTION restful.put(auri character varying, ajson_text text)
RETURNS text
LANGUAGE plperlu
SECURITY DEFINER
AS $function$
use REST::Client;
use Encode qw(encode);
my $client = REST::Client->new();
$client->getUseragent()->proxy( 'https', 'http://some-proxy/' ); # use for proxy authentication
$client->addHeader('Content-Type', 'application/json'); # headers
$client->POST( $_[0], encode('UTF-8', $_[1])); # encoding
return $client->responseContent();
$function$
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6474 次 |
最近记录: |