redmaster
redmaster

Reputation: 155

I'm working in Pyramid, but can't figure out how to send a POST from the server to the website, and catch it with Ajax

I can do it the other way, but now i need to send a request from the server, to avoid setting up a timer to check something every 100 milliseconds or so, instead i could just send a request FROM Pyramid to the website. So far i tried this but no luck:

The View i created to hold the request:

@view_config(route_name='request', request_method="POST")
def request(self):
    sometext = "Some random text"
    return Response(sometext)

Ajax:

function getmsg() {
    $.ajax({
        type:"GET",
        url:"/req", // Route for the View
        dataType: "text"
        success:function(result){
            alert( result );
            }
    });

The request is just simply not sent! any help would be appreciated!

Upvotes: 0

Views: 253

Answers (3)

crooksey
crooksey

Reputation: 8809

Right to clear everything up...

If you want to make an AJAX request from within a pyramid view, you will not need to use the pyramid framework code to do this, rather generic python, take a look at the requests library...

See the below question/answer on how to achieve this:

AJAX request with python requests library

As per your question, this will let you send a ajax request FROM the server (aka pyramid) to any other server.

Upvotes: 0

fat fantasma
fat fantasma

Reputation: 7613

You are sending a "GET" request from Ajax but looking for a "POST" request in pyramid. Change your Ajax type to POST or remove the request_method in your @view_config params(this will accept either posts or gets.

Upvotes: 0

Antoine Leclair
Antoine Leclair

Reputation: 18060

You can't "POST" from the server. That's not a Pyramid limitation, that's how HTTP is (a client makes a request to a server).

There are a few ways to send data from the back-end to the front-end like you want:

  • Polling: the browser sends a request every second or so. It's the simplest approach in most of the cases. Unless the app is highly "real-time", that's my go to solution.
  • WebSockets: the browser upgrades the connection from HTTP to WebSockets, then the browser can receive data from the WebSocket connection without requesting anything, as long as the connection is kept open. It works well but requires you to have a WebSocket setup (server side), so it can be involving.
  • Server Sent Events: the browser keeps the HTTP connection open and the server can send data through that connection. It's super easy in theory. In practice, the server has to be able to handle a lot of simultaneous connections, so it probably has to be an async server. I'm not sure if Pyramid supports this well in production (coupled with gunicorn maybe?).

Upvotes: 2

Related Questions