How to Create a Python Web Framework with Lambda, Serverless, & DynamoDB?
Welcome to the tutorial page of ChromeInfotech. Now in this guide, I will tell you how to develop a Python Web Framework with Serverless, Lambda, & DynamoDB.
Let me give you a small intro to our company! ChromeInfotech is a leading Python Web Framework Development organization and having expertise in PHP, Python, Django, Mean-Stack, SharePoint, BlockChain App Development, Ruby-On-Rails, Dot.NET, ASP.NET, React Native, AngularJS and a lot more.
We have delivered more than 160 application using python Web Framework. If you are looking for the best python development company or looking to hire a Python Web Framework developer, contact us.
We have a deal for you!
Now let me start the Python Web Framework tutorial, here we go!
Our current python web framework tooling can work flawlessly with the Serverless Framework. How about we go over how to utilize the Python web framework Flask to deploy a Serverless REST API.
In this stroll through, we will:
Deploy a straightforward Python Web Framework API endpoint
- Add a DynamoDB table and two parameters to make and recover a User object
- Set up way explicit routing for increasingly granular measurements and checking
- Configure your condition for local development for quicker development experience.
In case you as of now have a Flask application that you need to change over to Serverless, jump to the Converting a current Flask application segment beneath.
If you need to skirt the walkthrough and begin with a wholly configured format, look at the Using the Quick Start Template area beneath.
Let’s get started | Python Web Framework
To begin, you’ll need the Serverless Framework installed. You’ll additionally require your condition configured with AWS credentials.
- Creating and deploying a solitary endpoint
- Let’s begin by using a single parameter.
To start with, make another directory with a package.json document:
At that point, install a couple of dependencies. We’re going to utilize the serverless-WSGI module for arranging the API Gateway occasion type into the WSGI design that Flask anticipates. We’ll additionally use the serverless-python-prerequisites module for dealing with our Python Web Framework packages on deployment.
In case you need a more profound plunge on the serverless-python-necessities module, look at our past post on taking care of Python Web Framework packages with Serverless.
With our libraries installed, how about we compose our Flask application. Make a document app.py with the accompanying content:
This is an extremely straightforward application that profits “Hi World!” when a solicitation comes in on the root way/. It’s the model application appeared on Flask’s greeting page without any adjustments.
To get this application deployed,
Python Web Framework: Make a serverless.yml in the working directory:
Note
A past variant of this post set dockerizePip: valid rather than dockerizePip: non-Linux. You’ll require serverless-python-necessities v3.0.5 or higher for this alternative.
This is a really fundamental arrangement. We’ve made one functional application. The handler will be handler work from the WSGI module. Note that this module will be added to our deployment package by the serverless-wsgi module. We design our application’s entry point in the custom square under the wsgi area.
We pronounce that our application’s entry point is app.app, which implies the application object in the app.py module.
For our function’s occasions set up, we’ve utilized an expansive way coordinating with the goal that all solicitations on this space are steered to this capacity. The majority of the HTTP routing rationale will be done inside the Flask application.
The exact opposite thing we have to do is handle our Python Web Framework packages. The serverless-python-necessities module searches for a requirements.txt record in our working directory and installs them into our deployment package. How about we build that requirements.txt record.
To begin with, make a practical situation and actuate it. I’m utilizing Python3 in my serverless.yml, so I’m indicating that here too:
If you need a walkthrough on using Python Web Framework virtual environment, look at Kenneth Reitz’s walkthrough.
At that point, install the Flask package with pip, and spare your conditions in requirements.txt:
Python Web Framework | Deploy the functions:
After a moment, the console will demonstrate your endpoints in the Service Information area. Explore to that course in your program:
You nailed it—a genuine, live application on the Web!
Including a DynamoDB table along with the REST-like endpoints
Completing a “Welcome World!” is fun. However, your application should continue a type of state to be helpful. How about we include a DynamoDB table as our support store.
For this essential precedent, suppose we’re putting away Users in a database. We need to store them by userId, which is an exceptional identifier for a specific client.
To begin with, we’ll have to arrange our serverless.yml to arrangement the table. This includes three sections:
- Provisioning the table into the resources area;
- Including the proper permissions of IAM; and
- Passing the name if the table as the environment variable so the functions not able to use it.
Python Web Framework | Customize your serverless.yml to look as given here:
We provisioned the table in the assets segment utilizing CloudFormation punctuation. We additionally included IAM consents for our capacities under the iamRoleStatements bit of the supplier square.
At last, we passed the table name as the earth variable USERS_TABLE in the earth bit of the supplier square.
Presently, how about we update our application to utilize the table. We’ll actualize two endpoints: POST/clients to make another client, and GET/clients/{userId} to get data on a specific client.
Python Web Framework | Update your app.py as pursues:
Also, the base “Hello World” endpoint, we presently have two new endpoints:
- GET/clients/:userId for getting a User
- POST/clients for making another User
We’ve included a boto3 reliance, so we should install that into our virtual condition and update our necessities in requirements.txt:
Python Web Framework | Now, deploy the service as well as test it!
We can utilize the curl for the given examples. Configure the BASE_DOMAIN variable to the domain and base path. It can be easier to reuse:
Then, now make a user:
Friendly—we have created a new user! Then, let’s retrieve a user along with GET /users/:userId` endpoint:
This is undoubtedly not an undeniable REST API, and you’ll need to include things like mistake dealing with, confirmation, and extra business rationale. This gives a framework in which you can work to set up those things.
Python Web Framework | Path-specific routing
We should look again at our capacity arrangement in serverless.yml:
We’re sending all traffic on the area to our application and giving Flask a chance to deal with the aggregate of the routing rationale. There is an advantage to this—you don’t need to hang every one of my courses and capacities physically. You can likewise restrain the effect of cold-begins on delicately utilized classes.
But, We’re sending all traffic on the area to our application and giving Flask a chance to deal with the aggregate of the routing rationale. There is an advantage to this—you don’t need to hang every one of my courses and capacities physically. You can likewise restrain the effect of cold-begins on delicately utilized classes.
When each route is taken care of by an alternate Lambda work –
At that point you can see:
- How ordinarily each route has invoked
- How much issues and errors you have for every route
- What amount of time each route takes (and the amount of money you can save if you made the route quicker)
Fortunately, you can, in any case, get these things on the off chance that you need them! You can arrange your serverless.yml with the goal that various courses are steered to multiple instances of your capacity.
Each function case will have similar code, yet they’ll be sectioned for measurements purposes:
Presently, all solicitations to GET/clients/:userId will be dealt with by the getUser occurrence of your application, and all tenders to POST/clients/will be taken care of by the createUser occasion.
For some other solicitations, they’ll be dealt with by the principle application occurrence of your function. Once more, none of this is required, and it’s a touch of an overweight arrangement; every particular endpoint will incorporate the full application code for your different parameters.
In any case, it’s a decent harmony between speed of development by utilizing the devices you’re used to, alongside the per-endpoint granularity that serverless application designs give.
Local development configuration along with the Serverless offline plugin
When building up an application, it’s pleasant to quickly emphasize by creating and testing locally as opposed to completing a full deploy between changes. In this area, we’ll spread how to arrange your condition for local development.
The incredible thing about the serverless-wsgi module is that it incorporates a worked in the answer for local development. To begin the local server, run SLS wsgi serve:
Then move to the root page on localhost:5000 in the browser:
It is working! If you roll out an improvement in your app.py document, it will be refreshed whenever you hit your endpoint. This quickly improves development time.
While this works effectively for a stateless endpoint like “Hi World!”, it’s somewhat trickier for our/clients endpoints that collaborate with a database.
Fortunately, there’s a module for doing local development with a local DynamoDB emulator. We’ll utilize the serverless-dynamodb-local module for this.
Python Web Framework | Now, you need to install the plugin:
At that point, we should add the module to our serverless.yml. We’ll likewise include some config in the custom square with the goal that it locally makes our tables characterized in the resources block:
Now, run the command to install the DynamoDB local:
At last, we have to roll out some little improvements to our application code. While instantiating our DynamoDB customer, we’ll include some unique design in case we’re in a local, disconnected condition.
When growing locally, the serverless-WSGI module sets a situation variable of IS_OFFLINE to genuine, so we’ll utilize that to deal with our config. Change the start of app.py to the accompanying:
Presently, our DynamoDB customer is configured to use DynamoDB local. In case we’re running locally, or utilize the default alternatives if running in Lambda.
Now see if it works.
You’ll require two different terminal windows now. In your first window, start-up DynamoDB local:
In the next window, you need to start up the local WSGI server:
Now, run the curl command from before hit our local endpoint and make a user:
And after that retrieve a user:
Yeah, it works same as it did on the Lambda.
This local setup can genuinely accelerate your work process while as yet enabling you to imitate a nearby guess of the Lambda environment.
Converting the current Flask application
In case you as of now have a current Flask application, it’s anything but difficult to change over to a Serverless-accommodating application. Do the accompanying steps:
- Install serverless-wsgi & serverless-python-requirements packages — npm install –save serverless-wsgi serverless-python-requirements
- Configure the serverless.yml:
You must have the serverless.yml it can look like this:
Ensure that the value for the app under custom. wsgi square is configured for your application. It ought to be <module.instance>, where the module is the name of the Python Web Framework record with your Flask example, and the case is the name of the variable with your Flask application.
Deploy the function along with SLS deploy!
Note:
If you utilize different resources (databases, credentials, and so on.), you’ll have to ensure those make it into your application. Look at our other material on overseeing insider facts & API keys with Serverless.
Utilizing a Quick Start Template
In case you don’t have a current Flask application to change over, yet you need a well-organized beginning stage for a request, you can look at our serverless-flask application format.
To utilize it, you’ll need the Serverless Framework installed. You’ll additionally require your condition configured with AWS credentials.
With the Framework installed, utilize the SLS install order to clone the layout venture. At that point, change into the directory and run a post-setup content to arrange it as expected:
Then, run SLS deploy and hit the main web page to view your starter application:
Congratulations! You have successfully used your flask app. There are lots of things that you can build with Serverless &Python. The limit is only your imagination.
I hope this tutorial will help you to guide the best ways to create a REST API along with Lambda, Serverless, & DynamoDB. In case you need expert assistance for your app, you can get in touch with us.
As a leading Python Web Framework and Mobile App Development company, we always encourage our client to get the best product. We have quality software development team that can give you a great shot to your application. They also perform integration with Chat SDK, Map SDK, Cloud Server, App Analytics, Payment Gateway and so on.
If you found this post helpful, do let us know in the comment section. Keep connecting, keep sharing the knowledge and keep coding.
Good Luck!