python - 将 Stripe 与 Flask 集成时,如何防止表单提交到服务器?

标签 python flask forms stripe-payments

我一直在关注 Stripe 的教程,使用他们的 API 创建我自己的表单。长话短说,当提交表单时,会发生一些 Javascript 将数据发送到他们的服务器,然后附加 stripeToken输入字段。然后再次提交表单,我的 Flask 应用程序应该读取这个新表单字段的值。但是,当我尝试运行我的代码时,它会产生 500 Internal Server Error,我认为这是因为 Flask 正在立即寻找表单 stripeToken ,第一次检查时不存在。是否有 Javascript 或 Python 我可以添加到不调用 request.form['stripeToken']直到Stripe添加它之后?

这是我的相关 HTML:

<head>
    <title>Settings</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://js.stripe.com/v1/"></script>
    <script type="text/javascript">
    // This identifies your website in the createToken call below
    Stripe.setPublishableKey('STRIPE_TEST_KEY');

    var stripeResponseHandler = function(status, response) {
      var $form = $('#payment-form');

      if (response.error) {
        // Show the errors on the form
        $form.find('.payment-errors').text(response.error.message);
        $form.find('button').prop('disabled', false);
      } else {
        // token contains id, last4, and card type
        var token = response.id;
        // Insert the token into the form so it gets submitted to the server
        $form.append($('<input type="hidden" name="stripeToken" id="stripeToken" />').val(token));
        // and re-submit
        $form.get(0).submit();
      }
    };

    jQuery(function($) {
      $('#payment-form').submit(function(e) {
        var $form = $(this);

        // Disable the submit button to prevent repeated clicks
        $form.find('button').prop('disabled', true);

        Stripe.createToken($form, stripeResponseHandler);

        // Prevent the form from submitting with the default action
        return false;
      });
    });
  </script>
</head>

<body>
    <div id="payments">
        <h1>Add a credit card</h1>
        <form action="{{ url_for('stats') }}" method="POST" id="payment-form">

这是Python:
@app.route('/stats', methods=['GET', 'POST'])
def stats():
#if signed in as user       
if session['signed-in-accttype'] == 'u':
    u=User.query.get(session['signed-in-id'])
    if request.method == 'POST': 
            stripe.api_key = "STRIPE_TEST_KEY"
            token = request.form['stripeToken']

        customer = stripe.Customer.create(
            card=token,
            description=u.uemail
            )
        #update stripe id
        u.ustripe_id = customer.id
        db.session.commit()
        return redirect(url_for('stats'))       
    return render_template('settings.html', u=u)    

和日志:
2013-04-23T01:57:39.590458+00:00 app[web.1]: 10.44.13.218 - - [2013-04-23 01:57:39] "GET /stats HTTP/1.1" 200 2348 0.014429
2013-04-23T01:57:39.590171+00:00 heroku[router]: at=info method=GET path=/stats host=ancient-oasis-5770.herokuapp.com fwd="99.110.189.136" dyno=web.1 connect=3ms service=19ms status=200 bytes=2230
2013-04-23T01:57:39.804162+00:00 heroku[router]: at=info method=GET path=/favicon.ico host=ancient-oasis-5770.herokuapp.com fwd="99.110.189.136" dyno=web.1 connect=1ms service=4ms status=404 bytes=238
2013-04-23T01:57:39.808201+00:00 app[web.1]: 10.127.113.186 - - [2013-04-23 01:57:39] "GET /favicon.ico HTTP/1.1" 404 347 0.000610
2013-04-23T01:57:54.934252+00:00 heroku[router]: at=info method=POST path=/stats host=ancient-oasis-5770.herokuapp.com fwd="99.110.189.136" dyno=web.1 connect=1ms service=24ms status=500 bytes=291
2013-04-23T01:57:54.931497+00:00 app[web.1]: 10.92.74.166 - - [2013-04-23 01:57:54] "POST /stats HTTP/1.1" 500 412 0.020936
2013-04-23T01:57:55.133776+00:00 app[web.1]: 10.44.58.92 - - [2013-04-23 01:57:55] "GET /favicon.ico HTTP/1.1" 404 347 0.000603
2013-04-23T01:57:55.137417+00:00 heroku[router]: at=info method=GET path=/favicon.ico host=ancient-oasis-5770.herokuapp.com fwd="99.110.189.136" dyno=web.1 connect=24ms service=43ms status=404 bytes=238
2013-04-23T01:57:58.710721+00:00 heroku[router]: at=info method=GET path=/stats host=ancient-oasis-5770.herokuapp.com fwd="99.110.189.136" dyno=web.1 connect=1ms service=15ms status=200 bytes=2230
2013-04-23T01:57:58.714328+00:00 app[web.1]: 10.44.45.210 - - [2013-04-23 01:57:58] "GET /stats HTTP/1.1" 200 2348 0.012623
2013-04-23T01:57:58.826291+00:00 heroku[router]: at=info method=GET path=/favicon.ico host=ancient-oasis-5770.herokuapp.com fwd="99.110.189.136" dyno=web.1 connect=1ms service=3ms status=404 bytes=238
2013-04-23T01:57:58.827469+00:00 app[web.1]: 10.44.13.218 - - [2013-04-23 01:57:58] "GET /favicon.ico HTTP/1.1" 404 347 0.000772

更新:这是在本地运行的回溯)
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1701, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1689, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1687, in wsgi_app
    response = self.full_dispatch_request()
  File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1360, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1358, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1344, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/Zach/Desktop/t/t.py", line 20, in stats
    stripe.api_key = "STRIPE_TEST_KEY"
NameError: global name 'stripe' is not defined
127.0.0.1 - - [22/Apr/2013 22:11:03] "GET /stats?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [22/Apr/2013 22:11:03] "GET /stats?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
127.0.0.1 - - [22/Apr/2013 22:11:03] "GET /stats?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [22/Apr/2013 22:11:03] "GET /stats?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
127.0.0.1 - - [22/Apr/2013 22:11:03] "GET /stats?__debugger__=yes&cmd=resource&f=source.png HTTP/1.1" 200 -
127.0.0.1 - - [22/Apr/2013 22:11:03] "GET /stats?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -

更新 2:我推断我的本地测试脚本上的上述错误是因为我忘记了 import stripe .这样做使它运行良好。但是,同样的代码在 Heroku 上运行时会继续产生 500 错误。

更新 3(启示):所以我的 Stripe 仪表板说我确实在创建新用户。因此,我认为可以公平地假设直到(包括)customer = stripe.Customer.create 之前的所有代码作品。那么500错误可能是由我修改数据库引起的吗?

最佳答案

NameError:未定义全局名称“Stripe ”

好像忘记导入 stripe .

关于python - 将 Stripe 与 Flask 集成时,如何防止表单提交到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16159637/

相关文章:

Python dateutil 不解析月份

python - 使用 pd.read_csv 时无法删除 header

python - 使用 Flask 从静态之外的目录提供文件

python - 如何使用flask-login从数据库中注销用户

jQuery:提交动态表单元素时出现问题

python - 如何检查具体方法是否遵守抽象方法的类型提示

python - 狮身人面像 autodoc django 不工作

sqlalchemy - celery + SQLAlchemy : DatabaseError: (DatabaseError) SSL error: decryption failed or bad record mac

javascript - 无法读取表单中未定义错误的属性 'value'

php - 提交表单 - 使用 javascript