1
\$\begingroup\$

I have this code to POST and save a digest to redis, and retrieve it from redis on a GET. This uses Python and Flask, of course.

@app.route("/message/<shasum>", methods=['GET'])
def get_message(shasum):
    message = redis.get(shasum)
    if message:
        return jsonify(message=message)
    else:
        abort(404)

@app.route("/digest", methods=['POST'])
def get_digest():
    if request.headers['Content-Type'] == 'application/json':
        message = json.loads(request.data)
        sha = sha256(message['message'].encode('utf-8')).hexdigest()
        redis.set(sha, message['message'])
        return (jsonify(digest=sha), 201)
    else:
        return (jsonify(message="Bad Request"), 400 )

what else can I do to improve the performance of this little piece of code, specifically on the POST side and can it be improved on the GET side too?

\$\endgroup\$
2
\$\begingroup\$

from werkzeug.wrappers import BaseRequest
...

try:
    data = request.get_json()
except BadRequest:
    return (jsonify(message="Bad Request"), 400)

message = data['message']
digest = sha256(message.encode('utf-8')).hexdigest()
redis.set(sha, message)
return (jsonify(digest=digest), 201)
  • Use better variable names, message can be replaced with data and message variable can be used to store the actual message from data. Similarly sha can be replaced with digest.

  • The else blocks in both functions can be removed as the corresponding if blocks are already returning. I personally find lesser indented code much easier to read and it also helps in keeping the Cyclomatic complexity low.

  • There are no check against the data being passed by the user, for example message can be passed as an empty string, None, integer etc. You probably want to use some sort of validation here.

\$\endgroup\$
  • \$\begingroup\$ thanks. I was looking to optimize on the redis side. cause right now, irrespective of whether the digest exists in redis, I always write to redis. that seems kinda expensive. thoughts around that? \$\endgroup\$ – adele dazim May 19 '17 at 14:01
  • \$\begingroup\$ @adeledazim Setting and getting the key in Redis is an O(1) operation. You probably want to profile your function to see which part is the slowest. \$\endgroup\$ – Ashwini Chaudhary May 19 '17 at 16:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.