0

I'm new to Python/Flask. I need to pass the dictionary in "cmz" function called "dict" to the "form" function in order to call a html template an pass the same dictionary to the page. I'm stuck because when I run it I get only a string value instead of an object.

I tried to set the '**' before the argument "params" of "form" function but it doesn't work to me.

This is my code, thanks to anyone for any advice!

@app.route('/form<params>')
def form(params):
    return render_template('index.html', result = params)

@app.route('/page/<distrib>')
def cmz(distrib):
    if distrib == "cmz":
        dict = {'aaa' : 'bbb', 'ccc' : 'ddd'}
        return redirect(url_for('form', params = dict))
  • 3
    A URL by its very nature can only pass *strings* to the backend. Flask does allow you to specify that a parameter can be an integer or float, because these are common use-cases and not complicated to implement - but you can't pass a complicated object like a dict in a URL without serialising it in some way. Which is definitely doable, but I'm curious why you would need to do this, as I can't imagine a use-case. (If for example the data comes from your database, then just pass the row ID in your URL, and use that in the appropriate view to pull the information from the db.) – Robin Zigmond Sep 08 '19 at 10:41

2 Answers2

2

You can pass the dictionary in string form (e.g. "{1:2,2:3}") and then convert it back. Luckily, there is already a well-answered question on how to do this - Convert a python dict to a string and back

The easiest one seems to be the following:

import json
json.dumps()
  • Both solutions work fine! Json and Session methods achieve the goal in dfferent ways but both are pretty good! Now I just need to give them an in-dept reading for better understend how they work. Thank you very much! – Marco Maggioni Sep 09 '19 at 07:46
0

This can be acomplished by using sessions.

You would need to import it with

from flask import session

You also need to make sure that a secret key is set by using

app.secret_key = 'a random string'

After that you can add a dictionary in the session with

dict = {'aaa' : 'bbb', 'ccc' : 'ddd'}
session['dict'] = dict

In the other route you can retrieve the dictionary by reversing that line

dict = session['dict']

If this would not be the solution to your problem, please let me know and I'll be glad to help!

  • Both solutions work fine! Json and Session methods achieve the goal in dfferent ways but both are pretty good! Now I just need to give them an in-dept reading for better understend how they work. Thank you very much! – Marco Maggioni Sep 09 '19 at 07:45