Prolog收到Json的帖子



这是我在stackerflow中的第一个问题,请耐心等待。

我正在string中构建一个简单的Prolog api,它接收json帖子,并在处理它们之后,将另一个json帖子发送回。我找到了这个代码来接收json:

handle(Request) :-
    http_read_json_dict(Request, DictIn),
    compute(DictIn, DictOut),
    reply_json(DictOut).

我假设compute是一个自定义谓词,出于测试目的,它是test(D,D)

问题是,当我尝试在swi-prolog中测试handle(Request)时,我要么得到错误消息ERROR: atom_codes/2: Arguments are not sufficiently instantiated,要么得到false。

我想我只需要在Request中传递一个json,但它不起作用。我还试着用Postman发送一篇帖子,邮件正文中有一个json文件(raw和application/json),但我收到了一个超时,嗯…是的。。。我的问题是,我应该在Request中写些什么,以便它正确地实例化它?

提前感谢,如果这是一个糟糕的问题,很抱歉,但swi-prolog文档很糟糕,我在任何地方都找不到答案。

我不太确定您是否完全理解Prolog和swi-Prolog的web框架是如何工作的。

这里有一个循序渐进的迷你教程,让你开始:

  1. 将其复制到名为myserver.pl:的文件中

    :- use_module(library(http/thread_httpd)).
    :- use_module(library(http/http_dispatch)).
    :- use_module(library(http/http_json)).
    :- http_handler(root(.),handle,[]).
    server(Port) :-
       http_server(http_dispatch,[port(Port)]).
    handle(Request) :-
       format(user_output,"I'm here~n",[]),
       http_read_json(Request, DictIn,[json_object(term)]),
       format(user_output,"Request is: ~p~n",[Request]),
       format(user_output,"DictIn is: ~p~n",[DictIn]),
       DictOut=DictIn,
       reply_json(DictOut).
    
  2. 启动swi-prolog并在主repl类型中:

    [myserver].
    

    查阅您的档案。你应该没有错误。然后启动您的服务器,比如在端口8000上:

    server(8000).
    

    你应该得到以下回复:

    % Started server at http://localhost:8000/
    
  3. 打开另一个终端并使用curl:发布一些json

    curl -H "Content-Type: application/json" -X POST -d '{"hello":"world"}' http://localhost:8000
    

    你应该得到以下回复:

    {"hello":"world"}
    

    在运行的prolog中,您应该看到以下消息:

    I'm here
    Request is: [protocol(http),peer(ip(127,0,0,1)),pool(client('httpd@8000',user:http_dispatch,<stream>(0x7facc4026b20),<stream>(0x7facc4027040))),input(<stream>(0x7facc4026b20)),method(post),request_uri(/),path(/),http_version(1-1),user_agent('curl/7.35.0'),host(localhost),port(8000),accept([media(_G841/_G842,[],1.0,[])]),content_type('application/json'),content_length(17)]
    DictIn is: json([hello=world])
    

如果对文件myserver.pl进行任何修改,只需要在prolog的repl中键入make.

Anne Ogborn的优秀教程我推荐得再多也不为过。顺便说一下,swi-prolog的文档非常好。

还有几个JSON读写器:

这些模块采用原子并通过DCG实现:
https://github.com/khueue/prolog-json/tree/master/src

此模块通过ISO流进行定向编码:
https://gist.github.com/jburse/63986bf525784d6d8cf99db132538d67#file-json_o-p

这两种方法都不需要Prolog dicts,适用于各种Prolog系统。

相关内容

最新更新