Python flask.request.data() Examples

The following are 30 code examples of flask.request.data(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.request , or try the search function .
Example #1
Source Project: wechatpy   Author: wechatpy   File: app.py    License: MIT License 7 votes vote down vote up
def wechat():
    signature = request.args.get("msg_signature", "")
    timestamp = request.args.get("timestamp", "")
    nonce = request.args.get("nonce", "")

    crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId)
    if request.method == "GET":
        echo_str = request.args.get("echostr", "")
        try:
            echo_str = crypto.check_signature(signature, timestamp, nonce, echo_str)
        except InvalidSignatureException:
            abort(403)
        return echo_str
    else:
        try:
            msg = crypto.decrypt_message(request.data, signature, timestamp, nonce)
        except (InvalidSignatureException, InvalidCorpIdException):
            abort(403)
        msg = parse_message(msg)
        if msg.type == "text":
            reply = create_reply(msg.content, msg).render()
        else:
            reply = create_reply("Can not handle this for now", msg).render()
        res = crypto.encrypt_message(reply, nonce, timestamp)
        return res 
Example #2
Source Project: ServerSan   Author: BennyThink   File: webhook.py    License: Apache License 2.0 7 votes vote down vote up
def create():
    try:
        d = json.loads(request.data)
    except ValueError:
        return json.dumps({'status': 1, 'info': 'request failed.'})

    current_ts = time.time()
    _id = False
    d.update(timestamp=current_ts)

    perm = ts_can_insert(d.get('auth'), current_ts) and token_can_insert(d.get('auth'))

    if perm:
        _id = col.insert_one(d).inserted_id
    if _id:
        return json.dumps({'status': 0, 'info': 'success'})
    else:
        return json.dumps({'status': 2, 'info': 'op too frequent or invalid token.'}) 
Example #3
Source Project: social-relay   Author: jaywink   File: views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def receive_public():
    if not request.data:
        return abort(404)

    # Queue to rq for processing
    public_queue.enqueue("workers.receive.process", request.data, timeout=app.config.get("RELAY_WORKER_TIMEOUT"))

    # Log statistics
    log_receive_statistics(request.remote_addr)

    # return 200 whatever
    data = {
        'result': 'ok',
    }
    js = json.dumps(data)
    return Response(js, status=200, mimetype='application/json') 
Example #4
Source Project: dataiku-contrib   Author: dataiku   File: app.py    License: Apache License 2.0 6 votes vote down vote up
def display_new_token():    
    data = {
        "username"     : request.args.get("powerbi-username"),
        "password"     : request.args.get("powerbi-password"),
        "client_id"    : request.args.get("powerbi-client-id"),
        "client_secret": request.args.get("powerbi-client-secret"),
        "resource"     : request.args.get("powerbi-resource",   "https://analysis.windows.net/powerbi/api"),
        "grant_type"   : request.args.get("powerbi-grant-type", "password"),
        "scope"        : request.args.get("powerbi-scope",      "openid")
    }
    response = requests.post('https://login.microsoftonline.com/common/oauth2/token', data=data)
    o = {}
    #o["powerbi-auth-response"] = response.json()
    o["powerbi-access-token"] = response.json().get("access_token")    
    return json.dumps(o)


# Helper functions to interact with DSS Project Variables 
Example #5
Source Project: dataiku-contrib   Author: dataiku   File: app.py    License: Apache License 2.0 6 votes vote down vote up
def get_token():
    
    # Read in the existing conf
    dss = dataiku.api_client()
    project = dss.get_project(dataiku.default_project_key())
    variables = project.get_variables()["standard"]
    conf = variables.get("powerbi-settings", None)   
    
    # Decrypt
    key = request.args.get("api-key")
    pbi = {}
    pbi["username"]      = conf["username"]
    pbi["password"]      = decrypt_string(conf["password"], key)
    pbi["client_id"]     = conf["client_id"]
    pbi["client_secret"] = decrypt_string(conf["client_secret"], key)
    pbi["resource"]      = conf["resource"]
    pbi["grant_type"]    = conf["grant_type"]
    pbi["scope"]         = conf["scope"]
    
    # Get the token
    response = requests.post('https://login.microsoftonline.com/common/oauth2/token', data=pbi)
    o = {}
    o["token"] = response.json().get("access_token") 
    
    return json.dumps(o) 
Example #6
Source Project: maple-file   Author: honmaple   File: router.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def post(self):
        '''
        新建相册
        '''
        post_data = request.data
        user = request.user
        name = post_data.pop('name', None)
        description = post_data.pop('description', None)
        if name is None:
            return HTTP.BAD_REQUEST(message='相册名称不能为空')
        album = Album(name=name, user=user)
        if description is not None:
            album.description = description
        album.save()
        serializer = AlbumSerializer(album)
        return HTTP.OK(data=serializer.data) 
Example #7
Source Project: maple-file   Author: honmaple   File: router.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def put(self, pk):
        '''
        修改相册
        '''
        post_data = request.data
        user = request.user
        name = post_data.pop('name', None)
        description = post_data.pop('description', None)
        album = Album.query.filter_by(id=pk, user=user).get_or_404('相册不存在')
        if name is not None:
            album.name = name
        if description is not None:
            album.description = description
        album.save()
        serializer = AlbumSerializer(album)
        album.delete()
        return HTTP.OK(data=serializer.data) 
Example #8
Source Project: maple-file   Author: honmaple   File: router.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get(self):
        '''
        获取图片列表
        '''
        query_dict = request.data
        user = request.user
        page, number = self.page_info
        keys = ['name', 'description']
        order_by = gen_order_by(query_dict, keys)
        filter_dict = gen_filter_dict(query_dict, keys, user=user)
        album = query_dict.pop('album', None)
        if album is not None:
            filter_dict.update(album__id=album)
        images = Image.query.filter_by(
            **filter_dict).order_by(*order_by).paginate(page, number)
        serializer = ImageSerializer(images.items, True)
        pageinfo = PageInfo(images)
        return HTTP.OK(data=serializer.data, pageinfo=pageinfo) 
Example #9
Source Project: maple-file   Author: honmaple   File: router.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def put(self, pk):
        '''
        修改图片信息
        '''
        post_data = request.data
        user = request.user
        name = post_data.pop('name', None)
        description = post_data.pop('description', None)
        image = Image.query.filter_by(id=pk, user=user).get_or_404('图片不存在')
        if name is not None:
            image.name = name
            image.url = os.path.join(image.path, name)
        if description is not None:
            image.description = description
        image.save()
        serializer = ImageSerializer(image)
        return HTTP.OK(data=serializer.data) 
Example #10
Source Project: maple-file   Author: honmaple   File: router.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def delete(self, pk):
        '''
        删除图片
        '''
        user = request.user
        image = Image.query.filter_by(id=pk, user=user).get_or_404('图片不存在')
        serializer = ImageSerializer(image)
        img_path = os.path.join(current_app.config['UPLOAD_FOLDER_ROOT'],
                                image.url)
        # 删除原图
        if os.path.exists(img_path):
            os.remove(img_path)
        # 删除缩略图
        thumb_path = os.path.join(current_app.config['UPLOAD_FOLDER_ROOT'],
                                  image.url.replace('photo', 'thumb'))
        if os.path.exists(thumb_path):
            os.remove(thumb_path)
        image.delete()
        return HTTP.OK(data=serializer.data) 
Example #11
Source Project: rucio   Author: rucio   File: subscription.py    License: Apache License 2.0 6 votes vote down vote up
def get(self, account=None, name=None):
        """
        Retrieve a subscription.

        .. :quickref: Subscription; Get subscriptions.

        :param account: The account name.
        :param name: The subscription name.
        :resheader Content-Type: application/x-json-stream
        :status 200: OK.
        :status 401: Invalid Auth Token.
        :status 404: Subscription Not Found.
        :status 406: Not Acceptable.
        :status 500: Internal Error.
        :returns: Line separated list of dictionaries with subscription information.
        """
        try:
            data = ""
            for subscription in list_subscriptions(name=name, account=account):
                data += dumps(subscription, cls=APIEncoder) + '\n'
            return Response(data, content_type="application/x-json-stream")
        except SubscriptionNotFound as error:
            return generate_http_error_flask(404, 'SubscriptionNotFound', error.args[0])
        except Exception as error:
            return error, 500 
Example #12
Source Project: rucio   Author: rucio   File: subscription.py    License: Apache License 2.0 6 votes vote down vote up
def get(self, name=None):
        """
        Retrieve a subscription by name.

        .. :quickref: SubscriptionName; Get subscriptions by name.

        :param name: The subscription name.
        :resheader Content-Type: application/x-json-stream
        :status 200: OK.
        :status 401: Invalid Auth Token.
        :status 404: Subscription Not Found.
        :status 406: Not Acceptable.
        :status 500: Internal Error.
        :returns: Line separated list of dictionaries with subscription information.
        """
        try:
            data = ""
            for subscription in list_subscriptions(name=name):
                data += dumps(subscription, cls=APIEncoder) + '\n'
            return Response(data, content_type="application/x-json-stream")
        except SubscriptionNotFound as error:
            return generate_http_error_flask(404, 'SubscriptionNotFound', error.args[0])
        except Exception as error:
            return error, 500 
Example #13
Source Project: rucio   Author: rucio   File: replica.py    License: Apache License 2.0 6 votes vote down vote up
def get(self, scope, name):
        """
        List dataset replicas.

        .. :quickref: DatasetReplicas; List dataset replicas.

        :query deep: Flag to ennable lookup at the file level.
        :resheader Content-Type: application/x-json-stream
        :status 200: OK.
        :status 401: Invalid auth token.
        :status 406: Not Acceptable.
        :status 500: Internal Error.
        :returns: A dictionary containing all replicas information.
        """
        deep = request.args.get('deep', False)
        try:
            data = ""
            for row in list_dataset_replicas(scope=scope, name=name, deep=deep):
                data += dumps(row, cls=APIEncoder) + '\n'
            return Response(data, content_type='application/x-json-stream')
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            return error, 500 
Example #14
Source Project: rucio   Author: rucio   File: lifetime_exception.py    License: Apache License 2.0 6 votes vote down vote up
def get(self):
        """
        Retrieve all exceptions.

        .. :quickref: LifetimeException; Get all exceptions.

        :resheader Content-Type: application/x-json-stream
        :status 200: OK.
        :status 401: Invalid Auth Token.
        :status 404: Lifetime Exception Not Found.
        :status 406: Not Acceptable.
        :status 500: Internal Error.
        """
        try:
            data = ""
            for exception in list_exceptions():
                data += dumps(exception, cls=APIEncoder) + '\n'
            return Response(data, content_type="application/x-json-stream")
        except LifetimeExceptionNotFound as error:
            return generate_http_error_flask(404, 'LifetimeExceptionNotFound', error.args[0])
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            return error, 500 
Example #15
Source Project: rucio   Author: rucio   File: did.py    License: Apache License 2.0 6 votes vote down vote up
def get(self, scope, name):
        """
        Return all associated rules of a file.

        .. :quickref: AssociatedRules; List associated rules of DID.

        :resheader Content-Type: application/x-json-stream
        :param scope: The scope of the data identifier.
        :param name: The name of the data identifier.
        :status 200: DID found
        :status 401: Invalid Auth Token
        :status 404: DID not found
        :status 406: Not Acceptable
        :status 500: Database Exception
        :returns: List of associated rules.
        """
        try:
            data = ""
            for rule in list_associated_replication_rules_for_file(scope=scope, name=name):
                data += dumps(rule, cls=APIEncoder) + '\n'
            return Response(data, content_type="application/x-json-stream")
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            return error, 500 
Example #16
Source Project: rucio   Author: rucio   File: rule.py    License: Apache License 2.0 6 votes vote down vote up
def get(self, rule_id):
        """ get locks for a given rule_id.

        .. :quickref: ReplicaLocks; get locks by rule id

        :status 200: Rule found
        :status 406: Not Acceptable
        :status 500: Database Exception
        :returns: JSON dict containing informations about the requested user.
        """
        try:
            locks = get_replica_locks_for_rule_id(rule_id)
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            return error, 500

        data = ""
        for lock in locks:
            data += dumps(lock, cls=APIEncoder) + '\n'

        return Response(data, content_type="application/x-json-stream") 
Example #17
Source Project: rucio   Author: rucio   File: rule.py    License: Apache License 2.0 6 votes vote down vote up
def get(self, rule_id):
        """ get history for a given rule_id.

        .. :quickref: RuleHistory; get rule history by id

        :resheader Content-Type: application/x-json-stream
        :status 200: Rule found
        :status 406: Not Acceptable
        :status 500: Database Exception
        :returns: JSON dict containing informations about the requested user.
        """
        try:
            history = list_replication_rule_history(rule_id)
        except RucioException as error:
            return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            return error, 500

        data = ""
        for hist in history:
            data += dumps(hist, cls=APIEncoder) + '\n'
        return Response(data, content_type="application/x-json-stream") 
Example #18
Source Project: wechatpy   Author: wechatpy   File: app.py    License: MIT License 5 votes vote down vote up
def wechat():
    signature = request.args.get("signature", "")
    timestamp = request.args.get("timestamp", "")
    nonce = request.args.get("nonce", "")
    encrypt_type = request.args.get("encrypt_type", "raw")
    msg_signature = request.args.get("msg_signature", "")
    try:
        check_signature(TOKEN, signature, timestamp, nonce)
    except InvalidSignatureException:
        abort(403)
    if request.method == "GET":
        echo_str = request.args.get("echostr", "")
        return echo_str

    # POST request
    if encrypt_type == "raw":
        # plaintext mode
        msg = parse_message(request.data)
        if msg.type == "text":
            reply = create_reply(msg.content, msg)
        else:
            reply = create_reply("Sorry, can not handle this for now", msg)
        return reply.render()
    else:
        # encryption mode
        from wechatpy.crypto import WeChatCrypto

        crypto = WeChatCrypto(TOKEN, AES_KEY, APPID)
        try:
            msg = crypto.decrypt_message(request.data, msg_signature, timestamp, nonce)
        except (InvalidSignatureException, InvalidAppIdException):
            abort(403)
        else:
            msg = parse_message(msg)
            if msg.type == "text":
                reply = create_reply(msg.content, msg)
            else:
                reply = create_reply("Sorry, can not handle this for now", msg)
            return crypto.encrypt_message(reply.render(), nonce, timestamp) 
Example #19
Source Project: wechatpy   Author: wechatpy   File: app.py    License: MIT License 5 votes vote down vote up
def wechat():
    signature = request.args.get("signature", "")
    timestamp = request.args.get("timestamp", "")
    nonce = request.args.get("nonce", "")
    echo_str = request.args.get("echostr", "")
    encrypt_type = request.args.get("encrypt_type", "")
    msg_signature = request.args.get("msg_signature", "")

    print("signature:", signature)
    print("timestamp: ", timestamp)
    print("nonce:", nonce)
    print("echo_str:", echo_str)
    print("encrypt_type:", encrypt_type)
    print("msg_signature:", msg_signature)

    try:
        check_signature(TOKEN, signature, timestamp, nonce)
    except InvalidSignatureException:
        abort(403)
    if request.method == "GET":
        return echo_str
    else:
        print(f"Raw message: \n{request.data}")
        crypto = WeChatCrypto(TOKEN, EncodingAESKey, AppId)
        try:
            msg = crypto.decrypt_message(request.data, msg_signature, timestamp, nonce)
            print(f"Descypted message: \n{msg}")
        except (InvalidSignatureException, InvalidAppIdException):
            abort(403)
        msg = parse_message(msg)
        if msg.type == "text":
            reply = create_reply(msg.content, msg)
        else:
            reply = create_reply("Sorry, can not handle this for now", msg)
        return crypto.encrypt_message(reply.render(), nonce, timestamp) 
Example #20
Source Project: PickTrue   Author: winkidney   File: taskserver.py    License: MIT License 5 votes vote down vote up
def task_submit():
    """
    :return:
    """
    resp = request.data
    server.requester.submit_response(
        resp
    )
    return jsonify({}) 
Example #21
Source Project: insightface   Author: deepinsight   File: app.py    License: MIT License 5 votes vote down vote up
def get_image(data):
  image = None
  if 'url' in data:
    url = data['url']
    if url.startswith('http'):
      resp = urllib.urlopen(url)
      image = np.asarray(bytearray(resp.read()), dtype="uint8")
      image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    else:
      image = cv2.imread(url, cv2.IMREAD_COLOR)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = image_resize(image)
  elif 'data' in data:
    _bin = data['data']
    if _bin is not None:
      if not isinstance(_bin, list):
        _bin = base64.b64decode(_bin)
        _bin = np.fromstring(_bin, np.uint8)
        image = cv2.imdecode(_bin, cv2.IMREAD_COLOR)
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        image = image_resize(image)
      else:
        image = []
        for __bin in _bin:
          __bin = base64.b64decode(__bin)
          __bin = np.fromstring(__bin, np.uint8)
          _image = cv2.imdecode(__bin, cv2.IMREAD_COLOR)
          _image = cv2.cvtColor(_image, cv2.COLOR_BGR2RGB)
          _image = image_resize(_image)
          image.append(_image)

  return image 
Example #22
Source Project: insightface   Author: deepinsight   File: app.py    License: MIT License 5 votes vote down vote up
def ver():
  try:
    data = request.data
    values = json.loads(data)
    source_image = get_image(values['source'])
    if source_image is None:
      print('source image is None')
      return '-1'
    assert not isinstance(source_image, list)
    print(source_image.shape)
    target_image = get_image(values['target'])
    if target_image is None:
      print('target image is None')
      return '-1'
    #print(target_image.shape)
    if not isinstance(target_image, list):
      target_image = [target_image]
    #print('before call')
    #ret = model.is_same_id(source_image, target_image)
    ret = model.sim(source_image, target_image)
  except Exception as ex:
    print(ex)
    return '-1'

  #return str(int(ret))
  print('sim', ret)
  return "%1.3f"%ret 
Example #23
Source Project: dataiku-contrib   Author: dataiku   File: app.py    License: Apache License 2.0 5 votes vote down vote up
def save_new_token():
    
    # Read in the conf and get a token
    conf = json.loads(request.data)
    key = conf["api-key"]
    pbi = {}
    pbi["username"]      = conf["powerbi-username"]
    pbi["password"]      = conf["powerbi-password"]
    pbi["client_id"]     = conf["powerbi-client-id"]
    pbi["client_secret"] = conf["powerbi-client-secret"]
    pbi["resource"]      = conf["powerbi-resource"]
    pbi["grant_type"]    = conf["powerbi-grant-type"]
    pbi["scope"]         = conf["powerbi-scope"]
    response = requests.post('https://login.microsoftonline.com/common/oauth2/token', data=pbi)
        
    # Save the token
    data = pbi
    data["password"]       = encrypt_string(conf["powerbi-password"], key)
    data["client_secret"]  = encrypt_string(conf["powerbi-client-secret"], key)
    data["access_token"]   = response.json().get("access_token")
    data["created_at"]     = str(datetime.datetime.utcnow())
    data["dss_port"]       = os.environ["DKU_BACKEND_PORT"]
    data["webapp_project"] = conf["webapp-url"].split("/")[-3]
    data["webapp_id"]      = conf["webapp-url"].split("/")[-2]
    data["project_key"]    = os.environ["DKU_CURRENT_PROJECT_KEY"]
    
    set_dss_variables(
        dataiku.default_project_key(),
        data
    )
    # Send back some results
    o = {}
    o["powerbi-access-token"] = data["access_token"]
    return json.dumps(o) 
Example #24
Source Project: maple-file   Author: honmaple   File: router.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def post(self):
        '''
        登陆
        '''
        post_data = request.data
        username = post_data.pop('username', None)
        password = post_data.pop('password', None)
        remember = post_data.pop('remember', True)
        if username and password:
            user = User.query.filter_by(username=username).first()
            if user and user.check_password(password):
                user.login(remember)
                serializer = UserSerializer(user)
                return HTTP.OK(data=serializer.data)
        return HTTP.UNAUTHORIZED(message='用户名或密码错误') 
Example #25
Source Project: maple-file   Author: honmaple   File: router.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get(self):
        '''
        获取相册列表
        '''
        query_dict = request.data
        user = request.user
        page, number = self.page_info
        keys = ['name', 'description']
        order_by = gen_order_by(query_dict, keys)
        filter_dict = gen_filter_dict(query_dict, keys, user=user)
        albums = Album.query.filter_by(
            **filter_dict).order_by(*order_by).paginate(page, number)
        serializer = AlbumSerializer(albums.items, True)
        pageinfo = PageInfo(albums)
        return HTTP.OK(data=serializer.data, pageinfo=pageinfo) 
Example #26
Source Project: maple-file   Author: honmaple   File: router.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get(self, pk):
        '''
        获取具体相册
        '''
        user = request.user
        album = Album.query.filter_by(id=pk, user=user).get_or_404('相册不存在')
        serializer = AlbumSerializer(album)
        return HTTP.OK(data=serializer.data) 
Example #27
Source Project: maple-file   Author: honmaple   File: router.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get(self, pk):
        '''
        显示图片
        '''
        user = request.user
        image = Image.query.filter_by(id=pk, user=user).get_or_404('图片不存在')
        serializer = ImageSerializer(image)
        return HTTP.OK(data=serializer.data) 
Example #28
Source Project: sparkflow   Author: lifeomic   File: HogwildSparkModel.py    License: MIT License 5 votes vote down vote up
def put_deltas_to_server(delta, master_url='localhost:5000'):
    """
    This updates the master parameters. We just use simple pickle serialization here.
    """
    requests.post('http://{0}/update'.format(master_url), data=pickle.dumps(delta, -1)) 
Example #29
Source Project: Penny-Dreadful-Tools   Author: PennyDreadfulMTG   File: api.py    License: GNU General Public License v3.0 5 votes vote down vote up
def process_github_webhook() -> Response:
    if request.headers.get('X-GitHub-Event') == 'push':
        payload = json.loads(request.data)
        expected = 'refs/heads/{0}'.format(current_app.config['branch'])
        if payload['ref'] == expected:
            try:
                subprocess.check_output(['git', 'fetch'])
                subprocess.check_output(['git', 'reset', '--hard', 'origin/{0}'.format(current_app.config['branch'])])
                try:
                    subprocess.check_output([sys.executable, '-m', 'pip', 'install', '-U', '--user', '-r', 'requirements.txt', '--no-cache'])
                except subprocess.CalledProcessError:
                    pass
                try:
                    subprocess.check_output(['npm', 'run-script', 'build'])
                except subprocess.CalledProcessError:
                    pass
                import uwsgi  # pylint: disable=import-outside-toplevel
                uwsgi.reload()
                return return_json({'rebooting': True})
            except ImportError:
                pass
    return return_json({
        'rebooting': False,
        'commit-id': current_app.config['commit-id'],
        'current_branch': current_app.config['branch'],
        'ref': payload['ref'],
        'expected': expected
        }) 
Example #30
Source Project: calibre-web   Author: janeczku   File: gdrive.py    License: GNU General Public License v3.0 5 votes vote down vote up
def on_received_watch_confirmation():
    log.debug('%r', request.headers)
    if request.headers.get('X-Goog-Channel-Token') == gdrive_watch_callback_token \
            and request.headers.get('X-Goog-Resource-State') == 'change' \
            and request.data:

        data = request.data

        def updateMetaData():
            log.info('Change received from gdrive')
            log.debug('%r', data)
            try:
                j = json.loads(data)
                log.info('Getting change details')
                response = gdriveutils.getChangeById(gdriveutils.Gdrive.Instance().drive, j['id'])
                log.debug('%r', response)
                if response:
                    if sys.version_info < (3, 0):
                        dbpath = os.path.join(config.config_calibre_dir, "metadata.db")
                    else:
                        dbpath = os.path.join(config.config_calibre_dir, "metadata.db").encode()
                    if not response['deleted'] and response['file']['title'] == 'metadata.db' \
                       and response['file']['md5Checksum'] != hashlib.md5(dbpath):
                        tmpDir = tempfile.gettempdir()
                        log.info('Database file updated')
                        copyfile(dbpath, os.path.join(tmpDir, "metadata.db_" + str(current_milli_time())))
                        log.info('Backing up existing and downloading updated metadata.db')
                        gdriveutils.downloadFile(None, "metadata.db", os.path.join(tmpDir, "tmp_metadata.db"))
                        log.info('Setting up new DB')
                        # prevent error on windows, as os.rename does on exisiting files
                        move(os.path.join(tmpDir, "tmp_metadata.db"), dbpath)
                        calibre_db.setup_db(config, ub.app_DB_path)
            except Exception as e:
                log.exception(e)
        updateMetaData()
    return ''