I copy & pasted working code into my IDE - now Python is throwing tons of errors

StackOverflow https://stackoverflow.com/questions/22691882

  •  22-06-2023
  •  | 
  •  

문제

I copied and pasted code into my IDE (TextWrangler). Now when I try to run my code, I get a ton of random errors regarding indentation and invalid syntax.

The code worked perfectly before I copied & pasted it from one Django view into another. I'm almost 100% sure the code is still correct in my new view, however, every time it runs I'll get a ton of errors relating to indentation and invalid syntax (even multiline comments like ''' trigger an "invalid syntax on line 234" error.

I've tried switching IDE's over to sublime, and even backspacing all indentations and then retabbing them to no avail. Each time I fix an "error" on one line, a new error on another line is created.

My code is below, please let me know any thoughts on how to fix.

@require_POST   
def pay(request):


if request.method == 'POST':
    form = CustomerForm(request.POST)

    if form.is_valid(): 
    # If the form has been submitted...
    # All validation rules pass


        #get the customer by session'd customer_id
        c = get_object_or_404(Customer, pk = request.session['customer_id'])

        #assign shipping info from POST to the customer object
        c.first_name = request.POST['first_name']
        c.last_name = request.POST['last_name']
        c.street_address = request.POST['street_address']
        c.city = request.POST['city']
        c.state = request.POST['state']
        c.zip = request.POST['zip']

        #assign email info from POST to the customer object

        c.email_address = request.POST['email_address']

        stripe.api_key = REDACTED

        # Get the credit card details submitted by the form
        token = request.POST['stripeToken']


        #tries to save the newly added form data. 
        try:
            #save the new customer object's data
                c.save()

##########   THIS HANDLES CREATING A NEW STRIPE PAYMENT ################                    

    # Create a Customer 
        try:
            customer = stripe.Customer.create(
            card=token,
            plan="monthly",
            email= c.email_address)
            #need to save customer's id (ex: c.stripe_id = token.id)

            #if there's a token error   
        except stripe.error.InvalidRequestError, e:
            pass

        #if the card is declined by Stripe

        except stripe.error.CardError, e:
            body = e.json_body
            err  = body['error']

            print "Status is: %s" % e.http_status
            print "Type is: %s" % err['type']
            print "Code is: %s" % err['code']
            # param is '' in this case
            print "Param is: %s" % err['param']
            print "Message is: %s" % err['message']

        except stripe.error.AuthenticationError, e:
        # Authentication with Stripe's API failed
        # (maybe you changed API keys recently)
            pass

        except stripe.error.APIConnectionError, e:

        # Network communication with Stripe failed
            pass

        except stripe.error.StripeError, e:
        # Display a very generic error to the user, and maybe send
        # yourself an email
            pass

        except Exception, e:
        # Something else happened, completely unrelated to Stripe
            pass    

        return render(request, 'shipment/confirm.html', {'date' : 'April 15, 2014'})


            #passes the context to the template for confirming the customer's data
            #context = { 'email_address' : c.email_address, 'first_name' : c.first_name,
            #   'last_name' : c.last_name, 'street_address' : c.street_address, 
            #   'city' : c.city, 'state' : c.state, 'zip' : c.zip, }

            #return render(request, 'shipment/pay.html', context)

        #If there is a duplicate email it redirects the user back to the form with no error message.  




#If anything else happens, it redirects the user back to the form.      
else:
    form = CustomerForm() # An unbound form
    return render(request, 'shipment/createAccount.html', { 'form': form } )
도움이 되었습니까?

해결책

Here's a couple of screenshots of your code in my editor with tabs (set to 4) and space characters shown in a reddish color. As you can see it contains quite a hodgepodge of the two on many lines. Python is very whitespace sensitive and it's important to be consistent. This is usually handled by configuring your editor to always convert tabs to n whitespace characters (or vice versa, but the former is often preferred).

To fix your problem, re-indent everything using a single method. My editor also has a convert-tabs-to-spaces command which could be used first to simplify the task somewhat.

first screenshot

second screenshot

다른 팁

This is why you should use soft tabs instead of hard tabs. You have at least one line that mixes them (check out the line with c.save()), looking at the edit version of your code. Change your IDE settings to always use spaces or tabs (if you haven't already), I recommend spaces.

See this question for how to view whitespace in sublime to find the offending tab character.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top