34
loading...
This website collects cookies to deliver better user experience
What we are going to cover
- System setup
- Project setup
- Implementation
- Testing the API's
Mac OS and Python 3.X, VS Code, Postgresql and Git.
brew install python
python --version
pip install virtualenv
mkdir flash-sample
cd flask-sample
ls
__pycache__ env
python -m venv env
source env/bin/activate
pip install flask_sqlalchemy
pip install psycopg2
python -m pip freeze requirements.txt
click==8.0.1
Flask==2.0.1
Flask-SQLAlchemy==2.5.1
greenlet==1.1.1
itsdangerous==2.0.1
Jinja2==3.0.1
MarkupSafe==2.0.1
psycopg2==2.9.1
SQLAlchemy==1.4.25
Werkzeug==2.0.1
git init.
Initialized empty Git repository in /PROJECT_FOLDER/.git/
git s
On branch master
No commits yet
Untracked files:
(use "git add file..." to include in what will be committed)
env/
requirements.txt
nothing added to commit but untracked files present (use "git add" to track)
touch .gitignore
git add.
git commit -m "Initial commit"
touch app.py
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from flask import jsonify
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///hands_contact'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
'postgresql://usernamr:password@server/database_name'
class SampleUser(db.Model):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(80), nullable=False)
last_name = db.Column(db.String(120), nullable=False)
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
if __name__ == '__main__':
db.create_all()
app.run()
def creation():
content=request.get_json(silent=True)
try:
db.session.add(SampleUser(content["first_name"],
content["last_name"]))
db.session.commit()
return'Ok', 200
exceptExceptionase:
return'Invalid request', 400
@app.route("/create_users", methods=['POST'])
@app.route('/users', methods=['GET'])
def home():<br /> data = []
for user in SampleUser.query.all():
data.append(
{ "id": user.id,
"first_name": user.first_name,
"last_name": user.last_name
})
return jsonify(total_users_count=len(data), data=data, status=200)
from flask_marshmallow import Marshmallow
ma = Marshmallow(app)
class SampleUserSchema(ma.Schema):
class Meta:
fields = ("id", "first_name")
sample_user_schema = SampleUserSchema()
sample_user_schema = SampleUserSchema(many=True)
@app.route('/users', methods=['GET'])
def listing():
all_notes = SampleUser.query.all()
return jsonify(sample_user_schema.dump(all_notes)), 200
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask import jsonify
# Database ORM Configs
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///hands_contact'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
ma = Marshmallow(app)
# User model for contact us
class SampleUser(db.Model):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(80), nullable=False)
last_name = db.Column(db.String(120), nullable=False)
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
# JSON response serializer
class SampleUserSchema(ma.Schema):
class Meta:
fields = ("id", "first_name")
sample_user_schema = SampleUserSchema()
sample_user_schema = SampleUserSchema(many=True)
# Simple Dashboard
@app.route('/users', methods=['GET'])
def listing():
all_notes = SampleUser.query.all()
return jsonify(sample_user_schema.dump(all_notes)), 200
# Contact us POST API
@app.route("/create_users", methods=['POST'])
def creation():
content = request.get_json(silent=True)
try:
db.session.add(SampleUser(content["first_name"], content["last_name"]))
db.session.commit()
return 'Ok', 200
except Exception as e:
return 'Invalid request', 400
# Invoke the application
if __name__ == '__main__':
db.create_all()
app.run()
flask run
curl -X POST -d '{ "first_name": "Badsha", "last_name": "Manik" }' http://127.0.0.1:5000/create_users -H 'Content-Type: application/json' -H 'Accept: application/json'
Ok
curl http://127.0.0.1:5000/users
[{"first_name":"Vijay","id":1},{"first_name":"" 1","id":2},{"first_name":"Ajith","id":3}]