Working on Udacity homework, I found myself totally confused. Here's simplified version of my code:
import webapp2
form = '''
<h1>Signup</h1>
<form method='post'>
Username <input type='text' name='username'>%(usr)s<br>
<br>
<input type='submit'>
</form>
'''
class MainPage(webapp2.RequestHandler):
def write_form(self, usr=''):
self.response.write(form % {'usr':usr})
def get(self):
self.write_form()
def post(self):
user = self.request.get('username')
if user:
self.redirect('/welcome')
else:
self.get()
class WelcomePage(webapp2.RequestHandler):
def get(self):
user = self.request.get('username')
self.response.out.write('Welcome, %s' % user)
app = webapp2.WSGIApplication([('/', MainPage), ('/welcome', WelcomePage)], debug=True)
When I submit username, only 'Welcome,' is being displayed. What did I miss?
答案 0 :(得分:2)
在self.redirect('/welcome')
self.request.get('username')
您的class WelcomePage(webapp2.RequestHandler):
def get(self):
user = self.request.get('username')
数据丢失且未传递至:
/
因此您最终会得到空用户名,因此这是您提供的代码的预期行为。
有很多方法可以解决这个问题(取决于您的要求),但有些方法是:
您可以立即显示欢迎信息而无需重定向
而不是张贴到/welcome
,您可以直接发送到<form method='post' action='/welcome'>
(即/
),如果用户名为空,那么您将重定向回到表单上self.redirect('/welcome?username=' + user)
在重定向时将用户名作为GET参数传递,即public function rules()
{
return [
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'validateEmail'],
];
}
public function validateEmail($attribute, $params) {
if(ctype_digit($this->email)){
if(strlen($this->email)!=10)
$this->addError($attribute,'Phone number should be of 10 digits');
else{// Email validation using emailvalidator.}
}
}
您可以将用户名存储在某处,以便在请求之间保持持久性(即memcache,session / cookie,ndb等)。
答案 1 :(得分:0)
正如@Mihail Russu注意到的那样,username
在self.redirect('/welcome')
期间丢失了。最适合我的解决方案是将self.redirect('/welcome')
替换为self.redirect('/welcome?username=' + user)