I set webhook to my telegram chatbot with the help of CherryPy. And now I am trying to handle data which I receive through webhook. I found the variable in cherrypy webhook class which contains needed json data. In my code, the variable name is json_string. I need to call this variable everywhere in my python script. How I can do that? Thanks.
class WebhookServer(object):
@cherrypy.expose
def index(self):
if 'content-length' in cherrypy.request.headers and \
'content-type' in cherrypy.request.headers and \
cherrypy.request.headers['content-type'] == 'application/json':
length = int(cherrypy.request.headers['content-length'])
json_string = cherrypy.request.body.read(length).decode("utf-8")
update = telebot.types.Update.de_json(json_string)
bot.process_new_updates([update])
return ''
else:
raise cherrypy.HTTPError(403)
答案 0 :(得分:1)
让我们考虑简化的HTTP处理程序,其中json由json_in
工具自动解码为dict,结果存储在cherrypy.request.json
。
您可以在外部模块中编写一些函数,比如utils.py
,将其与服务器代码一起导入并传递给:
==>> your_server.py
<< ==
from utils import process_telegram_webhook
class WebhookServer(object):
@cherrypy.expose
@cherrypy.tools.json_in()
def index(self):
req = cherrypy.request
incoming_dict_object = req.json
process_telegram_webhook(incoming_dict_object)
return ''
# ...
==>> utils.py
<< ==
def process_telegram_webhook(data):
# ... do smth with json data from telegram: