gpt4 book ai didi

python - 将值从一个类/函数传递到另一个类/函数

转载 作者:行者123 更新时间:2023-12-01 08:58:52 25 4
gpt4 key购买 nike

我编写了两个类,一类用于发布付款数据,另一类用于显示带有 order_id 的付款成功消息。我正在从第一个函数发送订单 ID,我想捕获此 ID 以显示在我的付款成功模板中。

class ApiVIew(TemplateView):
template_name = 'payment.html'
def post(self,request):
r = requests.post(url='www.randomsite.com',params = {'authToken':'12345','card_no':'1234','card_cvv':'****'})
return HttpResponse(json.dumps({'response':r.json(),'status':'ok'}))

我称这个类为ajax并在那里解析,所以如果r没有给出错误,那么我将(window.location=localhost:8000/success)重定向到success- payment.html 页面。所以响应给了我一个 json 数据:

{'isSuccess': 1, 'order_id': 1cq2,}

所以我想获取这个order_id并将其传递给下面编写的另一个函数/类。

def payment_successfullView(request):
return render(request,'payment-successfull.html')

我怎样才能做到这一点?提前致谢。

最佳答案

<强>1。最简单的方法

url.py:

...
path('<str:order_id>/success/', views.payment_successfullView, name='success'),
...

浏览次数:

from django.shortcuts import redirect, reverse
class ApiVIew(TemplateView):
template_name = 'payment.html'
def post(self, request):
r = requests.post(url='www.randomsite.com',params = {'authToken':'12345','card_no':'1234','card_cvv':'****'})
if r.isSuccess:
return redirect(reverse('success', args=(r.order_id, )))
# do your stuff in case of failure here

def payment_successfullView(request, order_id):
return render(request,'payment-successfull.html', {
'order_id': order_id,
})

<强>2。另一种使用 session 的方法:

url.py:

...
path('success/', views.payment_successfullView, name='success'),
...

浏览次数:

from django.shortcuts import redirect, reverse
from django.http import HttpResponseForbidden

class ApiVIew(TemplateView):
template_name = 'payment.html'
def post(self, request):
r = requests.post(url='www.randomsite.com',params = {'authToken':'12345','card_no':'1234','card_cvv':'****'})
if r.isSuccess:
request.session['order_id'] = r.order_id # Put order id in session
return redirect(reverse('success', args=(r.order_id, )))
# do your stuff in case of failure here

def payment_successfullView(request):
if 'order_id' in request.session:
order_id = request.session['order_id'] # Get order_id from session
del request.session['order_id'] # Delete order_id from session if you no longer need it
return render(request,'payment-successfull.html', {
'order_id': order_id,
})

# order_id doesn't exists in session for some reason, eg. someone tried to open this link directly, handle that here.
return HttpResponseForbidden()

关于python - 将值从一个类/函数传递到另一个类/函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52628020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com