I want to have a GET route that will query an API to collect data, and then redirect to a POST with that data to save to the DB. For example:
我希望有一个GET路由,它将查询API以收集数据,然后重定向到具有该数据的POST以保存到数据库。例如:
get '/query/twitter/company/:name' do
get_number_of_tweets_for_day( params[:name] )
end
POST '/company/tweets/' do
company.tweets.create(:date => time_now, :count => num_tweets)
end
How do I set the parameters from the data returned by the function in the GET route, and pass them to the POST route so I can save to the DB?
如何从GET路由中的函数返回的数据中设置参数,并将它们传递给POST路由,以便保存到DB?
1 个解决方案
#1
1
Your code has two completely separate endpoints, which are called in separate API requests. You could make it a single POST request, i.e.:
您的代码有两个完全独立的端点,这些端点在单独的API请求中调用。你可以把它作为一个POST请求,即:
post '/company/:name/tweets/' do
num_tweets = get_number_of_tweets_for_day( params[:name] )
company.tweets.create(:date => time_now, :count => num_tweets)
end
As an alternative, for persisting data between subsequent requests, you would typically use sessions:
作为替代方案,为了在后续请求之间保持数据,通常使用会话:
enable :sessions
get '/query/twitter/company/:name' do
session['num_tweets'] = get_number_of_tweets_for_day( params[:name] )
end
post '/company/tweets/' do
company.tweets.create(:date => time_now, :count => session['num_tweets'])
end
A redirect is not possible from GET to POST, because browsers will keep the request method the same after a redirect. You would have to make your first route a POST too.
从GET到POST无法进行重定向,因为浏览器会在重定向后保持请求方法相同。您也必须将第一条路线设为POST。
#1
1
Your code has two completely separate endpoints, which are called in separate API requests. You could make it a single POST request, i.e.:
您的代码有两个完全独立的端点,这些端点在单独的API请求中调用。你可以把它作为一个POST请求,即:
post '/company/:name/tweets/' do
num_tweets = get_number_of_tweets_for_day( params[:name] )
company.tweets.create(:date => time_now, :count => num_tweets)
end
As an alternative, for persisting data between subsequent requests, you would typically use sessions:
作为替代方案,为了在后续请求之间保持数据,通常使用会话:
enable :sessions
get '/query/twitter/company/:name' do
session['num_tweets'] = get_number_of_tweets_for_day( params[:name] )
end
post '/company/tweets/' do
company.tweets.create(:date => time_now, :count => session['num_tweets'])
end
A redirect is not possible from GET to POST, because browsers will keep the request method the same after a redirect. You would have to make your first route a POST too.
从GET到POST无法进行重定向,因为浏览器会在重定向后保持请求方法相同。您也必须将第一条路线设为POST。