小编典典

在Google App Engine中的redirect()函数中的页面之间传递数据

python

我正在尝试使用GAE构建一个简单的博客,并编写了以下代码(删除了与该问题无关的部分):

# LOADING THE TEMPLATE INTO THE JINJA ENVIRONMENT
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True)

# HELPER FUNCTION
def render_str(template, **params):
    t = jinja_env.get_template(template)
    return t.render(params)

# GOOGLE DATASTORE DATABASE
class Entries(db.Model):
    title = db.StringProperty(required = True)
    body = db.TextProperty(required = True)
    created = db.DateTimeProperty(auto_now_add = True)

# HANDLER FUNCTIONS
class SignUp(webapp2.RequestHandler):
    def get(self):
        self.response.write(render_str('signup.html'))

    def post(self):
        have_error = False
        username = self.request.get('username')
        password = self.request.get('password')
        verify = self.request.get('verify')
        email = self.request.get('email')

        params = dict(username = username, email = email)

        if not valid_username(username):
            params['error_username'] = "That's not a valid username."
            have_error = True

        if not valid_password(password):
            params['error_password'] = "That wasn't a valid password."
            have_error = True
        elif password != verify:
            params['error_verify'] = "Your passwords didn't match."
            have_error = True

        if not valid_email(email):
            params['error_email'] = "That's not a valid email."
            have_error = True

        pwhash = make_secure_val(password)
        self.response.headers.add_header('Set-Cookie', 'uid: %s' % str(pwhash))

        if have_error:
            self.response.write(render_str('signup.html', **params))
        else:
            self.redirect('/welcome')

class Welcome(webapp2.RequestHandler):
    def get(self):
        self.response.write(render_str('welcome.html'))

# APP HANDLERS
app = webapp2.WSGIApplication([('/', MainPage),
                            ('/newpost', NewPost),
                            ('/newpost/(\d+)', Permalink),
                            ('/signup', SignUp),
                            ('/welcome', Welcome)
                            ], debug=True)

signup.html是只是简单的形式采取的usernamepasswordpassword再次验证和可选email

make_secure_val()只是一个散列函数,它HMAC以格式返回参数字符串的散列版本argument|HMAC(argument)

因此,这是我的问题:用户注册后,我希望重定向到另一个URL
/welcome,从而使我可以使用该redirect()功能。但是我也想username在欢迎页面上打印输入到表单中的用户。我知道如何在中传递变量的唯一方法redirect()是通过传递到URL
GET。但是我不希望URL显示用户名。我想将其作为模板变量传递给in
render_str()。但是,如果我使用render_str()POST方法SignUp,URL仍将是/signup

如何将数据传递给redirect()


阅读 276

收藏
2021-01-20

共1个答案

小编典典

您可以使用webapp2会话以更加灵活和安全的方式跨多个请求共享数据,而无需将其编码为URL。

2021-01-20