Python connection problem Webhook

4

I have a question in my code.

I'm using a sample code and tried to apply it to create a json template on the local machine. Follows what is working. It is located [in this link] ( link ):

#!/usr/bin/env python

import urllib
import json
import os

from flask import Flask
from flask import request
from flask import make_response

# Flask app should start in global layout
app = Flask(__name__)


@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeWebhookResult(req)

    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

def makeWebhookResult(req):
    if req.get("result").get("action") != "shipping.cost":
        return {}
    result = req.get("result")
    parameters = result.get("parameters")
    zone = parameters.get("shipping-zone")

    cost = {'Europe':100, 'North America':200, 'South America':300, 'Asia':400, 'Africa':500}

    speech = "The cost of shipping to " + zone + " is " + str(cost[zone]) + " euros."

    print("Response:")
    print(speech)

    return {
        "speech": speech,
        "displayText": speech,
        #"data": {},
        # "contextOut": [],
        "source": "apiai-onlinestore-shipping"
    }


if __name__ == '__main__':
    port = int(os.getenv('PORT', 5000))

    print "Starting app on port %d" % port

    app.run(debug=True, port=port, host='0.0.0.0')

Code that does not work

#!/usr/bin/env python

import urllib
import json
import os
import firebase
import urllib3

from flask import Flask
from flask import request
from flask import make_response

# Flask app should start in global layout
app = Flask(__name__)


@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeWebhookResult(req)

    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

def makeWebhookResult(req):

    action = req.get("result").get("action")


    if (action != "curso.valor") and (action != "translate.text") and (action !="planeta.temperatura" and (action != "pedido.gravar"):
        return {}
    result = req.get("result")
    parameters = result.get("parameters")

    # Curso

    if(action == "curso.valor"):
        curso = parameters.get("curso")

        #cost = {'R':100, 'Python':200, 'Machine Learning':300, 'Hadoop':400 }
        from firebase import firebase
        firebase = firebase.FirebaseApplication('https://dsa-bot-fabio.firebaseio.com', None)
        preco = firebase.get("/Cursos", Curso+"/Preco")

    if curso:
        speech = "O valor do curso " + curso + " e " + str(preco) + " reais."
    else:
        speech = "Qual Curso? Escolha entre: " + str(cost.keys())

     #tradução
    if(action =="translate.text"):
        text = parameters.get("text")
        language = parameters.get("to").get("lang")
        speech = text + " em " + language + " eh " + text[::-1]

    #Temperatura planeta
    if(action == "planeta.temperatura"):
        planeta = parameters.get("planeta")
        if(planeta != "Marte"):
            speech = "Ainda não medimos temperatura para " + planeta
        else:
            url="http://marsweather.ingenology.com/v1/latest/?format=json"
            http = urllib3.PoolManager()
            r=http.request('GET', url)
            data = json.loads(r.data.decode('utf-8'))
            temperatura_minima= str(data.get("Report").get("min_temp"))
            temperatura_maxima=str(data.get("Report").get("max_temp"))
            speech = "Previsao para {}: minima de {} e maxima de {}".format(planeta, temperatura_minima temperatura_maxima)

    #Gravação de pedido
    if(action =="pedido.gravar")
        from firebase import firebase
        from firebase.firebase import FirebaseApplication, FirebaseAuthentication


        authentication = FirebaseAuthentication('QuRhyzqXXn7s5pX2gEcdLnzC3o66mi2rmb92DcwO', True, True)
        firebase = firebase.FirebaseApplication('https://dsa-bot-fabio.firebaseio.com', authentication)

        parameters =  result.get("context")[0].get("parameters")
        nome = parameters.get("nome")
        tamanho_pao = parameters.get("tamanho_pao")
        tipo_pao = parameters.get("tipo_pao")
        recheio = parameters.get("recheio")
        queijo = "não"
        dobro_queijo = "não"
        if(parameters.get("dobro_queijo")):
            queijo = "sim"
            dobro_queijo = parameters.get("dobro_queijo")

        pedido = {"nome": nome, "tamanho_pao": tamanho_pao, "tipo_pao": tipo_pao, "queijo": queijo, "dobro_queijo": dobro_queijo, "recheio": recheio}
        result = firebase.post("/Pedidos", pedido)
        speech = "Anote seu pedido: {}. Volte sempre!".format(result['name'])







    print("Response:")
    print(speech)

    return {
        "speech": speech,
        "displayText": speech,
        #"data": {},
        # "contextOut": [],
        "source": "apiai-onlinestore-shipping"
    }


if __name__ == '__main__':
    port = int(os.getenv('PORT', 5000))

    print ("Starting app on port %d" % port)

    app.run(debug=True, port=port, host='0.0.0.0')

The error that arises for me is the following:

File "C:\Users\fabio\dsa-bot-fabio\app.py", line 37
if (action != "curso.valor") and (action != "translate.text") and (action !="planeta.temperatura" and (action != "pedido.gravar"):

^
IndentationError: unindent does not match any outer indentation level
[Finished in 0.4s with exit code 1]

If anyone can help, I appreciate it.

    
asked by anonymous 15.05.2017 / 06:13

1 answer

3

The error is clear, caused by something treacherous:

IndentationError: unindent does not match any outer indentation level

In this line:

File "C:\Users\fabio\dsa-bot-fabio\app.py", line 37
if (action != "curso.valor") and (action != "translate.text") and (action !="planeta.temperatura" and (action != "pedido.gravar"):

Possibly this if is indented with symbols different from the others. For example, file indentation is done with 4 spaces, but you used tab on the line.

Some editors have the option to swap any tab command with spaces to avoid this error. It would be nice to enable this option.

In any case, delete the indentation from the line and do it again. If it fails with tab , do so only by using spaces.

Correcting in Sublime Text:

  • View - > Indentation
  • Where it says
    • Indent using spaces [x]
    • Tab width : 2
  • Uncheck Convert Indentation to Tabs
    • Tab width : 4
    • Convert Indentation to Spaces
Use Ctrl + I to reframe the code.

    
15.05.2017 / 06:22