简体   繁体   中英

How do I send a variable from one function to another function?

Here is an example of a function that I want to be able to pass one variable to the other.

def foo(request):
    if request.method == "POST":
        unique_id = request.POST.get('per_id','')
        baz = get_object_or_404(Name, pk=unique_id)
        return render(request, 'details/guy.html', {'baz': baz})
    return render(request, 'details/person.html')

def bar(request):
    if request.method == "POST":
        baz = get_object_or_404(Name, pk=unique_id)
        return render(request, 'details/guy.html', {'baz': baz})
    return render(request, 'details/guy.html')

The problem is this:

local variable 'unique_id' referenced before assignment

So, how do I get this variable to feed from the foo(request) function to the bar(request) function?

I know I can use cPickle, but the amount of traffic this website will be getting will almost certainly cause the cPickle object to be mixed up with another person.

Session Variable should be used sparsely.

def foo(request):
    if request.method == "POST":
        unique_id = request.POST.get('per_id','')
        request.session["unique_id"] = unique_id
        baz = get_object_or_404(Name, pk=unique_id)
        return render(request, 'details/guy.html', {'baz': baz})
    return render(request, 'details/person.html')

def bar(request):
    if request.method == "POST":
        baz = get_object_or_404(Name, pk=request.session["unique_id"])
        del request.session["unique_id"]
        return render(request, 'details/guy.html', {'baz': baz})
    return render(request, 'details/guy.html')

I would not recommend but one can use global variable too.

unique_id = None

def foo(request):
    global unique_id
    unique_id = 10

def bar(request):
    print unique_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM