我正在尝试使用Python在Google App Engine上运行基本应用。代码要求用户输入并验证它们。我似乎无法运行以下代码:
import webapp2
import re
import cgi
def escape_html(s):
return cgi.escape(s, quote = True)
USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
def valid_username(username):
return USER_RE.match(username)
EMAIL_RE = re.compile(r'^[\S]+@[\S]+\.[\S]+$')
def valid_email(email):
return EMAIL_RE.match(email)
PASS_RE = re.compile(r"^.{3,20}$")
def valid_pass(password):
return PASS_RE.match(password)
form = """ #form is an HTML form that asks for Username, Pass and Email.
<form method="post">
<br> <label> Username </label> <input type="text" name="username" value= %(username)s> <div style="color: red">%(error1)s</div><br>
<label> Password </label> <input type="password" name="password"> <div style="color: red">%(error3)s</div><br>
<label> Verify Password </label> <input type="password" name="verify"> <div style="color: red">%(error4)s</div> <div style="color: red">%(error5)s</div><br>
<label> Email </label> <input type="text" name="email" value= %(email)s> <div style="color: red"> %(error2)s </div><br>
<input type="submit" name="Submit Form">
</form>
"""
class MainPage(webapp2.RequestHandler):
def write_form(self,error1="",error2="",error3="",error4="" , error5="", username="",email="" ):
self.response.out.write(form %{"error1":error1, "error2":error2,"error3":error3,"error4":error4, "error5":error5,"username":escape_html(username),"email":escape_html(email)})
def get(self):
self.write_form()
def post(self):
usr_username = self.request.get("username")
usr_email = self.request.get("email")
usr_password = self.request.get("password")
usr_verify = self.request.get("verify")
error1="";error2="";error3="";error4="";error5="";
username = vaild_username(usr_username);
email = vaild_email(usr_email);
password = vaild_pass(usr_password);
verify = vaild_pass(usr_verify);
if not (sername):
error1 = "That is not a valid username"
if not (email):
error2 = "That is not a valid email"
if not (password):
error3 = "That is not a valid password"
if not (verify):
error4 = "That is not a valid verify password"
if (password != verify):
error5 = "Passwords not matching!"
self.write_form(error1, error2, error3, error4, error5, usr_username, usr_email)
if (username and password and email and verify and password==verify):
self.redirect("/thanks" )
class ThanksHandler(webapp2.RequestHandler):
def get(self):
username = self.request.get("username")
self.response.out.write("Welcome" + username)
app = webapp2.WSGIApplication([('/', MainPage),
('/thanks', ThanksHandler)],
debug=True)
我收到了一个Nameerror全球名称&#39; valid_username&#39;未定义(第62行)。这很奇怪,因为函数定义已经位于文件的顶部。我认为Python由于某种原因没有在顶部读取三个验证函数。我检查了拼写错误和缩进错误。
答案 0 :(得分:2)
您没有检查错误拼写:您的代码说:
username = vaild_username(usr_username);
“vaild”不是“有效”: - )
而且:你不需要在一行的末尾加分号。