{"id":24,"date":"2023-11-25T17:00:09","date_gmt":"2023-11-25T22:00:09","guid":{"rendered":"https:\/\/coding101.xyz\/?p=24"},"modified":"2023-12-02T20:02:51","modified_gmt":"2023-12-03T01:02:51","slug":"flask-primer","status":"publish","type":"post","link":"https:\/\/coding101.xyz\/?p=24","title":{"rendered":"Flask Primer"},"content":{"rendered":"\n<p>Flask is a REST engine written in Python. Pretty much like Django, however much simpler. It is very suitable for exposing microservices, with a small number of controllers etc. Here is a sample of how to do stuff with Flask. <\/p>\n\n\n\n<!--more-->\n\n\n\n<p>Import: to use it, you have to install the package with pip, the packge name is flask;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The g object<\/h2>\n\n\n\n<p>The g object is accessed with flask.g and it is an object that is isolated in a request \/ response cycle. You add stuff in it, then get it wherever you need it and then read the previously set attributes. It is like a dictionary, so update it with whatever key \/ value pairs you want. <\/p>\n\n\n\n<p>One very good example: the general configuration data is one thing, the db connection pool is another thing that can be set <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Hello world sample with annotation<\/h2>\n\n\n\n<p>Here is an example of an application with a controller associated with that flask application instance<\/p>\n\n\n\n<!-- HTML generated using hilite.me --><div style=\"background: #ffffff; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;\"><pre style=\"margin: 0; line-height: 125%\"><span style=\"color: #008800; font-weight: bold\">import<\/span> <span style=\"color: #0e84b5; font-weight: bold\">flask<\/span>\n\n\n<span style=\"color: #008800; font-weight: bold\">def<\/span> <span style=\"color: #0066BB; font-weight: bold\">start<\/span>():\n    app <span style=\"color: #333333\">=<\/span> flask<span style=\"color: #333333\">.<\/span>Flask(__name__)\n\n    <span style=\"color: #555555; font-weight: bold\">@app<\/span><span style=\"color: #333333\">.<\/span>route(<span style=\"background-color: #fff0f0\">&#39;\/&#39;<\/span>, methods<span style=\"color: #333333\">=<\/span>[<span style=\"background-color: #fff0f0\">&#39;GET&#39;<\/span>])\n    <span style=\"color: #008800; font-weight: bold\">def<\/span> <span style=\"color: #0066BB; font-weight: bold\">alfa<\/span>():\n        <span style=\"color: #008800; font-weight: bold\">return<\/span> <span style=\"background-color: #fff0f0\">&quot;the response&quot;<\/span>\n\n    app<span style=\"color: #333333\">.<\/span>run(<span style=\"background-color: #fff0f0\">&#39;0.0.0.0&#39;<\/span>, <span style=\"color: #0000DD; font-weight: bold\">8080<\/span>)\n\n\n<span style=\"color: #008800; font-weight: bold\">if<\/span> __name__ <span style=\"color: #333333\">==<\/span> <span style=\"background-color: #fff0f0\">&#39;__main__&#39;<\/span>:\n    start()\n<\/pre><\/div>\n\n\n\n<p>So you see the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>application is defined<\/li>\n\n\n\n<li>@app is related to the flask application stored in variable app, different variable, different annotation<\/li>\n\n\n\n<li>@app.route registers route &#8220;\/&#8221; for method GET for the function alfa<\/li>\n<\/ul>\n\n\n\n<p>In the end all the requests on the server at port 8080 shall be processed by this function<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Hello world sample without annotation<\/h2>\n\n\n\n<p>In the above example there is a small problem: you need to define the function alfa inside a context that has all defined, app, etc. This is an issue: a project with 100 controllers, each exposing different route etc cannot be practically devised in this way: at least each controller function should be defined in a different file, to look more elegant etc. OK. So how do you programmatically add a route to a flask application, well, in this way: <\/p>\n\n\n\n<!-- HTML generated using hilite.me --><div style=\"background: #ffffff; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;\"><pre style=\"margin: 0; line-height: 125%\"><span style=\"color: #008800; font-weight: bold\">import<\/span> <span style=\"color: #0e84b5; font-weight: bold\">flask<\/span>\n\n\n<span style=\"color: #008800; font-weight: bold\">def<\/span> <span style=\"color: #0066BB; font-weight: bold\">alpha<\/span>():\n    <span style=\"color: #008800; font-weight: bold\">return<\/span> <span style=\"background-color: #fff0f0\">&quot;the response&quot;<\/span>\n\n\n<span style=\"color: #008800; font-weight: bold\">def<\/span> <span style=\"color: #0066BB; font-weight: bold\">start<\/span>():\n    app <span style=\"color: #333333\">=<\/span> flask<span style=\"color: #333333\">.<\/span>Flask(__name__)\n\n    app<span style=\"color: #333333\">.<\/span>add_url_rule(<span style=\"background-color: #fff0f0\">&#39;\/&#39;<\/span>, <span style=\"background-color: #fff0f0\">&#39;root&#39;<\/span>, alpha, methods<span style=\"color: #333333\">=<\/span>[<span style=\"background-color: #fff0f0\">&#39;GET&#39;<\/span>])\n\n    app<span style=\"color: #333333\">.<\/span>run(<span style=\"background-color: #fff0f0\">&#39;0.0.0.0&#39;<\/span>, <span style=\"color: #0000DD; font-weight: bold\">8080<\/span>)\n\n\n<span style=\"color: #008800; font-weight: bold\">if<\/span> __name__ <span style=\"color: #333333\">==<\/span> <span style=\"background-color: #fff0f0\">&#39;__main__&#39;<\/span>:\n    start()\n<\/pre><\/div>\n\n\n\n<p>Simple: function alpha is defined elsewhere; it is now in our file for simplicity but typically for bigger applications it is moved in a totally different file. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Setting response status code and headers<\/h2>\n\n\n\n<p>In the method alpha defined above, instead of merely returning a string, better create a response from flask and then modify the state of this response by adding headers and overriding the status code &#8211; which normally is 200, here:<\/p>\n\n\n\n<!-- HTML generated using hilite.me --><div style=\"background: #ffffff; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;\"><pre style=\"margin: 0; line-height: 125%\"><span style=\"color: #008800; font-weight: bold\">def<\/span> <span style=\"color: #0066BB; font-weight: bold\">alpha<\/span>():\n    resp <span style=\"color: #333333\">=<\/span> flask<span style=\"color: #333333\">.<\/span>Response(<span style=\"background-color: #fff0f0\">&quot;the response&quot;<\/span>)\n    resp<span style=\"color: #333333\">.<\/span>headers<span style=\"color: #333333\">.<\/span>update({<span style=\"background-color: #fff0f0\">&#39;Content-Type&#39;<\/span>: <span style=\"background-color: #fff0f0\">&#39;text&#39;<\/span>})\n    resp<span style=\"color: #333333\">.<\/span>status_code <span style=\"color: #333333\">=<\/span> <span style=\"color: #0000DD; font-weight: bold\">206<\/span>\n\n    <span style=\"color: #008800; font-weight: bold\">return<\/span> resp\n<\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Before request and after request<\/h2>\n\n\n\n<p>Many times you need to have something done before any request is being transferred to the route processors. A good example is either to get the actual start of the transaction for metrics, or to get the g object and put some stuff in it to be available for downstream processing. <\/p>\n\n\n\n<p>This is how you define a function that is used before any request: <\/p>\n\n\n\n<!-- HTML generated using hilite.me --><div style=\"background: #ffffff; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;\"><pre style=\"margin: 0; line-height: 125%\"><span style=\"color: #008800; font-weight: bold\">def<\/span> <span style=\"color: #0066BB; font-weight: bold\">call_before_request<\/span>():\n    <span style=\"color: #007020\">print<\/span>(<span style=\"background-color: #fff0f0\">&#39;before request&#39;<\/span>)\n\n\n<span style=\"color: #008800; font-weight: bold\">def<\/span> <span style=\"color: #0066BB; font-weight: bold\">call_after_request<\/span>(response):\n    <span style=\"color: #007020\">print<\/span>(<span style=\"background-color: #fff0f0\">&#39;after request&#39;<\/span>)\n    <span style=\"color: #008800; font-weight: bold\">return<\/span> response\n\n\n<span style=\"color: #008800; font-weight: bold\">def<\/span> <span style=\"color: #0066BB; font-weight: bold\">start<\/span>():\n    app <span style=\"color: #333333\">=<\/span> flask<span style=\"color: #333333\">.<\/span>Flask(__name__)\n\n    app<span style=\"color: #333333\">.<\/span>add_url_rule(<span style=\"background-color: #fff0f0\">&#39;\/&#39;<\/span>, <span style=\"background-color: #fff0f0\">&#39;root&#39;<\/span>, alpha, methods<span style=\"color: #333333\">=<\/span>[<span style=\"background-color: #fff0f0\">&#39;GET&#39;<\/span>])\n    app<span style=\"color: #333333\">.<\/span>before_request_funcs[<span style=\"color: #008800; font-weight: bold\">None<\/span>] <span style=\"color: #333333\">=<\/span> [call_before_request]\n    app<span style=\"color: #333333\">.<\/span>after_request_funcs[<span style=\"color: #008800; font-weight: bold\">None<\/span>] <span style=\"color: #333333\">=<\/span> [call_after_request]\n\n    app<span style=\"color: #333333\">.<\/span>run(<span style=\"background-color: #fff0f0\">&#39;0.0.0.0&#39;<\/span>, <span style=\"color: #0000DD; font-weight: bold\">8080<\/span>)\n<\/pre><\/div>\n\n\n\n<p>Please note:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>you can use very well annotation before_request and after_reqeust but again, the functions that are implemented for this purpose must be defined in a context where app is easy to access<\/li>\n\n\n\n<li>very important, the call after request gets the http response as a parameter and must return this response (after you did or you did not changes to it) or else you get http code 500<\/li>\n\n\n\n<li>definitely the fact that we wrote some print statements inside those function is only for demo purposes; normally you use either logging or you just don&#8217;t print stuff from those functions. <\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Flask is a REST engine written in Python. Pretty much like Django, however much simpler. It is very suitable for exposing microservices, with a small number of controllers etc. Here is a sample of how to do stuff with Flask.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-24","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/coding101.xyz\/index.php?rest_route=\/wp\/v2\/posts\/24","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/coding101.xyz\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/coding101.xyz\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/coding101.xyz\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/coding101.xyz\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=24"}],"version-history":[{"count":5,"href":"https:\/\/coding101.xyz\/index.php?rest_route=\/wp\/v2\/posts\/24\/revisions"}],"predecessor-version":[{"id":99,"href":"https:\/\/coding101.xyz\/index.php?rest_route=\/wp\/v2\/posts\/24\/revisions\/99"}],"wp:attachment":[{"href":"https:\/\/coding101.xyz\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=24"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/coding101.xyz\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=24"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/coding101.xyz\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=24"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}