【问题标题】:Call variable from cherrypy webhook class从cherrypy webhook类调用变量
【发布时间】:2017-06-15 09:41:14
【问题描述】:

我在 CherryPy 的帮助下为我的电报聊天机器人设置了 webhook。现在我正在尝试处理通过 webhook 收到的数据。我在cherrypy webhook 类中找到了包含所需json 数据的变量。在我的代码中,变量名是 json_string。我需要在我的 python 脚本中到处调用这个变量。我怎么能这样做?谢谢。

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) 

【问题讨论】:

    标签: python python-3.x cherrypy python-telegram-bot telegram-webhook


    【解决方案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:
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多