postgresql - 从 PostgreSQL 过程/函数调用 RESTful Web 服务

标签 postgresql rest web-services

我获得了 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/

相关文章:

jquery - 使用 jQuery 调用 Spring REST WebService

sql - 在字符串列表中搜索 super 字符串 - POSTGRES

java - 设计问题: Dynamically changing GUI -> sending implementation classes as soap attachments

python - 使用 Python 和 PostgreSQL 进行加密

c# - .net 3.5 中的 WebFaultException 类

c# - 在 ASP.NET Core 中实现 "JSON Merge Patch"- 区分 null 和未定义属性的最佳方法

rest - Gradle 脚本要在没有任何 3rd 方插件的情况下调用 REST Web 服务,有什么指示吗?

java - 将复杂类实例传递给 REST Web 服务的最佳做法是什么?

postgresql - 如何从登录角色中撤销所有组角色

ruby-on-rails - 在 Rspec 中测试物化 View