PostgreSQL生成RESTful神器PostgREST

当我们想要对PostgreSQL进行客户端上的操作时,我们需要从远端对数据库进行访问。这个时候PostgreSQL的神器PostgREST就可以出马了。PostgREST是一个能够帮助我们生成一系列用于操作PostgreSQL数据库的RESTful API的服务器。之前我还尝试过直接使用Nginx中的ngx_postgres模块进行数据的操作,但是实际使用下来发现非常的麻烦,并且RESTful style要求每个网址代表一种资源,在网址中不能有动词,只能有名词,而且所用的名词一般和数据库名称相同。然而,我在Nginx的使用中还并没有找到一种可以适配这种样式的方法,关于ngx_postgres这个模块,可以看一看我的这篇博客Nginx以及ngx_postgres安装以及配置 | Lucas的博客 和这一篇使用Java通过Nginx反向代理服务器操作PostgreSQL数据库 | Lucas的博客 )

PostgREST的配置

PostgREST的下载安装也非常的方便,首先我们创建一个文件夹用来放置PostgREST的安装目录。这里我选择在/opt目录下创建文件夹postgrest,然后下载压缩包到~/pacakges

sudo wget <https://github.com/begriffs/postgrest/releases/download/v0.4.1.0/postgrest-0.4.1.0-ubuntu.tar.xz>

将压缩包解压到postgrest中

cd ~/packages
sudo tar -xvf postgrest-0.4.1.0-ubuntu.tar.xz -C /opt/postgrest

然后进入postgrest目录中,解压后只有一个可执行文件postgrest,执行解压后的可执行文件。

cd /opt/postgrest
./postgrest

执行之后看到提示说明配置成功

db-uri = "postgres://user:pass@localhost:5432/dbname"
db-schema = "public"
db-anon-role = "postgres"
db-pool = 10

接下来配置配置文件,新建文件default.conf,配置文件内容

# postgrest.conf
# The standard connection URI format, documented at
# <https://www.postgresql.org/docs/current/static/libpq-connect.html#AEN45347>
db-uri       = "postgres://postgres:password@127.0.0.1:5432/dbname"

# The name of which database schema to expose to REST clients
db-schema    = "public"

# The database role to use when no client authentication is provided.
# Can (and probably should) differ from user in db-uri
db-anon-role = "postgres"

用设置好的配置文件启动postgrest

cd /opt/postgrest
sudo ./postgrest default.conf

启动之后,就会看到日志直接输出,可以通过Ctrl-C停止程序。我们可以通过调整将日志输出到日志文件,并且后台运行程序,日志文件应该保存在当前用户空间中,否则会出现权限问题。

sudo nohup postgrest default.conf>~/postgrest.log &

启动之后,我们就可以通过PostgREST进行Query或者Insertion了。

PostgREST和Nignx联合使用

虽然PostgREST能够为我们提供强大的RESTful API帮助,但是它并未提供一些安全上的保障和措施。所以,在实际应用中,我们可以搭配强大的Nginx,用Nginx反向代理PostgREST。我们在Nginx的配置文件中加入如下配置:

upstream postgrest {
     server localhost:3000;
     keepalive 64;
}

server {
		...

		location /api/ {
        	default_type  application/json;
        	proxy_hide_header Content-Location;
        	add_header Content-Location  /api/$upstream_http_content_location;
        	proxy_set_header  Connection "";
        	proxy_http_version 1.1;
        	proxy_pass http://postgrest/;
    	}

		...
}

然后就可以直接通过http://hostname/api/来对数据库进行操作

参考资料:【PostgREST 基本教程(一)】 PostgREST快速搭建 )
使用教程:官方文档

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值