{"id":249,"date":"2023-05-24T10:49:17","date_gmt":"2023-05-24T10:49:17","guid":{"rendered":"https:\/\/ramansaini.in\/blog\/?p=249"},"modified":"2023-10-17T13:56:34","modified_gmt":"2023-10-17T13:56:34","slug":"serverless-flask-application-from-scratch","status":"publish","type":"post","link":"https:\/\/ramansaini.in\/blog\/serverless-flask-application-from-scratch\/","title":{"rendered":"Creating serverless flask application from scratch."},"content":{"rendered":"\n<p><a href=\"https:\/\/www.serverless.com\/\" target=\"_blank\" rel=\"noopener\">Serverless<\/a> gives the hassle-free deployment and management of the code in both development and production environments, which decreases the development time and cost and also the struggle with deployments.<\/p>\n\n\n\n<p>In AWS, we get many serverless services like <code>Lambda<\/code>, <code>DynamoDB<\/code>, <code>API Gateway<\/code> etc. All of these services are managed by AWS and we do not need to manage the scalability, deployment, load management, etc.<\/p>\n\n\n\n<p>For using the serverless framework, we need <code>serverless.yml<\/code> inside the root directory of the project. In serverless.yml, we will define the application configuration, like, from where the app will be served, what is needed in DynamoDB, how many functions will be needed, and all their names, etc.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Creating the new Flask app with a serverless framework:<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>mkdir flask-serverless-application\ncd flask-serverless-application\nnpm init -f<\/code><\/pre>\n\n\n\n<p>After this, we will need to install the serverless plugins, which is, <code>serverless-wsgi<\/code>, which is needed to run the deployed Python application on lambda. Another one is, <code>serverless-python-requirements<\/code>, which will handle all the python package requirements.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm install --save-dev serverless-wsgi serverless-python-requirements<\/code><\/pre>\n\n\n\n<p>Now, we can start with the flask application. We will create <code>app.py<\/code> file, where we will write our Flask API.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\t\n# app.py\n \nfrom flask import Flask, make_response\napp = Flask(__name__)\n \n@app.route(\"\/\")\ndef root_route():\n    return make_response(({'message' : \"Running Serverless Flask App.\"}))\n<\/code><\/pre>\n\n\n\n<p>The above-written app will return a JSON in response to the API call, which will return a message key with the value <code>Running Serverless Flask App.<\/code> <\/p>\n\n\n\n<p>Now we will create <code>serverless.yml<\/code> file <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>service: flask-serverless-app\n\nplugins:\n  - serverless-python-requirements\n  - serverless-wsgi\n\ncustom:\n  wsgi:\n    app: app.app\n    packRequirements: false\n  pythonRequirements:\n    dockerizePip: non-linux\n\n\npackage:\n  exclude:\n    - node_modules\/**\n    - venv\/**\n\n\nprovider:\n  name: aws\n  runtime: python3.8\n  stage: dev\n  region: ap-southeast-2\n  iamManagedPolicies:\n  - arn:aws:iam::aws:policy\/AmazonDynamoDBFullAccess\n  versionFunctions: false\n  timeout: 29\n\nfunctions:\n  app:\n    handler: wsgi.handler\n    events:\n      - http: ANY \/\n      - http: 'ANY {proxy+}'\n        cors: true\n<\/code><\/pre>\n\n\n\n<p>In the above code, we have defined <code>code.wsgi.app<\/code> as <code>app.app<\/code>, which will tell wsgi from where the Flask app is needed to be served.  All the required plugins are defined inside <code>plugins<\/code>. And inside <code>functions<\/code> we define handled as <code>wsgi.handler<\/code>, as we have used <code>serverless-wsgi<\/code> plugin, which will help in serving all the APIs through flask on the HTTP events.<\/p>\n\n\n\n<p>To run the code, we will need to create the python environment and then run the flask app locally first and then deploy the code.<\/p>\n\n\n\n<p>First, create the virtual environment and install the dependencies<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>virtualenv venv --python=python3\nsource venv\/bin\/activate<\/code><\/pre>\n\n\n\n<p>When the virtual environment is active, then we will run the installations and then freeze the packages in requirements.txt.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>(venv) $ pip install flask\n(venv) $ pip freeze &gt; requirements.txt<\/code><\/pre>\n\n\n\n<p>Now, we will test running the code on the local machine. First, we will add the was keys using aws-cli.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>aws configure<\/code><\/pre>\n\n\n\n<p>This can also be done by editing the credentials file in the aws root folder at `~\/.aws\/credentials`. Here you can create AWS profiles, which can be used to to deploy in multiple accounts and for multiple project development from one system.<\/p>\n\n\n\n<p>Then we will run the code on the local environment.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sls wsgi serve<\/code><\/pre>\n\n\n\n<p>This should run the code on port <code>5000<\/code>.<\/p>\n\n\n\n<p>Now to deploy the code, we will run the command:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sls deploy<\/code><\/pre>\n\n\n\n<p>This command should return URLs of the API gateway, from where the API can be accessed directly, which should be something like:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>https:&#47;&#47;ny931jc3f1.execute-api.ap-southeast-2.amazonaws.com\/dev<\/code><\/pre>\n\n\n\n<p>From this URL, we will be able to hit any API created in the Flask application. We can create as many APIs, and we do not need to make any changes in the serverless.yml file, as we have defined any endpoint in the HTTP events. <br>This is a simple Flask serverless application. We can achieve many things using Flask serverless. We can connect to different databases, and server applications and create many high-level applications.<br>In case you need more insights, contact me from the contact page.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Serverless gives the hassle-free deployment and management of the code in both development and production environments, which decreases the development time and cost and also the struggle with deployments. In AWS, we get many serverless services like Lambda, DynamoDB, API Gateway etc. All of these services are managed by AWS and we do not need&hellip;&nbsp;<a href=\"https:\/\/ramansaini.in\/blog\/serverless-flask-application-from-scratch\/\" class=\"\" rel=\"bookmark\">Read More &raquo;<span class=\"screen-reader-text\">Creating serverless flask application from scratch.<\/span><\/a><\/p>\n","protected":false},"author":2,"featured_media":281,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"neve_meta_sidebar":"","neve_meta_container":"","neve_meta_enable_content_width":"","neve_meta_content_width":0,"neve_meta_title_alignment":"","neve_meta_author_avatar":"","neve_post_elements_order":"","neve_meta_disable_header":"","neve_meta_disable_footer":"","neve_meta_disable_title":"","_themeisle_gutenberg_block_has_review":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[6],"tags":[16,14,17],"class_list":["post-249","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-programming","tag-lambda","tag-python","tag-serverless"],"jetpack_featured_media_url":"https:\/\/ramansaini.in\/blog\/wp-content\/uploads\/2023\/10\/Netathon-web-crawling-1.png","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/ramansaini.in\/blog\/wp-json\/wp\/v2\/posts\/249","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ramansaini.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ramansaini.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ramansaini.in\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/ramansaini.in\/blog\/wp-json\/wp\/v2\/comments?post=249"}],"version-history":[{"count":4,"href":"https:\/\/ramansaini.in\/blog\/wp-json\/wp\/v2\/posts\/249\/revisions"}],"predecessor-version":[{"id":284,"href":"https:\/\/ramansaini.in\/blog\/wp-json\/wp\/v2\/posts\/249\/revisions\/284"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/ramansaini.in\/blog\/wp-json\/wp\/v2\/media\/281"}],"wp:attachment":[{"href":"https:\/\/ramansaini.in\/blog\/wp-json\/wp\/v2\/media?parent=249"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ramansaini.in\/blog\/wp-json\/wp\/v2\/categories?post=249"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ramansaini.in\/blog\/wp-json\/wp\/v2\/tags?post=249"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}