My First Patch: Cool Coding


My first patch was to differentiate between the accept headers using flask’s methods and returns content accordingly. It means that if the accept header is in “application/json” it should return the content in JSON format and in case of “text/html”, it should return “HTML” format and for other cases it should return ‘JSON’ by default.
 
I was given a link to use it as reference. There is a function request_wants_json that returns true if accept header is “application/json”. otherwise it returns false. By default  an HTTP request is rendered as html in browser. But, we can provide accept header on our wish and can give preference to other mimetype. I came to know that there are 17 mimetypes in total and many more are coming.

Initially i thought why not check for “text/html” header’s type using flask method i.e. flask.request.headers.get(‘Accept’) and then return content according that. But my mentor suggested not to use that as they wanted codes in more engineered way and extensible one 🙂

So I moved on the flask accept header snippet and modified ‘request_wants_json’ function to ‘request_wants_html’ so as to put html on  higher quality than ‘application/json’ and ‘text/plain’.So, it returns true in case of “text/html” and false otherwise.
def request_wants_html():     
    best = flask.request.accept_mimetypes.best_match(['application/json',\
             'text/html','text/plain'])     
    return best=='text/html' and flask.request.accept_mimetypes[best]\ 
             > (flask.request.accept_mimetypes['application/json'] or
             \ (flask.request.accept_mimetypes['text/plain']) 
I also made the following changes in the /datagrepper/app.py. It uses request_wants_html to obtain the desired output.
# return HTML content else json
if request_wants_html():         
   return "HTML Format"     
else:         
   return flask.Response(response=body,                
                         status=status,                
                         mimetype=mimetype) 
It returns the “HTML Format” in case if accept header  is “text/html” otherwise it returns the JSON format. Later on i will have to add something in this HTML part to make it return some beautiful HTML content. 
 
This is how I submitted my first patch. It was a nice beginning. 
Cheers!

2 thoughts on “My First Patch: Cool Coding

Leave a comment