How to use hook in bottle?
https://pypi.python.org/pypi/bottle-session/0.4
I am trying to implement session plug in with bottle hook.
#bottle.route('/loginpage')
def loginpage():
return '''
<form action="/login" method="post">
Username: <input name="username" type="text" />
Password: <input name="password" type="password" />
<input value="Login" type="submit" />
</form>
'''
#bottle.route('/login', method='POST')
def do_login(session, rdb):
username = request.forms.get('username')
password = request.forms.get('password')
session['name'] = username
return session['name']
#bottle.route('/usernot')
def nextPage(session):
return session['name']
and below is my hook:
#hook('before_request')
def setup_request():
try:
request.session = session['name']
request.session.cookie_expires = False
response.set_cookie(session['name'], "true")
#request.session.save()
except Exception, e:
print ('setup_request--> ', e)
I am unable to access session in hook, is it possible to pass session as a parameter to hook?
You can use
request.get_cookie("bottle.session") #if you haven't changed the default cookie name ...
If you use the session beaker, the one mentioned and described in bottle recipes:
http://bottlepy.org/docs/dev/recipes.html
You can access the session in hook like this:
http_session = bottle.request.environ.get('beaker.session')
it works smoothly. Have you considered to change it?
Related
html page
{%block title%}Login page{% endblock %}
{%block content%}
<form action = '#' method="post">
<p>creds:</p>
<p><input type="number" placeholder="id" Id="id" /></p>
<p><input type="text" placeholder="nm" name="nm" /></p>
<p><input type="submit" value="submit" /></p>
</form>
{%endblock%}
app code
#app.route("/")
def home():
return render_template("login.html")
#app.route("/",methods = ["POST","GET"])
def post():
if request.method == "POST":
user = request.form['nm']
id = request.form['id']
sql = ('''INSERT INTO abc
(id, name) VALUES (?, ?)
''')
val = (id,user)
cur.execute (sql, val)
return 'Ok'
i tried using return.form.get('id') but its returning null
Can anyone please help me on this
Thanks
<p><input type="number" placeholder="id" name="id" /></p>
you have typed Id instead of name
When you use request.form["something"] you assume that this something always be part of your request, I recommend you to use request.form.get("something", False) to avoid that error. I hope this will solve your doubts.
I had exactly the same problem, but mine was with a "SelectField" , the update fields would be "None" and to avoid that I just added option value None as shown below:
<option value="None">None</option>
This fixed my problem
i am trying to processing a form in lift frame work. my form is having one checkbox and radiobuttons. how could i check whether the checkbox is checked or not and the selected radio button.the following code i used to get other elements value.
the view:
<form class="lift:MySnippet?form=post">
From:<input type="text" name="source" /><br />
To: <input type="text" name="destination" /><br />
Age: <input type="text" name = "age"/><br />
Return: <input type="checkbox" name="needreturn" value="Return Ticket" /><br />
<input type="radio" name="sex" value="male" />Male<br />
<input type="radio" name="sex" value="male" />Female<br />
<input type="submit" value="Book Ticket"/>
</form>
and MySnippet scala code is:
object MySnippet {
def render = {
var from = ""
var to = ""
var age = 0
def process() {
S.notice("in process function")
}
"name=source" #> SHtml.onSubmit(from = _) &
"name=destination" #> SHtml.onSubmit(to = _) &
"name=age" #> SHtml.onSubmit(s => asInt(s).foreach(age = _)) &
"type=submit" #> SHtml.onSubmitUnit(process)
}
}
in this how could i process the checkbox and radio button. can anyone help me...thanx in advance.
Do you need to specify the choices in your HTML? If not, the easiest way is:
Return: <input type="checkbox" name="needreturn" /><br />
Sex: <input type="radio" name="sex" />
and the CSS Transform:
val radioChoices = List("male", "female")
var sex:Box[String] = None
var needReturn:Boolean = false
"#sex" #> SHtml.radio(radioChoices, sex, (resp) => sex = Full(resp)) &
"#needreturn" #> SHtml.checkbox(needReturn, (resp) => needReturn = resp)
You could replace SHtml.radio with SHtml.ajaxRadio and SHtml.checkbox with SHtml.ajaxCheckbox if you want your selection to be sent to the server every time the value is changed, instead of when the form is submitted
I believe you can also use the SHtml.onSubmit as you do above for the checkbox and radio, but I'd have to do some testing to figure out exactly how.
With regards to the radio button, you can find some information about changing the way the label is output here if you need to: https://groups.google.com/forum/?fromgroups=#!topic/liftweb/rowpmIDbQAE
Use SHtml.checkbox, SHtml.radio
By the way, the <input>-s should be SHtml.text, I think. So, they're not buttons -- they're inputs. Don't forget to check the resulting html in the web page with firebug. (You'd see that using the current code you have input=text deleted.)
I'm very very new on HTML5 development and this question could be very silly but I've found an answer for it (or I've searched very well).
I want to send a form to a web service via post (I don't want to show all fields in URL).
I have two question:
How must I named forms fields? If I trying to send an userName I think I have to put this test as ID to the field which will held that value.
And this is because I'm so curious. Which is the post message content which is sent to web service?
This is an example that I've found searching Internet:
<FORM action="http://somesite.com/prog/adduser" method="post">
<P>
<LABEL for="firstname">First name: </LABEL>
<INPUT type="text" id="firstname"><BR>
<LABEL for="lastname">Last name: </LABEL>
<INPUT type="text" id="lastname"><BR>
<LABEL for="email">email: </LABEL>
<INPUT type="text" id="email"><BR>
<INPUT type="radio" name="sex" value="Male"> Male<BR>
<INPUT type="radio" name="sex" value="Female"> Female<BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</P>
</FORM
I think I will need those ids to get those values while processing them on web service, isn't it?
It depends, you could do a post to a page with a redirect (in .NET you would handle it this way):
<form action="http://myurl/postpage.ashx" method="post">
<input name="forename" />
<input name="surname" />
<input type="submit" value="Submit" />
</form>
And then pick this up in the server side script at postpage.ashx using:
string forename = Request["forename"];
string surname = Request["surname"];
You could also use jQuery to make an ajax call to the same page using the following:
var forename = $("input[name=\"forename\"]").val();
var surname = $("input[name=\"surname\"]").val();
$.ajax({
url: "http://myurl/postpage.ashx",
type: "POST",
async: true, // set to false if you don't mind the page pausing while waiting for response
cache: false,
dataType: "json",
data: "{ 'forename': '" + forename + "', 'surname': '" + surname + "' }",
contentType: "application/json; charset=utf-8",
success: function(data) {
// handle your successful response here
},
error: function(xhr, ajaxOptions, thrownError) {
// handle your fail response here
}
});
You would handle the post in the server side code the same way. The key thing to note here is that whatever you enter as the name attribute of your input element is what will get POSTed as a key/value pair to your receiving URL.
every web service should give you something like WSDL which normally contains specification of available fields and methods you can use. if the webservice you are connecting to have url webservice.com than try webservice.com/wsdl to get the WSDL.
Check this topic: click
Attribute "name" is the one that needs to be unique in order to pass that parameter to a Servlet (or wherever). The post method then encrypts the message and sends it to the Servlet.
<form method="post" action = "LoginServlet">
Name: <input type="text" name="userName">
Password: <input type="password" name="password">
<input type="submit" name = "Login" class="button">
</form>
In order to access that data you will do something like this in the Servlet:
String userName = request.getParameter("userName");
Let say I have a simple form with no required fields:
<form action="index.jsp" method="post">
<input type="text" name="firstName" />
<input type="text" name="lastName" />
<input type="text" name="email" />
<input type="submit" value="submit" />
</form>
I want to check if the form was submitted by checking the submit parameter (because it's always present). In PHP I can do a simple
if ( $_POST['submit'] )
but the request.getParameter("submit") doesn't seem to work.
So what's the best way to check if a form was submitted?
You need to give the input element a name. It's the element's name which get sent as request parameter name.
<input type="submit" name="submit" value="submit" />
Then you can check it as follows:
if (request.getParameter("submit") != null) {
// ...
}
You perhaps also want to check if "POST".equalsIgnoreCase(request.getMethod()) is also true.
if ("POST".equalsIgnoreCase(request.getMethod()) && request.getParameter("submit") != null) {
// ...
}
Better, however, would be to use a servlet and do the job in doPost() method.
You can try this way:-
if ("POST".equalsIgnoreCase(request.getMethod())) {
// Form was submitted.
} else {
// It may be a GET request.
}
I am running a Perl application named bitlfu.For login it is using something like Apache HTTP Basic Auth but not a form.I want to make form for the login with username and password field.
I have tried JavaScript and PHP with no results till now.
So I need help!
PS:
this kind of url works
http://user:password#host.com
I think a simple JavaScript like:
document.location='http://' + user + ':' + pass + '#mydomain.tld';
should do the work.
So basically, you have to create a form, with a user and pass field, then onsubmit, use the part of JavaScript given here:
<form method="post" onsubmit="javascript:document.location='http://' + $('login') + ':' + $('pass') + '#mydomain.tld';">
<input type="text" name="login" id="login" />
<input type="password" name="pass" id="pass" />
<input type="submit" value="ok"/>
</form>
where $() is a document.getElementById or jquery or so. I used the $() function to make the code shorter. Here is an implementation, which does not work on every browser. Again, look throw jQuery for cross browser solution.
function $(_id) { return document.getElementById(_id); }
Otherwise, you can use php and redirect the user with a header location.
php way:
<?php
if (isset($_POST['login']) && isset($_POST['password'])) { header('Location: ' . urlencode($_POST['login']) . ':' . urlencode($_POST['password']) . '#domain.tld'); }
else
{
?>
<form method="post" onsubmit="javascript:document.location='http://' + $('login') + ':' + $('pass') + '#mydomain.tld';">
<input type="text" name="login" id="login" />
<input type="password" name="pass" id="pass" />
<input type="submit" value="ok"/>
</form>
<?php
}
You can redirect the user to http://user:password#host.com with Perl, or using JavaScript. I don't know Perl so I'll show you the JS:
function submitted() {
document.location = "http://" + document.getElementById("username").value + ":" + document.getElementById("password").value + "#host.com";
}
<form onSubmit="submitted">...blablabla...</form>
This should work. The only problem is that this shows the password in the URL.
The awesome AJAX way using jQuery:
$.ajax({
'url': 'http://host.com/',
//'otherSettings': 'othervalues',
username: $("username").val(),
password: $("password").val()
},
sucess: function(result) {
alert('done');
}
});
The ultimate Perl way (I think)
$username = # somehow get username
$password = # somehow get password
use CGI;
my $query=new CGI;
print $query->redirect('http://host.com/');
The method of explicitly redirecting document.location with username#password in URL caused me some problems with Safari giving a phishing warning.
If I instead first make an AJAX request to a URL with basic auth headers added, and then redirect document.location without the username/pass in the URL then it worked better for me
Example
<script
src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g="
crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$('form').submit(function() {
$.ajax({
url: 'https://site/collaborators/',
username: $("#login").val(),
password: $("#pass").val()
}).done(function() {
$("#error_msg").html("");
document.location='https://site/collaborators/';
}).fail(function(result) {
console.error(result);
$("#error_msg").html("Error logging in: "+result.statusText);
});
return false;
});
});
</script>
<div id="error_msg" style="color: red"></div>
<form method="post">
Username:
<input type="text" name="login" id="login" />
Password:
<input type="password" name="pass" id="pass" />
<input type="submit" value="Submit"/>
</form>
Unfortunate caveat with Safari only, if you type your username and password incorrectly, then it makes another standard HTTP basic auth popup, but this is better than a big red "Phishing warning" that occurs when you make the document.location include username/pass
Chrome doesn't have duplicate popup if login credentials are incorrect though
This is a simple plug&play solution ;-). Will work for any domain (and on HTTPS too):
<script>
function submitAuthForm() {
var login = document.getElementById('login').value;
var pass = document.getElementById('pass').value;
location = location.href.replace('://', '://' + encodeURIComponent(login) + ':' + encodeURIComponent(pass) + '#');
// might be required to reload on Firefox (FF shows confirmation dialog)
setTimeout(function(){
location.reload(true);
}, 5000);
}
</script>
<form method="get" onsubmit="submitAuthForm(); return false">
<input type="text" id="login" />
<input type="password" id="pass" />
<input type="submit" value="OK" />
</form>
You can drop this in your 401 error document.
Note that return false is required so that the page is not reloaded twice.