Web development learning notes -- abstract out the Page class

Posted by ChompGator on Sun, 01 Dec 2019 06:46:50 +0100

review

  • Through the content of the previous articles, we have built a simple Web application based on the Flask framework. The code of server.py is as follows


    from flask import Flask, make_response
    from flask.views import MethodView
    app = Flask(__name__)
    
    class IndexHandler(MethodView):
        def get(self):
            resp = make_response('It is a GET request')
            resp.headers['Strict-Transport-Security'] = 'max-age=15768000; includeSubDomains; preload'
            return resp
    
    if __name__ == '__main__':
        app.add_url_rule('/', view_func=IndexHandler.as_view('index'))
        context = ('./server.cer', './server.key')
        app.run(port=443, host='0.0.0.0', debug=True, threaded=True, ssl_context=context)

Abstract out the Page class

  • Because we will use HSTS and other common features in the Handler of each Page in the future, we will extract them and abstract them into a Page class. Modify server.py as follows


    from flask import Flask, make_response
    from flask.views import MethodView
    app = Flask(__name__)
    
    class Page(MethodView):
        def render(self, resp):
            resp.headers['Strict-Transport-Security'] = 'max-age=15768000; includeSubDomains; preload'
            return resp
    
    class IndexHandler(Page):
        def get(self):
            content = 'It is a GET request'
            return self.render(content)
    
    if __name__ == '__main__':
        app.add_url_rule('/', view_func=IndexHandler.as_view('index'))
        context = ('./server.cer', './server.key')
        app.run(port=443, host='0.0.0.0', debug=True, threaded=True, ssl_context=context)

Extract other common properties

  • get_args()


    Args usually appears in GET requests. For example, https://www.google.com/search?q=awesome appears in the address bar when Google searches. The content after? Is args in the form of key value. Corresponding to the previous example, key is Q and value is awesome. If there are multiple groups of key values, use & connection in the middle, such as? Q = awesome & type = server. This form is easy to make We think of Python's dictionary structure, dict File , Flask is through ImmutableMultiDict To store args, we can add the get_args() method to the Page class

    from flask import request
    class Page(MethodView):
        def get_args(self, key):
            return request.args.get(key)

    In this way, we can get the parameters in the user request by calling get ENU args(), for example, chestnut


    class AwesomeHandler(Page):
        def get(self):
            if self.get_args('q') == 'awesome':
                # do something
                return 'This is an awesome page!'
  • Similarly, we can add other features to the Page class, such as get_date(), get_referer(), get_cookies(), etc. the prepared Page class is as follows


    from flask import request
    from datetime import datetime, date
    
    class Page(MethodView):
        def render(self, resp):
            resp.headers['Strict-Transport-Security'] = 'max-age=15768000; includeSubDomains; preload'
            return resp
    
        def get_args(self, key):
            return request.args.get(key)
    
        def get_date(self, year=0, month=0, day=0):
            if year and month and day:
                return date(year, month, day)
            else:
                return date.today()
    
        def get_referer(self):
            return request.headers.get('referer')
    
        def get_cookies(self):
            return request.cookies

Reference material

Topics: Python Google