4
I have a doubt in my code.
I am using an example code and tried to apply to create a json template on the local machine. Follow what is working. It is located [at this link]( https://github.com/svet4/shipping-costs-sample):
#!/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 doesn’t 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 Mistake that comes to me is this:
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’d appreciate it.
But strange to give this problem, being that in the other code the spacing is the same no? I’m using the sublime to run the code.
– Fabio Niglio
It is. See my edition if it helps you.
– Leonel Sanches da Silva