34
loading...
This website collects cookies to deliver better user experience
core
. Navigate to this folder from the terminal and create a new file called server.py
, add another file called Procfile
after doing this your project folder should look like the following:core/
|__server.py
|__Procfile
virtualenv
virtualenv server
source server/bin/activate
.\server\scripts\activate
Flask
and Flask-Sqlalchemy
,gunicorn
, Flask-CORS
and Flask-Marhsmallow
as shown below:pip install flask flask-sqlalchemy flask-cors gunicorn flask-marshmallow marshmallow-sqlalchemy
server.py
file and add the following lines of code:from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_cors import CORS
import os
basedir = os.path.abspath(os.getcwd())
# instantiate new flask app
app = Flask(__name__)
# app config for database
app.config['SQLALCHEMY_DATABASE_URI'] = f"sqlite:///{basedir}/demo.db"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
CORS(app)
# database models
db = SQLAlchemy(app)
ma = Marshmallow(app)
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
price = db.Column(db.Float)
description = db.Column(db.Text)
quantity = db.Column(db.Integer)
class ProductSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Product
load_instance = True
products_schema = ProductSchema(many=True)
@app.route('/get_products')
def fetch_products():
all_ = Product.query.all()
return jsonify(products_schema.dump(all_)), 200
@app.route('/add_product', methods=['POST'])
def add_note():
data = request.get_json(force=True)
new_product = Product(
name=data['name'],
price=data['price'],
description=data['description'],
quantity=data['quantity']
)
try:
db.session.add(new_product)
db.session.commit()
return {
"status": "Success"
}, 200
except Exception as e:
print(e)
return {
"status": "Error"
}, 500
@app.route('/edit_product', methods=['PUT'])
def edit_note():
data = request.get_json(force=True)
# find product
product = Product.query.filter_by(id=data['id']).first()
for key, value in data.items():
setattr(product, key, value)
try:
db.session.commit()
return {
"status": "Success"
}, 200
except Exception:
return {
"status": "Error"
}, 500
@app.route('/delete_product', methods=['DELETE'])
def delete_note():
data = request.get_json(force=True)
# find product
product = Product.query.filter_by(id=data['id']).first()
db.session.delete(product)
try:
db.session.commit()
return {
"status": "Success"
}, 200
except Exception:
return {
"status": "Error"
}, 500
if __name__=="__main__":
db.create_all()
app.run(debug=True)
server
file, we import the required dependencies, create a new flask app instance, add some necessary configurations including "cors" and database config, and specified three endpoints to which we can send requests.python server.py
Heroku
.Heroku is a PaaS cloud service provider that helps us to deploy application really easily without having to worry about the kind of machine to provision for the software and how to scale them - Heroku does all that on our behalf, all we have to do is tell them howto run our application, and we do that using the Procfile
that we created earlier on.
heroku login
heroku create appsmith-server
appsmith-server
, you can give yours any name as well. Since Heroku doesn't allow shared names you might have to come up with a much cooler name.Procfile
, so open the Procfile
and add the following to it:web: python gunicorn:app
Procfile
deployment specification follows the format of[process_type]: [command]
"process_type"
be of type "web"
, meaning the application to be deployed is a web application. The "command"
to run the application has also been specified (its supposed to run the flask server using gunicorn). What this means is that when Heroku wants to spin up an instance of our application it looks at the Procfile
and uses the instructions there to run the application.requirements.txt
filepip freeze>requirements.txt
requirements.txt
, so you should find that it created a new file for you by that name that has the following contents, or at least similar contents:click==8.0.3
colorama==0.4.4
Flask==2.0.2
Flask-Cors==3.0.10
Flask-SQLAlchemy==2.5.1
greenlet==1.1.2
itsdangerous==2.0.1
Jinja2==3.0.2
MarkupSafe==2.0.1
six==1.16.0
SQLAlchemy==1.4.26
Werkzeug==2.0.2
git
, so head back to the terminal ad initialize a git repository in the project folder using the init
command, and then add
and commit
the changes to version control history.heroku git:remote -a <Your-heroku-app-name>
git push heroku main
(your-app-name).herokuapp.com
. Copy this link and paste it in a browser, and add any of the url prefix for any of the endpoints on the serer like /add_product
for exampletable
widget unto the right area, this table will display a business's product inventory, and the details of each one:Text
and Input
widgets which will help us to name and create the input fields for the form. For this form we need fields that will hold details of each product including the name
, description
, price
, and quantity
. So drag text labels and input widgets for each field, as shown below:Add new
and Update
, as they will serve to create new products and update existing onesDatasources
section click on the create new API
option to add a new API to communicate with from your appsmnith applicationadd_product
that sends a POST request to add a new product to the database. In the body add the following to create a payload that contains data from the form.{
"name": {{Input1.text}},
"price": {{Input2.text}},
"description": {{Input3.text}},
"quantity": {{Input4.text}}
}
Add new
button so that when we edit the form and click Add new
the this api is called. Head over to the Add new
widget and bring up the settings pane, and under the Actions
section choose the onClick
option, and choose the option to Execute a query
and then select the AddProduct
api from the list of options showed.onClick
action is the onSuccess
option, and this will trigger on success of the request sent when the button is clicked. We want the table to be updated when we add a new product from the form, so we will create a new api to fill the table with data from the database, and then call that api whenever we add a new product from the form as the onSuccess
action.getProducts
that sends a GET request to the server endpoint of get_products
as shown below:onSuccess
action of the Add new
button from earlier and choose the option to Execute a query
and then select the getProducts
api from the list of options showed.Table Data
, you want to clear out the hard-coded data in it and add the following instead:{{getProducts.data}}
Add new
button on the form the new data should create a new row in the table.Default value
property of the input widget and add moustache syntax to fetch data on the selected row and add it to the field. Default value
entry on the Name
field to prefill it with the name of the product on a selected row.{{Table1.selectedRow.name}}
Data type
property for the input fields: quantity
, and price
to type of Number
. This way we can edit any product by clicking on it making the changes in the form and then use the Update
button on the form to submit the edit to the database.updateProduct
, that sends a PUT
request to the server on the /edit_product
endpoint. Add the following to the body of the request:{
"id": {{Table1.selectedRow.id}},
"name": {{Input1.text}},
"price": {{Input2.text}},
"description": {{Input3.text}},
"quantity": {{Input4.text}}
}
update
button just like we did for the Add new
button as an onClick
action, also specify the getProducts
api as an onSuccess
action so that the table reloads the data. Now we can click on any row and edit a product from the form and it'll be automatically updated on the table.deleteProduct
api that sends a DELETE
request to the server on the /delete_product
endpoint, with a payload defined as follows:{
"id": {{Table1.selectedRow.id}}
}
delete
button and add an onSuccess
action to call the getProducts
api once again like before.