Search code examples
pythonpython-3.xcouchdbcloudant

How to update server_doc if curent revision doesn't match


I have an API created in flask which gets some file in base64 format. Using couchdb, I keep track whether the server side version is same as current document version. Here is still what I could write:

@app.route('/dbupload', methods=['POST'])
def approved():
    if request.method == "POST":
        if request.json:
            if 'data' in request.json:
                if request.files.get("file"):
                    data = request.json['data']
                    username = "username"
                    pwd = "password"
                    file_obj = request.files["file"]
                    file_name = file_obj.filename
                    if file_name.lower().endswith('.csv'):
                        doc_id = data["_id"]
                        doc_rev = data["_rev"]
                        try:
                            with couchdb(username, pwd, url=os.genenv("COUCHDB_HOST"), connect=True, auto_renew=True, timeout=120, adapter=HTTPAdapter(pool_connections=15, pool_maxsize=100)) as client:
                                try:
                                    filedata = file_obj.read()
                                    session = client.session()
                                except Exception as e:
                                    return abort(500)
                                try:
                                    this_db = client['calhoun']
                                except Exception as e:
                                    return jsonify({"status": False})
                                try:
                                    server_doc = this_db[doc_id]
                                    if server_doc["_rev"] == doc_rev:
                                        server_doc["data"] = data["data"]
                                    else:
                                        # How to update data
                                        return abort(500)
                                except KeyError:
                                    logger.error("No such document")
                                except Exception as e:
                                    return abort(500)
                                return jsonify({"status": True})
                        except Exception as e:
                            return abort(401)
                else:
                    return abort(400)
            else:
                return abort(400)
        else:
            return abort(400)
    else:
        return abort(501)

Now I need to add inside else part if I need to update the server if there is a mismatch of the revision. How to do it?


Solution

  • @app.route('/dbupload', methods=['POST'])
    def approved():
        if request.method != "POST":
            return abort(501)
        if not request.json:
            return abort(400)
        if 'data' not in request.json:
            return abort(400)
        if not request.files.get("file"):
            return abort(400)
        data = request.json['data']
        username = "username"
        pwd = "password"
        file_obj = request.files["file"]
        file_name = file_obj.filename
        if file_name.lower().endswith('.csv'):
            doc_id = data["_id"]
            doc_rev = data["_rev"]
            try:
                with couchdb(username, pwd, url=os.genenv("COUCHDB_HOST"), connect=True, auto_renew=True, timeout=120, adapter=HTTPAdapter(pool_connections=15, pool_maxsize=100)) as client:
                    try:
                        filedata = file_obj.read()
                        session = client.session()
                    except Exception as e:
                        return abort(500)
                    try:
                        this_db = client['calhoun']
                    except Exception as e:
                        return jsonify({"status": False})
                    try:
                        server_doc = this_db[doc_id]
                        # Since your fetching the latest doc from db
                        # No need to use/check the rev if ur going to
                        # update the data anyway
                        server_doc["data"] = data["data"]
                        server_doc.save() # will throw conflict (409) if some _rev mismatch happens
                    except KeyError:
                        logger.error("No such document")
                    except Exception as e:
                        return abort(500)
                    return jsonify({"status": True})
            except Exception as e:
                return abort(401)