Redirect via HTTPFound parameters not being passed - redirect

I have a Pyramid app using URL disptach. I have a route '/delete' that removes a record from the database and redirects to a view. When the redirect happens, I want the view to reload on the same page. I'm using webhelpers.paginate for pagination. The problem is, when the redirection happens, the parameters are not passed.
The delete route:
#view_config(route_name='delete')
def delete(request):
# Get the current page, the page title, and the id of the record to delete
current_page = int(request.params.get('page', 1))
# Database transactions
...
# Reload the view
url = request.route_url(route_name='records', app_name='BLAH', userid='BLAH', page=current_page)
return HTTPFound(location=url)
The records view:
#view_config(route_name='records', renderer='records.jinja2')
def records(request):
# Get the current page
current_page = int(request.params.get('page', 1))
When the records view is loaded, the parameters are not passed and the default value of '1' is set for the current_page. The values of "BLAH" for the app_name and user_id aren't passed either.
One thing I did notice is that it seems like the view is loaded twice but I don't know how to confirm that. I think the page is loaded twice because I see two calls to the database after the redirect.
What am I missing? Thanks.

What's the url when your print url in delete route and what it the route records definition?
If your want a GET Request, you shoud try keyword argument _query
url = request.route_url(name='records', _query=(('page', current_page),))

Related

pyTelegramBotAPI pagination: how to pass a data between pages in a message

I have a Telegram bot for the forwarding of database requests. It returns long messages, so,
I use pagination from python-telegram-bot-pagination, for splitting this message to blocks. But I can't find a way to split the message to blocks effectively.
Now it looks like this:
by user request, the #bot.message_handler runs send_info_to_user function.
send_info_to_user calls the some_long_operation and gets the whole dataset as a result.
send_info_to_user gets a slice from some_long_operation result and sends it as a message for user
in case of using pagination inline buttons, the #bot.callback_query_handler will call send_info_to_user again
it re-calls the some_long_operation and gets the whole dataset again, just for another slice from the result and edit the content of the previous message.
# a time-consumable function
def some_long_operation(user_id):
return [f'some_text{i}\n{user_id}' for i in range(40)]
# send info to user by pages
def send_info_to_user(message, user_id, isCallback=False, page=1):
result = some_long_operation(user_id)
paginator = InlineKeyboardPaginator(
len(answer),
current_page=page,
data_pattern=f'{user_id}#'+'items#{page}' # wrap user_id for callback
)
if isCallback:
bot.edit_message_text(message.chat.id, result[page-1], message.message_id, paginator.markup)
else:
bot.send_message(message.chat.id, result[page-1],paginator.markup)
#bot.message_handler(content_types='text')
def message_reply(message):
send_info_to_user(message, message.from_user.id)
# parse callback from inline buttons
#bot.callback_query_handler(func=lambda call: call.data.split('#')[1]=='items')
def items_page_callback(call):
page = int(call.data.split('#')[2])
user_id = call.data.split('#')[0] # unwrap user_id
get_items(call.message, user_id, True, page)
Obviously, re-call of some_long_operation every time and using a slice of it isn't a good solution. But I can't find a way to pass the data between pages in a message.
The result of some_long_operation is user-specific and changes in time, so, store it anywhere isn't a good idea.
As I think, the some_long_operation should be called once, the result of it should be available as a slices for different pages of the message.

Play Framework sending POST request data to GET

How would I send request data from a POST request to a GET request using Scala Play?(Using Play Framework 2.1.1)
My goal is to have a single page "Reports" that works like this: The report is a GET request, so if needed you could bookmark this report. The report consists of a table of models, and each model row has a delete button at the end. I want to click the delete button, have it post the id to my controller then reload the page with the reports filter parameters still on.
Currently I have the delete button just adding to the get, which works correctly but the remove=id parameter stays in the request/address bar. Therefore it tries to delete this model every time the page is reloaded. What I would like to do is have this form POST and then remove the model, then send all the request parameters other than remove to a GET request.
I would rather do this without javascript/AJAX.
You could reconstruct a URL through using queryString and path from the request object. Then redirect that back (without the delete parameter)
How to get query string parameters in java play framework?
Or if you have the call setup in the routes file to parse out, use the reverse route minus the delete parameter.
Play Framework - Redirect with params
http://www.mariussoutier.com/blog/2012/12/10/playframework-routes-part-1-basics/
def index() = Action { request =>
import play.api.Play.current
println(request.queryString)
val allWithoutDel = request.queryString - "del" //del is the query parameter
println(allWithoutDel)
val url = request.path + // fold or map the allWithoutDel down to a URL string again
redirect(url)
}

Redirect to referer after a POST Request

I have a web application in Play. The web application consists of several pages. In every page there is a small flag that enables the user to change the language (locale) from german to english and back.
I handle this with a redirect to referer:
def referer(implicit request: Request[AnyContent]) =
request.headers.get(REFERER).getOrElse(mainUrl)
def locale(l: String) = Authenticated { user =>
implicit request =>
Redirect(referer).withCookies(Cookie(LANG, if (l == "de" || l == "en") l else "de"))
}
It is working fine. Well, at least for GET requests.
I have a specific page where the user has to input data in a form. This form is then POSTed to the server. Were errors found, the form is displayed again with the error messages, as usual. Now, if the user wants to change the language (by clicking on the flag), the redirect to referer does not work, because it tries to use a GET request, and Play complains that a GET route does not exist for this method (which is true).
I am solving this by caching the form and defining another method where the form is taken from the cache:
# User data is POSTed to the server
POST /create/insert controllers.MyCreate.insert()
# After a redirect the cached form is displayed again
GET /create/insert controllers.MyCreate.insertGet()
It works, but I don't like this solution. It does not seem normal to have to create another entry in the routes and another method just to adress this problem. I would need to add this hack for every POST route in my application!
Is there a more elegant solution to this?
You could change it into something like this (untested):
def changeLang(lang:String, returnUri:String) = Action {
Redirect(returnUri)
.withCookies(Cookie(LANG, if (lang == "de" || lang == "en") lang else "de"))
}
In you template you would output the route to changeLang in the link, you can get the uri via the request
#routes.Application.changeLang("en", request.uri).url
I suggest you make request implicit in your action and define it as implicit in your template so you don't need to pass it on to each template.
// in the controller
def myUrl = Action { implicit request =>
Ok(views.html.myTemplate("something"))
}
// in the template
#(title:String)(implicit request:play.api.mvc.RequestHeader)
Edit
As for the POST requests, it common (for these types of framework) to have POST requests simple handle stuff and then redirect to another page. The usual flow is like this:
Form submits to a handler
Handler does something with the form information
Handler redirects to a page
An example:
// Hooked up to a GET route
def edit(id:Long) = Action {
// render the view with a form that displays the element with given id
// if the flash scope contains validation information, use that in display
}
// Hooked up to a POST route
def editHandler = Action {
// validate the form
// if validation succeeds
// persist the object
// redirect to edit
// else
// put the form information into the flash scope
// put any validation messages into the flash scope
// redirect to edit
}
If you do not want to use this flow you need to have both a GET and POST route anyway. The user might do a page reload on the resulting page.

Symfony2: Redirect to requested path

I want to redirect the user back to the path from which he started the request.
Example:
/profile
/profile/edit
/profile
OR:
/products
/profile/edit
/products
What do I have to set for this redirection mode?
Inside your controller for /profile/edit you can capture the page they came from with $request->headers->get('referer').
If /profile/edit is a page with a single form, I'd probably just add a hidden field that says where the redirect should go.
public function editAction(Request $request)
{
// If you have a POST value coming from the user, it will be used, otherwise
// assume this is the first time they landed on the page and grab the current
// referer. With this method it doesn't matter how many times they submit the form
// you won't accidentally overwrite the referer URL with /profile/edit. That could
// lead to a confusing loop.
$referer = $request->request->get('referer', $request->headers->get('referer'));
if ($formIsSaved)
{
return new RedirectResponse($referer)
}
return array(
// Your template should include a hidden field in the form that returns this.
'referer' => $referer,
);
}
You could pass a redirect path as a GET parameter — say, redirectTo — to the edit page and after the edit process is complete, redirect to that path.
return new RedirectResponse($request->query->get('redirectTo');
You could make it more robust by checking whether or not that parameter is provided, and if it isn't, redirect to some sort of a default path.

redirect forms with url values in zend

I have a page of the format www.test.com/policy-info/
which has a form that takes you to another page www.test.com/payment-info.
Now I am redirecting the page from www.test.com/payment-info to www.test.com/policy-info based on the some values obtained from the form. How do I redirect with certain values in the url.
the filename is policy-info.phtml.
Is this the only way to redirect?
$this->redirect(www.test.com/policy-info/index.phhtml&count=2);
You can use this:
$this->_helper->redirector('action', 'controller', 'module', array('param1'=>'value1', 'param2'=>'value2'));
in your case:
$this->_helper->redirector('index', 'policy-info', 'default',array('param1'=>'value1', 'param2'=>'value2'));
I always use $this->_redirect(...) and that works fine:
$this->_redirect('/module/controller/action/param1/value1/param2/value2');
This may be a case where _forward() may be the best choice.
_forward($action, $controller = null, $module = null, array $params = null): perform another action. If called in preDispatch(), the
currently requested action will be skipped in favor of the new one.
Otherwise, after the current action is processed, the action requested
in _forward() will be executed.
also It looks like you may be using named/defined routes, if that is true gotoRoute maybe useful as well Redirector Helper:
$this->_helper->getHelper('Redirector')->gotoRoute(array('param'=>'value'), 'routeName');