如何在烧瓶中将数据从一页路由到另一页?

时间:2019-05-08 18:48:03

标签: python flask

我有一个页面index.html,该页面必须将两个值发送到main.html。我从index.html用json对象/api/session_loaddata发送了ajax请求。我将重定向功能称为main

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/main')    
def main(names):

    print('Hello-main')
    print('main', names, type(names))

    return render_template('main.html', nomens = names)

@app.route('/api/session_load', methods=['GET', 'POST'])
def session_load():
    if request.method == "POST":
        data = json.loads(request.get_data())
    global session_name
    global file_name
    session_name = data['session_name']
    file_name = data['file_name']

    print('sess', data, type(data))

    return redirect(url_for('main', names = data))

这是输出

* Restarting with stat
 * Debugger is active!
 * Debugger PIN: 147-211-412
sess {'file_name': 'sample.txt', 'session_name': 'asfds'} <class 'dict'>
127.0.0.1 - - [09/May/2019 00:04:32] "POST /api/session_load HTTP/1.1" 302 -
127.0.0.1 - - [09/May/2019 00:04:32] "GET /main?names=%7B%27file_name%27%3A+%27sample.txt%27%2C+%27session_name%27%3A+%27asfds%27%7D HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 2295, in wsgi_app
    response = self.handle_exception(e)
  File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 1741, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
TypeError: main() missing 1 required positional argument: 'names'

main.html文件具有与{{ nomens }}相同的模板。 main()的两个语句都不打印。

1 个答案:

答案 0 :(得分:0)

@app.route('/main')应该是@app.route('/main/<string:names>')。您需要告诉flask在您的路由名称之后,URL还会包含其他内容。